PackageManagerService.java revision 7c4c55dcb6d386fb3843069a02c177df66df09c7
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.PARSE_IS_OEM;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
106import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
107import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
108import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
109import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
110import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
111import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
112import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
113import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
117import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
118
119import android.Manifest;
120import android.annotation.IntDef;
121import android.annotation.NonNull;
122import android.annotation.Nullable;
123import android.app.ActivityManager;
124import android.app.AppOpsManager;
125import android.app.IActivityManager;
126import android.app.ResourcesManager;
127import android.app.admin.IDevicePolicyManager;
128import android.app.admin.SecurityLog;
129import android.app.backup.IBackupManager;
130import android.content.BroadcastReceiver;
131import android.content.ComponentName;
132import android.content.ContentResolver;
133import android.content.Context;
134import android.content.IIntentReceiver;
135import android.content.Intent;
136import android.content.IntentFilter;
137import android.content.IntentSender;
138import android.content.IntentSender.SendIntentException;
139import android.content.ServiceConnection;
140import android.content.pm.ActivityInfo;
141import android.content.pm.ApplicationInfo;
142import android.content.pm.AppsQueryHelper;
143import android.content.pm.AuxiliaryResolveInfo;
144import android.content.pm.ChangedPackages;
145import android.content.pm.ComponentInfo;
146import android.content.pm.FallbackCategoryProvider;
147import android.content.pm.FeatureInfo;
148import android.content.pm.IDexModuleRegisterCallback;
149import android.content.pm.IOnPermissionsChangeListener;
150import android.content.pm.IPackageDataObserver;
151import android.content.pm.IPackageDeleteObserver;
152import android.content.pm.IPackageDeleteObserver2;
153import android.content.pm.IPackageInstallObserver2;
154import android.content.pm.IPackageInstaller;
155import android.content.pm.IPackageManager;
156import android.content.pm.IPackageManagerNative;
157import android.content.pm.IPackageMoveObserver;
158import android.content.pm.IPackageStatsObserver;
159import android.content.pm.InstantAppInfo;
160import android.content.pm.InstantAppRequest;
161import android.content.pm.InstantAppResolveInfo;
162import android.content.pm.InstrumentationInfo;
163import android.content.pm.IntentFilterVerificationInfo;
164import android.content.pm.KeySet;
165import android.content.pm.PackageCleanItem;
166import android.content.pm.PackageInfo;
167import android.content.pm.PackageInfoLite;
168import android.content.pm.PackageInstaller;
169import android.content.pm.PackageManager;
170import android.content.pm.PackageManagerInternal;
171import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
172import android.content.pm.PackageParser;
173import android.content.pm.PackageParser.ActivityIntentInfo;
174import android.content.pm.PackageParser.Package;
175import android.content.pm.PackageParser.PackageLite;
176import android.content.pm.PackageParser.PackageParserException;
177import android.content.pm.PackageStats;
178import android.content.pm.PackageUserState;
179import android.content.pm.ParceledListSlice;
180import android.content.pm.PermissionGroupInfo;
181import android.content.pm.PermissionInfo;
182import android.content.pm.ProviderInfo;
183import android.content.pm.ResolveInfo;
184import android.content.pm.ServiceInfo;
185import android.content.pm.SharedLibraryInfo;
186import android.content.pm.Signature;
187import android.content.pm.UserInfo;
188import android.content.pm.VerifierDeviceIdentity;
189import android.content.pm.VerifierInfo;
190import android.content.pm.VersionedPackage;
191import android.content.res.Resources;
192import android.database.ContentObserver;
193import android.graphics.Bitmap;
194import android.hardware.display.DisplayManager;
195import android.net.Uri;
196import android.os.Binder;
197import android.os.Build;
198import android.os.Bundle;
199import android.os.Debug;
200import android.os.Environment;
201import android.os.Environment.UserEnvironment;
202import android.os.FileUtils;
203import android.os.Handler;
204import android.os.IBinder;
205import android.os.Looper;
206import android.os.Message;
207import android.os.Parcel;
208import android.os.ParcelFileDescriptor;
209import android.os.PatternMatcher;
210import android.os.Process;
211import android.os.RemoteCallbackList;
212import android.os.RemoteException;
213import android.os.ResultReceiver;
214import android.os.SELinux;
215import android.os.ServiceManager;
216import android.os.ShellCallback;
217import android.os.SystemClock;
218import android.os.SystemProperties;
219import android.os.Trace;
220import android.os.UserHandle;
221import android.os.UserManager;
222import android.os.UserManagerInternal;
223import android.os.storage.IStorageManager;
224import android.os.storage.StorageEventListener;
225import android.os.storage.StorageManager;
226import android.os.storage.StorageManagerInternal;
227import android.os.storage.VolumeInfo;
228import android.os.storage.VolumeRecord;
229import android.provider.Settings.Global;
230import android.provider.Settings.Secure;
231import android.security.KeyStore;
232import android.security.SystemKeyStore;
233import android.service.pm.PackageServiceDumpProto;
234import android.system.ErrnoException;
235import android.system.Os;
236import android.text.TextUtils;
237import android.text.format.DateUtils;
238import android.util.ArrayMap;
239import android.util.ArraySet;
240import android.util.Base64;
241import android.util.DisplayMetrics;
242import android.util.EventLog;
243import android.util.ExceptionUtils;
244import android.util.Log;
245import android.util.LogPrinter;
246import android.util.MathUtils;
247import android.util.PackageUtils;
248import android.util.Pair;
249import android.util.PrintStreamPrinter;
250import android.util.Slog;
251import android.util.SparseArray;
252import android.util.SparseBooleanArray;
253import android.util.SparseIntArray;
254import android.util.TimingsTraceLog;
255import android.util.Xml;
256import android.util.jar.StrictJarFile;
257import android.util.proto.ProtoOutputStream;
258import android.view.Display;
259
260import com.android.internal.R;
261import com.android.internal.annotations.GuardedBy;
262import com.android.internal.app.IMediaContainerService;
263import com.android.internal.app.ResolverActivity;
264import com.android.internal.content.NativeLibraryHelper;
265import com.android.internal.content.PackageHelper;
266import com.android.internal.logging.MetricsLogger;
267import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
268import com.android.internal.os.IParcelFileDescriptorFactory;
269import com.android.internal.os.RoSystemProperties;
270import com.android.internal.os.SomeArgs;
271import com.android.internal.os.Zygote;
272import com.android.internal.telephony.CarrierAppUtils;
273import com.android.internal.util.ArrayUtils;
274import com.android.internal.util.ConcurrentUtils;
275import com.android.internal.util.DumpUtils;
276import com.android.internal.util.FastPrintWriter;
277import com.android.internal.util.FastXmlSerializer;
278import com.android.internal.util.IndentingPrintWriter;
279import com.android.internal.util.Preconditions;
280import com.android.internal.util.XmlUtils;
281import com.android.server.AttributeCache;
282import com.android.server.DeviceIdleController;
283import com.android.server.EventLogTags;
284import com.android.server.FgThread;
285import com.android.server.IntentResolver;
286import com.android.server.LocalServices;
287import com.android.server.LockGuard;
288import com.android.server.ServiceThread;
289import com.android.server.SystemConfig;
290import com.android.server.SystemServerInitThreadPool;
291import com.android.server.Watchdog;
292import com.android.server.net.NetworkPolicyManagerInternal;
293import com.android.server.pm.Installer.InstallerException;
294import com.android.server.pm.Settings.DatabaseVersion;
295import com.android.server.pm.Settings.VersionInfo;
296import com.android.server.pm.dex.DexManager;
297import com.android.server.pm.dex.DexoptOptions;
298import com.android.server.pm.dex.PackageDexUsage;
299import com.android.server.pm.permission.BasePermission;
300import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
301import com.android.server.pm.permission.PermissionManagerService;
302import com.android.server.pm.permission.PermissionManagerInternal;
303import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
304import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
305import com.android.server.pm.permission.PermissionsState;
306import com.android.server.pm.permission.PermissionsState.PermissionState;
307import com.android.server.storage.DeviceStorageMonitorInternal;
308
309import dalvik.system.CloseGuard;
310import dalvik.system.DexFile;
311import dalvik.system.VMRuntime;
312
313import libcore.io.IoUtils;
314import libcore.io.Streams;
315import libcore.util.EmptyArray;
316
317import org.xmlpull.v1.XmlPullParser;
318import org.xmlpull.v1.XmlPullParserException;
319import org.xmlpull.v1.XmlSerializer;
320
321import java.io.BufferedOutputStream;
322import java.io.BufferedReader;
323import java.io.ByteArrayInputStream;
324import java.io.ByteArrayOutputStream;
325import java.io.File;
326import java.io.FileDescriptor;
327import java.io.FileInputStream;
328import java.io.FileOutputStream;
329import java.io.FileReader;
330import java.io.FilenameFilter;
331import java.io.IOException;
332import java.io.InputStream;
333import java.io.OutputStream;
334import java.io.PrintWriter;
335import java.lang.annotation.Retention;
336import java.lang.annotation.RetentionPolicy;
337import java.nio.charset.StandardCharsets;
338import java.security.DigestInputStream;
339import java.security.MessageDigest;
340import java.security.NoSuchAlgorithmException;
341import java.security.PublicKey;
342import java.security.SecureRandom;
343import java.security.cert.Certificate;
344import java.security.cert.CertificateEncodingException;
345import java.security.cert.CertificateException;
346import java.text.SimpleDateFormat;
347import java.util.ArrayList;
348import java.util.Arrays;
349import java.util.Collection;
350import java.util.Collections;
351import java.util.Comparator;
352import java.util.Date;
353import java.util.HashMap;
354import java.util.HashSet;
355import java.util.Iterator;
356import java.util.LinkedHashSet;
357import java.util.List;
358import java.util.Map;
359import java.util.Objects;
360import java.util.Set;
361import java.util.concurrent.CountDownLatch;
362import java.util.concurrent.Future;
363import java.util.concurrent.TimeUnit;
364import java.util.concurrent.atomic.AtomicBoolean;
365import java.util.concurrent.atomic.AtomicInteger;
366import java.util.zip.GZIPInputStream;
367
368/**
369 * Keep track of all those APKs everywhere.
370 * <p>
371 * Internally there are two important locks:
372 * <ul>
373 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
374 * and other related state. It is a fine-grained lock that should only be held
375 * momentarily, as it's one of the most contended locks in the system.
376 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
377 * operations typically involve heavy lifting of application data on disk. Since
378 * {@code installd} is single-threaded, and it's operations can often be slow,
379 * this lock should never be acquired while already holding {@link #mPackages}.
380 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
381 * holding {@link #mInstallLock}.
382 * </ul>
383 * Many internal methods rely on the caller to hold the appropriate locks, and
384 * this contract is expressed through method name suffixes:
385 * <ul>
386 * <li>fooLI(): the caller must hold {@link #mInstallLock}
387 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
388 * being modified must be frozen
389 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
390 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
391 * </ul>
392 * <p>
393 * Because this class is very central to the platform's security; please run all
394 * CTS and unit tests whenever making modifications:
395 *
396 * <pre>
397 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
398 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
399 * </pre>
400 */
401public class PackageManagerService extends IPackageManager.Stub
402        implements PackageSender {
403    static final String TAG = "PackageManager";
404    public static final boolean DEBUG_SETTINGS = false;
405    static final boolean DEBUG_PREFERRED = false;
406    static final boolean DEBUG_UPGRADE = false;
407    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
408    private static final boolean DEBUG_BACKUP = false;
409    public static final boolean DEBUG_INSTALL = false;
410    public static final boolean DEBUG_REMOVE = false;
411    private static final boolean DEBUG_BROADCASTS = false;
412    private static final boolean DEBUG_SHOW_INFO = false;
413    private static final boolean DEBUG_PACKAGE_INFO = false;
414    private static final boolean DEBUG_INTENT_MATCHING = false;
415    public static final boolean DEBUG_PACKAGE_SCANNING = false;
416    private static final boolean DEBUG_VERIFY = false;
417    private static final boolean DEBUG_FILTERS = false;
418    public static final boolean DEBUG_PERMISSIONS = false;
419    private static final boolean DEBUG_SHARED_LIBRARIES = false;
420    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
421
422    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
423    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
424    // user, but by default initialize to this.
425    public static final boolean DEBUG_DEXOPT = false;
426
427    private static final boolean DEBUG_ABI_SELECTION = false;
428    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
429    private static final boolean DEBUG_TRIAGED_MISSING = false;
430    private static final boolean DEBUG_APP_DATA = false;
431
432    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
433    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
434
435    private static final boolean HIDE_EPHEMERAL_APIS = false;
436
437    private static final boolean ENABLE_FREE_CACHE_V2 =
438            SystemProperties.getBoolean("fw.free_cache_v2", true);
439
440    private static final int RADIO_UID = Process.PHONE_UID;
441    private static final int LOG_UID = Process.LOG_UID;
442    private static final int NFC_UID = Process.NFC_UID;
443    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
444    private static final int SHELL_UID = Process.SHELL_UID;
445
446    // Suffix used during package installation when copying/moving
447    // package apks to install directory.
448    private static final String INSTALL_PACKAGE_SUFFIX = "-";
449
450    static final int SCAN_NO_DEX = 1<<1;
451    static final int SCAN_FORCE_DEX = 1<<2;
452    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
453    static final int SCAN_NEW_INSTALL = 1<<4;
454    static final int SCAN_UPDATE_TIME = 1<<5;
455    static final int SCAN_BOOTING = 1<<6;
456    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
457    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
458    static final int SCAN_REPLACING = 1<<9;
459    static final int SCAN_REQUIRE_KNOWN = 1<<10;
460    static final int SCAN_MOVE = 1<<11;
461    static final int SCAN_INITIAL = 1<<12;
462    static final int SCAN_CHECK_ONLY = 1<<13;
463    static final int SCAN_DONT_KILL_APP = 1<<14;
464    static final int SCAN_IGNORE_FROZEN = 1<<15;
465    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
466    static final int SCAN_AS_INSTANT_APP = 1<<17;
467    static final int SCAN_AS_FULL_APP = 1<<18;
468    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
469    /** Should not be with the scan flags */
470    static final int FLAGS_REMOVE_CHATTY = 1<<31;
471
472    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
473    /** Extension of the compressed packages */
474    public final static String COMPRESSED_EXTENSION = ".gz";
475    /** Suffix of stub packages on the system partition */
476    public final static String STUB_SUFFIX = "-Stub";
477
478    private static final int[] EMPTY_INT_ARRAY = new int[0];
479
480    private static final int TYPE_UNKNOWN = 0;
481    private static final int TYPE_ACTIVITY = 1;
482    private static final int TYPE_RECEIVER = 2;
483    private static final int TYPE_SERVICE = 3;
484    private static final int TYPE_PROVIDER = 4;
485    @IntDef(prefix = { "TYPE_" }, value = {
486            TYPE_UNKNOWN,
487            TYPE_ACTIVITY,
488            TYPE_RECEIVER,
489            TYPE_SERVICE,
490            TYPE_PROVIDER,
491    })
492    @Retention(RetentionPolicy.SOURCE)
493    public @interface ComponentType {}
494
495    /**
496     * Timeout (in milliseconds) after which the watchdog should declare that
497     * our handler thread is wedged.  The usual default for such things is one
498     * minute but we sometimes do very lengthy I/O operations on this thread,
499     * such as installing multi-gigabyte applications, so ours needs to be longer.
500     */
501    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
502
503    /**
504     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
505     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
506     * settings entry if available, otherwise we use the hardcoded default.  If it's been
507     * more than this long since the last fstrim, we force one during the boot sequence.
508     *
509     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
510     * one gets run at the next available charging+idle time.  This final mandatory
511     * no-fstrim check kicks in only of the other scheduling criteria is never met.
512     */
513    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
514
515    /**
516     * Whether verification is enabled by default.
517     */
518    private static final boolean DEFAULT_VERIFY_ENABLE = true;
519
520    /**
521     * The default maximum time to wait for the verification agent to return in
522     * milliseconds.
523     */
524    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
525
526    /**
527     * The default response for package verification timeout.
528     *
529     * This can be either PackageManager.VERIFICATION_ALLOW or
530     * PackageManager.VERIFICATION_REJECT.
531     */
532    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
533
534    public static final String PLATFORM_PACKAGE_NAME = "android";
535
536    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
537
538    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
539            DEFAULT_CONTAINER_PACKAGE,
540            "com.android.defcontainer.DefaultContainerService");
541
542    private static final String KILL_APP_REASON_GIDS_CHANGED =
543            "permission grant or revoke changed gids";
544
545    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
546            "permissions revoked";
547
548    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
549
550    private static final String PACKAGE_SCHEME = "package";
551
552    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
553
554    /** Canonical intent used to identify what counts as a "web browser" app */
555    private static final Intent sBrowserIntent;
556    static {
557        sBrowserIntent = new Intent();
558        sBrowserIntent.setAction(Intent.ACTION_VIEW);
559        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
560        sBrowserIntent.setData(Uri.parse("http:"));
561    }
562
563    /**
564     * The set of all protected actions [i.e. those actions for which a high priority
565     * intent filter is disallowed].
566     */
567    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
568    static {
569        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
570        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
571        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
572        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
573    }
574
575    // Compilation reasons.
576    public static final int REASON_FIRST_BOOT = 0;
577    public static final int REASON_BOOT = 1;
578    public static final int REASON_INSTALL = 2;
579    public static final int REASON_BACKGROUND_DEXOPT = 3;
580    public static final int REASON_AB_OTA = 4;
581    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
582    public static final int REASON_SHARED = 6;
583
584    public static final int REASON_LAST = REASON_SHARED;
585
586    /** All dangerous permission names in the same order as the events in MetricsEvent */
587    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
588            Manifest.permission.READ_CALENDAR,
589            Manifest.permission.WRITE_CALENDAR,
590            Manifest.permission.CAMERA,
591            Manifest.permission.READ_CONTACTS,
592            Manifest.permission.WRITE_CONTACTS,
593            Manifest.permission.GET_ACCOUNTS,
594            Manifest.permission.ACCESS_FINE_LOCATION,
595            Manifest.permission.ACCESS_COARSE_LOCATION,
596            Manifest.permission.RECORD_AUDIO,
597            Manifest.permission.READ_PHONE_STATE,
598            Manifest.permission.CALL_PHONE,
599            Manifest.permission.READ_CALL_LOG,
600            Manifest.permission.WRITE_CALL_LOG,
601            Manifest.permission.ADD_VOICEMAIL,
602            Manifest.permission.USE_SIP,
603            Manifest.permission.PROCESS_OUTGOING_CALLS,
604            Manifest.permission.READ_CELL_BROADCASTS,
605            Manifest.permission.BODY_SENSORS,
606            Manifest.permission.SEND_SMS,
607            Manifest.permission.RECEIVE_SMS,
608            Manifest.permission.READ_SMS,
609            Manifest.permission.RECEIVE_WAP_PUSH,
610            Manifest.permission.RECEIVE_MMS,
611            Manifest.permission.READ_EXTERNAL_STORAGE,
612            Manifest.permission.WRITE_EXTERNAL_STORAGE,
613            Manifest.permission.READ_PHONE_NUMBERS,
614            Manifest.permission.ANSWER_PHONE_CALLS);
615
616
617    /**
618     * Version number for the package parser cache. Increment this whenever the format or
619     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
620     */
621    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
622
623    /**
624     * Whether the package parser cache is enabled.
625     */
626    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed third-party apps stored */
665    final File mAppInstallDir;
666
667    /**
668     * Directory to which applications installed internally have their
669     * 32 bit native libraries copied.
670     */
671    private File mAppLib32InstallDir;
672
673    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
674    // apps.
675    final File mDrmAppPrivateInstallDir;
676
677    // ----------------------------------------------------------------
678
679    // Lock for state used when installing and doing other long running
680    // operations.  Methods that must be called with this lock held have
681    // the suffix "LI".
682    final Object mInstallLock = new Object();
683
684    // ----------------------------------------------------------------
685
686    // Keys are String (package name), values are Package.  This also serves
687    // as the lock for the global state.  Methods that must be called with
688    // this lock held have the prefix "LP".
689    @GuardedBy("mPackages")
690    final ArrayMap<String, PackageParser.Package> mPackages =
691            new ArrayMap<String, PackageParser.Package>();
692
693    final ArrayMap<String, Set<String>> mKnownCodebase =
694            new ArrayMap<String, Set<String>>();
695
696    // Keys are isolated uids and values are the uid of the application
697    // that created the isolated proccess.
698    @GuardedBy("mPackages")
699    final SparseIntArray mIsolatedOwners = new SparseIntArray();
700
701    /**
702     * Tracks new system packages [received in an OTA] that we expect to
703     * find updated user-installed versions. Keys are package name, values
704     * are package location.
705     */
706    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
707    /**
708     * Tracks high priority intent filters for protected actions. During boot, certain
709     * filter actions are protected and should never be allowed to have a high priority
710     * intent filter for them. However, there is one, and only one exception -- the
711     * setup wizard. It must be able to define a high priority intent filter for these
712     * actions to ensure there are no escapes from the wizard. We need to delay processing
713     * of these during boot as we need to look at all of the system packages in order
714     * to know which component is the setup wizard.
715     */
716    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
717    /**
718     * Whether or not processing protected filters should be deferred.
719     */
720    private boolean mDeferProtectedFilters = true;
721
722    /**
723     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
724     */
725    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
726    /**
727     * Whether or not system app permissions should be promoted from install to runtime.
728     */
729    boolean mPromoteSystemApps;
730
731    @GuardedBy("mPackages")
732    final Settings mSettings;
733
734    /**
735     * Set of package names that are currently "frozen", which means active
736     * surgery is being done on the code/data for that package. The platform
737     * will refuse to launch frozen packages to avoid race conditions.
738     *
739     * @see PackageFreezer
740     */
741    @GuardedBy("mPackages")
742    final ArraySet<String> mFrozenPackages = new ArraySet<>();
743
744    final ProtectedPackages mProtectedPackages;
745
746    @GuardedBy("mLoadedVolumes")
747    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
748
749    boolean mFirstBoot;
750
751    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
752
753    @GuardedBy("mAvailableFeatures")
754    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
755
756    // If mac_permissions.xml was found for seinfo labeling.
757    boolean mFoundPolicyFile;
758
759    private final InstantAppRegistry mInstantAppRegistry;
760
761    @GuardedBy("mPackages")
762    int mChangedPackagesSequenceNumber;
763    /**
764     * List of changed [installed, removed or updated] packages.
765     * mapping from user id -> sequence number -> package name
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
769    /**
770     * The sequence number of the last change to a package.
771     * mapping from user id -> package name -> sequence number
772     */
773    @GuardedBy("mPackages")
774    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
775
776    class PackageParserCallback implements PackageParser.Callback {
777        @Override public final boolean hasFeature(String feature) {
778            return PackageManagerService.this.hasSystemFeature(feature, 0);
779        }
780
781        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
782                Collection<PackageParser.Package> allPackages, String targetPackageName) {
783            List<PackageParser.Package> overlayPackages = null;
784            for (PackageParser.Package p : allPackages) {
785                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
786                    if (overlayPackages == null) {
787                        overlayPackages = new ArrayList<PackageParser.Package>();
788                    }
789                    overlayPackages.add(p);
790                }
791            }
792            if (overlayPackages != null) {
793                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
794                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
795                        return p1.mOverlayPriority - p2.mOverlayPriority;
796                    }
797                };
798                Collections.sort(overlayPackages, cmp);
799            }
800            return overlayPackages;
801        }
802
803        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
804                String targetPackageName, String targetPath) {
805            if ("android".equals(targetPackageName)) {
806                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
807                // native AssetManager.
808                return null;
809            }
810            List<PackageParser.Package> overlayPackages =
811                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
812            if (overlayPackages == null || overlayPackages.isEmpty()) {
813                return null;
814            }
815            List<String> overlayPathList = null;
816            for (PackageParser.Package overlayPackage : overlayPackages) {
817                if (targetPath == null) {
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                    continue;
823                }
824
825                try {
826                    // Creates idmaps for system to parse correctly the Android manifest of the
827                    // target package.
828                    //
829                    // OverlayManagerService will update each of them with a correct gid from its
830                    // target package app id.
831                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
832                            UserHandle.getSharedAppGid(
833                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
834                    if (overlayPathList == null) {
835                        overlayPathList = new ArrayList<String>();
836                    }
837                    overlayPathList.add(overlayPackage.baseCodePath);
838                } catch (InstallerException e) {
839                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
840                            overlayPackage.baseCodePath);
841                }
842            }
843            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
844        }
845
846        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
847            synchronized (mPackages) {
848                return getStaticOverlayPathsLocked(
849                        mPackages.values(), targetPackageName, targetPath);
850            }
851        }
852
853        @Override public final String[] getOverlayApks(String targetPackageName) {
854            return getStaticOverlayPaths(targetPackageName, null);
855        }
856
857        @Override public final String[] getOverlayPaths(String targetPackageName,
858                String targetPath) {
859            return getStaticOverlayPaths(targetPackageName, targetPath);
860        }
861    }
862
863    class ParallelPackageParserCallback extends PackageParserCallback {
864        List<PackageParser.Package> mOverlayPackages = null;
865
866        void findStaticOverlayPackages() {
867            synchronized (mPackages) {
868                for (PackageParser.Package p : mPackages.values()) {
869                    if (p.mIsStaticOverlay) {
870                        if (mOverlayPackages == null) {
871                            mOverlayPackages = new ArrayList<PackageParser.Package>();
872                        }
873                        mOverlayPackages.add(p);
874                    }
875                }
876            }
877        }
878
879        @Override
880        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
881            // We can trust mOverlayPackages without holding mPackages because package uninstall
882            // can't happen while running parallel parsing.
883            // Moreover holding mPackages on each parsing thread causes dead-lock.
884            return mOverlayPackages == null ? null :
885                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
886        }
887    }
888
889    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
890    final ParallelPackageParserCallback mParallelPackageParserCallback =
891            new ParallelPackageParserCallback();
892
893    public static final class SharedLibraryEntry {
894        public final @Nullable String path;
895        public final @Nullable String apk;
896        public final @NonNull SharedLibraryInfo info;
897
898        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
899                String declaringPackageName, int declaringPackageVersionCode) {
900            path = _path;
901            apk = _apk;
902            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
903                    declaringPackageName, declaringPackageVersionCode), null);
904        }
905    }
906
907    // Currently known shared libraries.
908    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
909    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
910            new ArrayMap<>();
911
912    // All available activities, for your resolving pleasure.
913    final ActivityIntentResolver mActivities =
914            new ActivityIntentResolver();
915
916    // All available receivers, for your resolving pleasure.
917    final ActivityIntentResolver mReceivers =
918            new ActivityIntentResolver();
919
920    // All available services, for your resolving pleasure.
921    final ServiceIntentResolver mServices = new ServiceIntentResolver();
922
923    // All available providers, for your resolving pleasure.
924    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
925
926    // Mapping from provider base names (first directory in content URI codePath)
927    // to the provider information.
928    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
929            new ArrayMap<String, PackageParser.Provider>();
930
931    // Mapping from instrumentation class names to info about them.
932    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
933            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
934
935    // Packages whose data we have transfered into another package, thus
936    // should no longer exist.
937    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
938
939    // Broadcast actions that are only available to the system.
940    @GuardedBy("mProtectedBroadcasts")
941    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
942
943    /** List of packages waiting for verification. */
944    final SparseArray<PackageVerificationState> mPendingVerification
945            = new SparseArray<PackageVerificationState>();
946
947    final PackageInstallerService mInstallerService;
948
949    private final PackageDexOptimizer mPackageDexOptimizer;
950    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
951    // is used by other apps).
952    private final DexManager mDexManager;
953
954    private AtomicInteger mNextMoveId = new AtomicInteger();
955    private final MoveCallbacks mMoveCallbacks;
956
957    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
958
959    // Cache of users who need badging.
960    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
961
962    /** Token for keys in mPendingVerification. */
963    private int mPendingVerificationToken = 0;
964
965    volatile boolean mSystemReady;
966    volatile boolean mSafeMode;
967    volatile boolean mHasSystemUidErrors;
968    private volatile boolean mEphemeralAppsDisabled;
969
970    ApplicationInfo mAndroidApplication;
971    final ActivityInfo mResolveActivity = new ActivityInfo();
972    final ResolveInfo mResolveInfo = new ResolveInfo();
973    ComponentName mResolveComponentName;
974    PackageParser.Package mPlatformPackage;
975    ComponentName mCustomResolverComponentName;
976
977    boolean mResolverReplaced = false;
978
979    private final @Nullable ComponentName mIntentFilterVerifierComponent;
980    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
981
982    private int mIntentFilterVerificationToken = 0;
983
984    /** The service connection to the ephemeral resolver */
985    final EphemeralResolverConnection mInstantAppResolverConnection;
986    /** Component used to show resolver settings for Instant Apps */
987    final ComponentName mInstantAppResolverSettingsComponent;
988
989    /** Activity used to install instant applications */
990    ActivityInfo mInstantAppInstallerActivity;
991    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
992
993    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
994            = new SparseArray<IntentFilterVerificationState>();
995
996    // TODO remove this and go through mPermissonManager directly
997    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
998    private final PermissionManagerInternal mPermissionManager;
999
1000    // List of packages names to keep cached, even if they are uninstalled for all users
1001    private List<String> mKeepUninstalledPackages;
1002
1003    private UserManagerInternal mUserManagerInternal;
1004
1005    private DeviceIdleController.LocalService mDeviceIdleController;
1006
1007    private File mCacheDir;
1008
1009    private Future<?> mPrepareAppDataFuture;
1010
1011    private static class IFVerificationParams {
1012        PackageParser.Package pkg;
1013        boolean replacing;
1014        int userId;
1015        int verifierUid;
1016
1017        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1018                int _userId, int _verifierUid) {
1019            pkg = _pkg;
1020            replacing = _replacing;
1021            userId = _userId;
1022            replacing = _replacing;
1023            verifierUid = _verifierUid;
1024        }
1025    }
1026
1027    private interface IntentFilterVerifier<T extends IntentFilter> {
1028        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1029                                               T filter, String packageName);
1030        void startVerifications(int userId);
1031        void receiveVerificationResponse(int verificationId);
1032    }
1033
1034    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1035        private Context mContext;
1036        private ComponentName mIntentFilterVerifierComponent;
1037        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1038
1039        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1040            mContext = context;
1041            mIntentFilterVerifierComponent = verifierComponent;
1042        }
1043
1044        private String getDefaultScheme() {
1045            return IntentFilter.SCHEME_HTTPS;
1046        }
1047
1048        @Override
1049        public void startVerifications(int userId) {
1050            // Launch verifications requests
1051            int count = mCurrentIntentFilterVerifications.size();
1052            for (int n=0; n<count; n++) {
1053                int verificationId = mCurrentIntentFilterVerifications.get(n);
1054                final IntentFilterVerificationState ivs =
1055                        mIntentFilterVerificationStates.get(verificationId);
1056
1057                String packageName = ivs.getPackageName();
1058
1059                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1060                final int filterCount = filters.size();
1061                ArraySet<String> domainsSet = new ArraySet<>();
1062                for (int m=0; m<filterCount; m++) {
1063                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1064                    domainsSet.addAll(filter.getHostsList());
1065                }
1066                synchronized (mPackages) {
1067                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1068                            packageName, domainsSet) != null) {
1069                        scheduleWriteSettingsLocked();
1070                    }
1071                }
1072                sendVerificationRequest(verificationId, ivs);
1073            }
1074            mCurrentIntentFilterVerifications.clear();
1075        }
1076
1077        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1078            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1081                    verificationId);
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1084                    getDefaultScheme());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1087                    ivs.getHostsString());
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1090                    ivs.getPackageName());
1091            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1092            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1093
1094            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1095            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1096                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1097                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1098
1099            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1100            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1101                    "Sending IntentFilter verification broadcast");
1102        }
1103
1104        public void receiveVerificationResponse(int verificationId) {
1105            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1106
1107            final boolean verified = ivs.isVerified();
1108
1109            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1110            final int count = filters.size();
1111            if (DEBUG_DOMAIN_VERIFICATION) {
1112                Slog.i(TAG, "Received verification response " + verificationId
1113                        + " for " + count + " filters, verified=" + verified);
1114            }
1115            for (int n=0; n<count; n++) {
1116                PackageParser.ActivityIntentInfo filter = filters.get(n);
1117                filter.setVerified(verified);
1118
1119                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1120                        + " verified with result:" + verified + " and hosts:"
1121                        + ivs.getHostsString());
1122            }
1123
1124            mIntentFilterVerificationStates.remove(verificationId);
1125
1126            final String packageName = ivs.getPackageName();
1127            IntentFilterVerificationInfo ivi = null;
1128
1129            synchronized (mPackages) {
1130                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1131            }
1132            if (ivi == null) {
1133                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1134                        + verificationId + " packageName:" + packageName);
1135                return;
1136            }
1137            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1138                    "Updating IntentFilterVerificationInfo for package " + packageName
1139                            +" verificationId:" + verificationId);
1140
1141            synchronized (mPackages) {
1142                if (verified) {
1143                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1144                } else {
1145                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1146                }
1147                scheduleWriteSettingsLocked();
1148
1149                final int userId = ivs.getUserId();
1150                if (userId != UserHandle.USER_ALL) {
1151                    final int userStatus =
1152                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1153
1154                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1155                    boolean needUpdate = false;
1156
1157                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1158                    // already been set by the User thru the Disambiguation dialog
1159                    switch (userStatus) {
1160                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1161                            if (verified) {
1162                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1163                            } else {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1165                            }
1166                            needUpdate = true;
1167                            break;
1168
1169                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1170                            if (verified) {
1171                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1172                                needUpdate = true;
1173                            }
1174                            break;
1175
1176                        default:
1177                            // Nothing to do
1178                    }
1179
1180                    if (needUpdate) {
1181                        mSettings.updateIntentFilterVerificationStatusLPw(
1182                                packageName, updatedStatus, userId);
1183                        scheduleWritePackageRestrictionsLocked(userId);
1184                    }
1185                }
1186            }
1187        }
1188
1189        @Override
1190        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1191                    ActivityIntentInfo filter, String packageName) {
1192            if (!hasValidDomains(filter)) {
1193                return false;
1194            }
1195            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1196            if (ivs == null) {
1197                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1198                        packageName);
1199            }
1200            if (DEBUG_DOMAIN_VERIFICATION) {
1201                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1202            }
1203            ivs.addFilter(filter);
1204            return true;
1205        }
1206
1207        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1208                int userId, int verificationId, String packageName) {
1209            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1210                    verifierUid, userId, packageName);
1211            ivs.setPendingState();
1212            synchronized (mPackages) {
1213                mIntentFilterVerificationStates.append(verificationId, ivs);
1214                mCurrentIntentFilterVerifications.add(verificationId);
1215            }
1216            return ivs;
1217        }
1218    }
1219
1220    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1221        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1222                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1223                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1224    }
1225
1226    // Set of pending broadcasts for aggregating enable/disable of components.
1227    static class PendingPackageBroadcasts {
1228        // for each user id, a map of <package name -> components within that package>
1229        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1230
1231        public PendingPackageBroadcasts() {
1232            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1233        }
1234
1235        public ArrayList<String> get(int userId, String packageName) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            return packages.get(packageName);
1238        }
1239
1240        public void put(int userId, String packageName, ArrayList<String> components) {
1241            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1242            packages.put(packageName, components);
1243        }
1244
1245        public void remove(int userId, String packageName) {
1246            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1247            if (packages != null) {
1248                packages.remove(packageName);
1249            }
1250        }
1251
1252        public void remove(int userId) {
1253            mUidMap.remove(userId);
1254        }
1255
1256        public int userIdCount() {
1257            return mUidMap.size();
1258        }
1259
1260        public int userIdAt(int n) {
1261            return mUidMap.keyAt(n);
1262        }
1263
1264        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1265            return mUidMap.get(userId);
1266        }
1267
1268        public int size() {
1269            // total number of pending broadcast entries across all userIds
1270            int num = 0;
1271            for (int i = 0; i< mUidMap.size(); i++) {
1272                num += mUidMap.valueAt(i).size();
1273            }
1274            return num;
1275        }
1276
1277        public void clear() {
1278            mUidMap.clear();
1279        }
1280
1281        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1282            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1283            if (map == null) {
1284                map = new ArrayMap<String, ArrayList<String>>();
1285                mUidMap.put(userId, map);
1286            }
1287            return map;
1288        }
1289    }
1290    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1291
1292    // Service Connection to remote media container service to copy
1293    // package uri's from external media onto secure containers
1294    // or internal storage.
1295    private IMediaContainerService mContainerService = null;
1296
1297    static final int SEND_PENDING_BROADCAST = 1;
1298    static final int MCS_BOUND = 3;
1299    static final int END_COPY = 4;
1300    static final int INIT_COPY = 5;
1301    static final int MCS_UNBIND = 6;
1302    static final int START_CLEANING_PACKAGE = 7;
1303    static final int FIND_INSTALL_LOC = 8;
1304    static final int POST_INSTALL = 9;
1305    static final int MCS_RECONNECT = 10;
1306    static final int MCS_GIVE_UP = 11;
1307    static final int WRITE_SETTINGS = 13;
1308    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1309    static final int PACKAGE_VERIFIED = 15;
1310    static final int CHECK_PENDING_VERIFICATION = 16;
1311    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1312    static final int INTENT_FILTER_VERIFIED = 18;
1313    static final int WRITE_PACKAGE_LIST = 19;
1314    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1315
1316    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1317
1318    // Delay time in millisecs
1319    static final int BROADCAST_DELAY = 10 * 1000;
1320
1321    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1322            2 * 60 * 60 * 1000L; /* two hours */
1323
1324    static UserManagerService sUserManager;
1325
1326    // Stores a list of users whose package restrictions file needs to be updated
1327    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1328
1329    final private DefaultContainerConnection mDefContainerConn =
1330            new DefaultContainerConnection();
1331    class DefaultContainerConnection implements ServiceConnection {
1332        public void onServiceConnected(ComponentName name, IBinder service) {
1333            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1334            final IMediaContainerService imcs = IMediaContainerService.Stub
1335                    .asInterface(Binder.allowBlocking(service));
1336            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1337        }
1338
1339        public void onServiceDisconnected(ComponentName name) {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1341        }
1342    }
1343
1344    // Recordkeeping of restore-after-install operations that are currently in flight
1345    // between the Package Manager and the Backup Manager
1346    static class PostInstallData {
1347        public InstallArgs args;
1348        public PackageInstalledInfo res;
1349
1350        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1351            args = _a;
1352            res = _r;
1353        }
1354    }
1355
1356    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1357    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1358
1359    // XML tags for backup/restore of various bits of state
1360    private static final String TAG_PREFERRED_BACKUP = "pa";
1361    private static final String TAG_DEFAULT_APPS = "da";
1362    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1363
1364    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1365    private static final String TAG_ALL_GRANTS = "rt-grants";
1366    private static final String TAG_GRANT = "grant";
1367    private static final String ATTR_PACKAGE_NAME = "pkg";
1368
1369    private static final String TAG_PERMISSION = "perm";
1370    private static final String ATTR_PERMISSION_NAME = "name";
1371    private static final String ATTR_IS_GRANTED = "g";
1372    private static final String ATTR_USER_SET = "set";
1373    private static final String ATTR_USER_FIXED = "fixed";
1374    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1375
1376    // System/policy permission grants are not backed up
1377    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1378            FLAG_PERMISSION_POLICY_FIXED
1379            | FLAG_PERMISSION_SYSTEM_FIXED
1380            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1381
1382    // And we back up these user-adjusted states
1383    private static final int USER_RUNTIME_GRANT_MASK =
1384            FLAG_PERMISSION_USER_SET
1385            | FLAG_PERMISSION_USER_FIXED
1386            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1387
1388    final @Nullable String mRequiredVerifierPackage;
1389    final @NonNull String mRequiredInstallerPackage;
1390    final @NonNull String mRequiredUninstallerPackage;
1391    final @Nullable String mSetupWizardPackage;
1392    final @Nullable String mStorageManagerPackage;
1393    final @NonNull String mServicesSystemSharedLibraryPackageName;
1394    final @NonNull String mSharedSystemSharedLibraryPackageName;
1395
1396    private final PackageUsage mPackageUsage = new PackageUsage();
1397    private final CompilerStats mCompilerStats = new CompilerStats();
1398
1399    class PackageHandler extends Handler {
1400        private boolean mBound = false;
1401        final ArrayList<HandlerParams> mPendingInstalls =
1402            new ArrayList<HandlerParams>();
1403
1404        private boolean connectToService() {
1405            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1406                    " DefaultContainerService");
1407            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1410                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                mBound = true;
1413                return true;
1414            }
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416            return false;
1417        }
1418
1419        private void disconnectService() {
1420            mContainerService = null;
1421            mBound = false;
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            mContext.unbindService(mDefContainerConn);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425        }
1426
1427        PackageHandler(Looper looper) {
1428            super(looper);
1429        }
1430
1431        public void handleMessage(Message msg) {
1432            try {
1433                doHandleMessage(msg);
1434            } finally {
1435                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            }
1437        }
1438
1439        void doHandleMessage(Message msg) {
1440            switch (msg.what) {
1441                case INIT_COPY: {
1442                    HandlerParams params = (HandlerParams) msg.obj;
1443                    int idx = mPendingInstalls.size();
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1445                    // If a bind was already initiated we dont really
1446                    // need to do anything. The pending install
1447                    // will be processed later on.
1448                    if (!mBound) {
1449                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                System.identityHashCode(mHandler));
1451                        // If this is the only one pending we might
1452                        // have to bind to the service again.
1453                        if (!connectToService()) {
1454                            Slog.e(TAG, "Failed to bind to media container service");
1455                            params.serviceError();
1456                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                    System.identityHashCode(mHandler));
1458                            if (params.traceMethod != null) {
1459                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1460                                        params.traceCookie);
1461                            }
1462                            return;
1463                        } else {
1464                            // Once we bind to the service, the first
1465                            // pending request will be processed.
1466                            mPendingInstalls.add(idx, params);
1467                        }
1468                    } else {
1469                        mPendingInstalls.add(idx, params);
1470                        // Already bound to the service. Just make
1471                        // sure we trigger off processing the first request.
1472                        if (idx == 0) {
1473                            mHandler.sendEmptyMessage(MCS_BOUND);
1474                        }
1475                    }
1476                    break;
1477                }
1478                case MCS_BOUND: {
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1480                    if (msg.obj != null) {
1481                        mContainerService = (IMediaContainerService) msg.obj;
1482                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                System.identityHashCode(mHandler));
1484                    }
1485                    if (mContainerService == null) {
1486                        if (!mBound) {
1487                            // Something seriously wrong since we are not bound and we are not
1488                            // waiting for connection. Bail out.
1489                            Slog.e(TAG, "Cannot bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                                if (params.traceMethod != null) {
1496                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1497                                            params.traceMethod, params.traceCookie);
1498                                }
1499                                return;
1500                            }
1501                            mPendingInstalls.clear();
1502                        } else {
1503                            Slog.w(TAG, "Waiting to connect to media container service");
1504                        }
1505                    } else if (mPendingInstalls.size() > 0) {
1506                        HandlerParams params = mPendingInstalls.get(0);
1507                        if (params != null) {
1508                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                    System.identityHashCode(params));
1510                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1511                            if (params.startCopy()) {
1512                                // We are done...  look for more work or to
1513                                // go idle.
1514                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                        "Checking for more work or unbind...");
1516                                // Delete pending install
1517                                if (mPendingInstalls.size() > 0) {
1518                                    mPendingInstalls.remove(0);
1519                                }
1520                                if (mPendingInstalls.size() == 0) {
1521                                    if (mBound) {
1522                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                                "Posting delayed MCS_UNBIND");
1524                                        removeMessages(MCS_UNBIND);
1525                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1526                                        // Unbind after a little delay, to avoid
1527                                        // continual thrashing.
1528                                        sendMessageDelayed(ubmsg, 10000);
1529                                    }
1530                                } else {
1531                                    // There are more pending requests in queue.
1532                                    // Just post MCS_BOUND message to trigger processing
1533                                    // of next pending install.
1534                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                            "Posting MCS_BOUND for next work");
1536                                    mHandler.sendEmptyMessage(MCS_BOUND);
1537                                }
1538                            }
1539                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1540                        }
1541                    } else {
1542                        // Should never happen ideally.
1543                        Slog.w(TAG, "Empty queue");
1544                    }
1545                    break;
1546                }
1547                case MCS_RECONNECT: {
1548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1549                    if (mPendingInstalls.size() > 0) {
1550                        if (mBound) {
1551                            disconnectService();
1552                        }
1553                        if (!connectToService()) {
1554                            Slog.e(TAG, "Failed to bind to media container service");
1555                            for (HandlerParams params : mPendingInstalls) {
1556                                // Indicate service bind error
1557                                params.serviceError();
1558                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1559                                        System.identityHashCode(params));
1560                            }
1561                            mPendingInstalls.clear();
1562                        }
1563                    }
1564                    break;
1565                }
1566                case MCS_UNBIND: {
1567                    // If there is no actual work left, then time to unbind.
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1569
1570                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1571                        if (mBound) {
1572                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1573
1574                            disconnectService();
1575                        }
1576                    } else if (mPendingInstalls.size() > 0) {
1577                        // There are more pending requests in queue.
1578                        // Just post MCS_BOUND message to trigger processing
1579                        // of next pending install.
1580                        mHandler.sendEmptyMessage(MCS_BOUND);
1581                    }
1582
1583                    break;
1584                }
1585                case MCS_GIVE_UP: {
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1587                    HandlerParams params = mPendingInstalls.remove(0);
1588                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1589                            System.identityHashCode(params));
1590                    break;
1591                }
1592                case SEND_PENDING_BROADCAST: {
1593                    String packages[];
1594                    ArrayList<String> components[];
1595                    int size = 0;
1596                    int uids[];
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        if (mPendingBroadcasts == null) {
1600                            return;
1601                        }
1602                        size = mPendingBroadcasts.size();
1603                        if (size <= 0) {
1604                            // Nothing to be done. Just return
1605                            return;
1606                        }
1607                        packages = new String[size];
1608                        components = new ArrayList[size];
1609                        uids = new int[size];
1610                        int i = 0;  // filling out the above arrays
1611
1612                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1613                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1614                            Iterator<Map.Entry<String, ArrayList<String>>> it
1615                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1616                                            .entrySet().iterator();
1617                            while (it.hasNext() && i < size) {
1618                                Map.Entry<String, ArrayList<String>> ent = it.next();
1619                                packages[i] = ent.getKey();
1620                                components[i] = ent.getValue();
1621                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1622                                uids[i] = (ps != null)
1623                                        ? UserHandle.getUid(packageUserId, ps.appId)
1624                                        : -1;
1625                                i++;
1626                            }
1627                        }
1628                        size = i;
1629                        mPendingBroadcasts.clear();
1630                    }
1631                    // Send broadcasts
1632                    for (int i = 0; i < size; i++) {
1633                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1634                    }
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1636                    break;
1637                }
1638                case START_CLEANING_PACKAGE: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    final String packageName = (String)msg.obj;
1641                    final int userId = msg.arg1;
1642                    final boolean andCode = msg.arg2 != 0;
1643                    synchronized (mPackages) {
1644                        if (userId == UserHandle.USER_ALL) {
1645                            int[] users = sUserManager.getUserIds();
1646                            for (int user : users) {
1647                                mSettings.addPackageToCleanLPw(
1648                                        new PackageCleanItem(user, packageName, andCode));
1649                            }
1650                        } else {
1651                            mSettings.addPackageToCleanLPw(
1652                                    new PackageCleanItem(userId, packageName, andCode));
1653                        }
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    startCleaningPackages();
1657                } break;
1658                case POST_INSTALL: {
1659                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1660
1661                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1662                    final boolean didRestore = (msg.arg2 != 0);
1663                    mRunningInstalls.delete(msg.arg1);
1664
1665                    if (data != null) {
1666                        InstallArgs args = data.args;
1667                        PackageInstalledInfo parentRes = data.res;
1668
1669                        final boolean grantPermissions = (args.installFlags
1670                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1671                        final boolean killApp = (args.installFlags
1672                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1673                        final boolean virtualPreload = ((args.installFlags
1674                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1675                        final String[] grantedPermissions = args.installGrantPermissions;
1676
1677                        // Handle the parent package
1678                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1679                                virtualPreload, grantedPermissions, didRestore,
1680                                args.installerPackageName, args.observer);
1681
1682                        // Handle the child packages
1683                        final int childCount = (parentRes.addedChildPackages != null)
1684                                ? parentRes.addedChildPackages.size() : 0;
1685                        for (int i = 0; i < childCount; i++) {
1686                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1687                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1688                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1689                                    args.installerPackageName, args.observer);
1690                        }
1691
1692                        // Log tracing if needed
1693                        if (args.traceMethod != null) {
1694                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1695                                    args.traceCookie);
1696                        }
1697                    } else {
1698                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1699                    }
1700
1701                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1702                } break;
1703                case WRITE_SETTINGS: {
1704                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1705                    synchronized (mPackages) {
1706                        removeMessages(WRITE_SETTINGS);
1707                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1708                        mSettings.writeLPr();
1709                        mDirtyUsers.clear();
1710                    }
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1712                } break;
1713                case WRITE_PACKAGE_RESTRICTIONS: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1717                        for (int userId : mDirtyUsers) {
1718                            mSettings.writePackageRestrictionsLPr(userId);
1719                        }
1720                        mDirtyUsers.clear();
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case WRITE_PACKAGE_LIST: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_PACKAGE_LIST);
1728                        mSettings.writePackageListLPr(msg.arg1);
1729                    }
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1731                } break;
1732                case CHECK_PENDING_VERIFICATION: {
1733                    final int verificationId = msg.arg1;
1734                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1735
1736                    if ((state != null) && !state.timeoutExtended()) {
1737                        final InstallArgs args = state.getInstallArgs();
1738                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1739
1740                        Slog.i(TAG, "Verification timed out for " + originUri);
1741                        mPendingVerification.remove(verificationId);
1742
1743                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1744
1745                        final UserHandle user = args.getUser();
1746                        if (getDefaultVerificationResponse(user)
1747                                == PackageManager.VERIFICATION_ALLOW) {
1748                            Slog.i(TAG, "Continuing with installation of " + originUri);
1749                            state.setVerifierResponse(Binder.getCallingUid(),
1750                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1751                            broadcastPackageVerified(verificationId, originUri,
1752                                    PackageManager.VERIFICATION_ALLOW, user);
1753                            try {
1754                                ret = args.copyApk(mContainerService, true);
1755                            } catch (RemoteException e) {
1756                                Slog.e(TAG, "Could not contact the ContainerService");
1757                            }
1758                        } else {
1759                            broadcastPackageVerified(verificationId, originUri,
1760                                    PackageManager.VERIFICATION_REJECT, user);
1761                        }
1762
1763                        Trace.asyncTraceEnd(
1764                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1765
1766                        processPendingInstall(args, ret);
1767                        mHandler.sendEmptyMessage(MCS_UNBIND);
1768                    }
1769                    break;
1770                }
1771                case PACKAGE_VERIFIED: {
1772                    final int verificationId = msg.arg1;
1773
1774                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1775                    if (state == null) {
1776                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1777                        break;
1778                    }
1779
1780                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1781
1782                    state.setVerifierResponse(response.callerUid, response.code);
1783
1784                    if (state.isVerificationComplete()) {
1785                        mPendingVerification.remove(verificationId);
1786
1787                        final InstallArgs args = state.getInstallArgs();
1788                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1789
1790                        int ret;
1791                        if (state.isInstallAllowed()) {
1792                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    response.code, state.getInstallArgs().getUser());
1795                            try {
1796                                ret = args.copyApk(mContainerService, true);
1797                            } catch (RemoteException e) {
1798                                Slog.e(TAG, "Could not contact the ContainerService");
1799                            }
1800                        } else {
1801                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1802                        }
1803
1804                        Trace.asyncTraceEnd(
1805                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1806
1807                        processPendingInstall(args, ret);
1808                        mHandler.sendEmptyMessage(MCS_UNBIND);
1809                    }
1810
1811                    break;
1812                }
1813                case START_INTENT_FILTER_VERIFICATIONS: {
1814                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1815                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1816                            params.replacing, params.pkg);
1817                    break;
1818                }
1819                case INTENT_FILTER_VERIFIED: {
1820                    final int verificationId = msg.arg1;
1821
1822                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1823                            verificationId);
1824                    if (state == null) {
1825                        Slog.w(TAG, "Invalid IntentFilter verification token "
1826                                + verificationId + " received");
1827                        break;
1828                    }
1829
1830                    final int userId = state.getUserId();
1831
1832                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1833                            "Processing IntentFilter verification with token:"
1834                            + verificationId + " and userId:" + userId);
1835
1836                    final IntentFilterVerificationResponse response =
1837                            (IntentFilterVerificationResponse) msg.obj;
1838
1839                    state.setVerifierResponse(response.callerUid, response.code);
1840
1841                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1842                            "IntentFilter verification with token:" + verificationId
1843                            + " and userId:" + userId
1844                            + " is settings verifier response with response code:"
1845                            + response.code);
1846
1847                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1848                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1849                                + response.getFailedDomainsString());
1850                    }
1851
1852                    if (state.isVerificationComplete()) {
1853                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1854                    } else {
1855                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1856                                "IntentFilter verification with token:" + verificationId
1857                                + " was not said to be complete");
1858                    }
1859
1860                    break;
1861                }
1862                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1863                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1864                            mInstantAppResolverConnection,
1865                            (InstantAppRequest) msg.obj,
1866                            mInstantAppInstallerActivity,
1867                            mHandler);
1868                }
1869            }
1870        }
1871    }
1872
1873    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1874        @Override
1875        public void onGidsChanged(int appId, int userId) {
1876            mHandler.post(new Runnable() {
1877                @Override
1878                public void run() {
1879                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1880                }
1881            });
1882        }
1883        @Override
1884        public void onPermissionGranted(int uid, int userId) {
1885            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1886
1887            // Not critical; if this is lost, the application has to request again.
1888            synchronized (mPackages) {
1889                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1890            }
1891        }
1892        @Override
1893        public void onInstallPermissionGranted() {
1894            synchronized (mPackages) {
1895                scheduleWriteSettingsLocked();
1896            }
1897        }
1898        @Override
1899        public void onPermissionRevoked(int uid, int userId) {
1900            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1901
1902            synchronized (mPackages) {
1903                // Critical; after this call the application should never have the permission
1904                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1905            }
1906
1907            final int appId = UserHandle.getAppId(uid);
1908            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1909        }
1910        @Override
1911        public void onInstallPermissionRevoked() {
1912            synchronized (mPackages) {
1913                scheduleWriteSettingsLocked();
1914            }
1915        }
1916        @Override
1917        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1918            synchronized (mPackages) {
1919                for (int userId : updatedUserIds) {
1920                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1921                }
1922            }
1923        }
1924        @Override
1925        public void onInstallPermissionUpdated() {
1926            synchronized (mPackages) {
1927                scheduleWriteSettingsLocked();
1928            }
1929        }
1930        @Override
1931        public void onPermissionRemoved() {
1932            synchronized (mPackages) {
1933                mSettings.writeLPr();
1934            }
1935        }
1936    };
1937
1938    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1939            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1940            boolean launchedForRestore, String installerPackage,
1941            IPackageInstallObserver2 installObserver) {
1942        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1943            // Send the removed broadcasts
1944            if (res.removedInfo != null) {
1945                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1946            }
1947
1948            // Now that we successfully installed the package, grant runtime
1949            // permissions if requested before broadcasting the install. Also
1950            // for legacy apps in permission review mode we clear the permission
1951            // review flag which is used to emulate runtime permissions for
1952            // legacy apps.
1953            if (grantPermissions) {
1954                final int callingUid = Binder.getCallingUid();
1955                mPermissionManager.grantRequestedRuntimePermissions(
1956                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1957                        mPermissionCallback);
1958            }
1959
1960            final boolean update = res.removedInfo != null
1961                    && res.removedInfo.removedPackage != null;
1962            final String installerPackageName =
1963                    res.installerPackageName != null
1964                            ? res.installerPackageName
1965                            : res.removedInfo != null
1966                                    ? res.removedInfo.installerPackageName
1967                                    : null;
1968
1969            // If this is the first time we have child packages for a disabled privileged
1970            // app that had no children, we grant requested runtime permissions to the new
1971            // children if the parent on the system image had them already granted.
1972            if (res.pkg.parentPackage != null) {
1973                final int callingUid = Binder.getCallingUid();
1974                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1975                        res.pkg, callingUid, mPermissionCallback);
1976            }
1977
1978            synchronized (mPackages) {
1979                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1980            }
1981
1982            final String packageName = res.pkg.applicationInfo.packageName;
1983
1984            // Determine the set of users who are adding this package for
1985            // the first time vs. those who are seeing an update.
1986            int[] firstUsers = EMPTY_INT_ARRAY;
1987            int[] updateUsers = EMPTY_INT_ARRAY;
1988            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1989            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1990            for (int newUser : res.newUsers) {
1991                if (ps.getInstantApp(newUser)) {
1992                    continue;
1993                }
1994                if (allNewUsers) {
1995                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1996                    continue;
1997                }
1998                boolean isNew = true;
1999                for (int origUser : res.origUsers) {
2000                    if (origUser == newUser) {
2001                        isNew = false;
2002                        break;
2003                    }
2004                }
2005                if (isNew) {
2006                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2007                } else {
2008                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
2009                }
2010            }
2011
2012            // Send installed broadcasts if the package is not a static shared lib.
2013            if (res.pkg.staticSharedLibName == null) {
2014                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2015
2016                // Send added for users that see the package for the first time
2017                // sendPackageAddedForNewUsers also deals with system apps
2018                int appId = UserHandle.getAppId(res.uid);
2019                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2020                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2021                        virtualPreload /*startReceiver*/, appId, firstUsers);
2022
2023                // Send added for users that don't see the package for the first time
2024                Bundle extras = new Bundle(1);
2025                extras.putInt(Intent.EXTRA_UID, res.uid);
2026                if (update) {
2027                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2028                }
2029                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2030                        extras, 0 /*flags*/,
2031                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2032                if (installerPackageName != null) {
2033                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2034                            extras, 0 /*flags*/,
2035                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2036                }
2037
2038                // Send replaced for users that don't see the package for the first time
2039                if (update) {
2040                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2041                            packageName, extras, 0 /*flags*/,
2042                            null /*targetPackage*/, null /*finishedReceiver*/,
2043                            updateUsers);
2044                    if (installerPackageName != null) {
2045                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2046                                extras, 0 /*flags*/,
2047                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2048                    }
2049                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2050                            null /*package*/, null /*extras*/, 0 /*flags*/,
2051                            packageName /*targetPackage*/,
2052                            null /*finishedReceiver*/, updateUsers);
2053                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2054                    // First-install and we did a restore, so we're responsible for the
2055                    // first-launch broadcast.
2056                    if (DEBUG_BACKUP) {
2057                        Slog.i(TAG, "Post-restore of " + packageName
2058                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2059                    }
2060                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2061                }
2062
2063                // Send broadcast package appeared if forward locked/external for all users
2064                // treat asec-hosted packages like removable media on upgrade
2065                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2066                    if (DEBUG_INSTALL) {
2067                        Slog.i(TAG, "upgrading pkg " + res.pkg
2068                                + " is ASEC-hosted -> AVAILABLE");
2069                    }
2070                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2071                    ArrayList<String> pkgList = new ArrayList<>(1);
2072                    pkgList.add(packageName);
2073                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2074                }
2075            }
2076
2077            // Work that needs to happen on first install within each user
2078            if (firstUsers != null && firstUsers.length > 0) {
2079                synchronized (mPackages) {
2080                    for (int userId : firstUsers) {
2081                        // If this app is a browser and it's newly-installed for some
2082                        // users, clear any default-browser state in those users. The
2083                        // app's nature doesn't depend on the user, so we can just check
2084                        // its browser nature in any user and generalize.
2085                        if (packageIsBrowser(packageName, userId)) {
2086                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2087                        }
2088
2089                        // We may also need to apply pending (restored) runtime
2090                        // permission grants within these users.
2091                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2092                    }
2093                }
2094            }
2095
2096            // Log current value of "unknown sources" setting
2097            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2098                    getUnknownSourcesSettings());
2099
2100            // Remove the replaced package's older resources safely now
2101            // We delete after a gc for applications  on sdcard.
2102            if (res.removedInfo != null && res.removedInfo.args != null) {
2103                Runtime.getRuntime().gc();
2104                synchronized (mInstallLock) {
2105                    res.removedInfo.args.doPostDeleteLI(true);
2106                }
2107            } else {
2108                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2109                // and not block here.
2110                VMRuntime.getRuntime().requestConcurrentGC();
2111            }
2112
2113            // Notify DexManager that the package was installed for new users.
2114            // The updated users should already be indexed and the package code paths
2115            // should not change.
2116            // Don't notify the manager for ephemeral apps as they are not expected to
2117            // survive long enough to benefit of background optimizations.
2118            for (int userId : firstUsers) {
2119                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2120                // There's a race currently where some install events may interleave with an uninstall.
2121                // This can lead to package info being null (b/36642664).
2122                if (info != null) {
2123                    mDexManager.notifyPackageInstalled(info, userId);
2124                }
2125            }
2126        }
2127
2128        // If someone is watching installs - notify them
2129        if (installObserver != null) {
2130            try {
2131                Bundle extras = extrasForInstallResult(res);
2132                installObserver.onPackageInstalled(res.name, res.returnCode,
2133                        res.returnMsg, extras);
2134            } catch (RemoteException e) {
2135                Slog.i(TAG, "Observer no longer exists.");
2136            }
2137        }
2138    }
2139
2140    private StorageEventListener mStorageListener = new StorageEventListener() {
2141        @Override
2142        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2143            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2144                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2145                    final String volumeUuid = vol.getFsUuid();
2146
2147                    // Clean up any users or apps that were removed or recreated
2148                    // while this volume was missing
2149                    sUserManager.reconcileUsers(volumeUuid);
2150                    reconcileApps(volumeUuid);
2151
2152                    // Clean up any install sessions that expired or were
2153                    // cancelled while this volume was missing
2154                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2155
2156                    loadPrivatePackages(vol);
2157
2158                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2159                    unloadPrivatePackages(vol);
2160                }
2161            }
2162        }
2163
2164        @Override
2165        public void onVolumeForgotten(String fsUuid) {
2166            if (TextUtils.isEmpty(fsUuid)) {
2167                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2168                return;
2169            }
2170
2171            // Remove any apps installed on the forgotten volume
2172            synchronized (mPackages) {
2173                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2174                for (PackageSetting ps : packages) {
2175                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2176                    deletePackageVersioned(new VersionedPackage(ps.name,
2177                            PackageManager.VERSION_CODE_HIGHEST),
2178                            new LegacyPackageDeleteObserver(null).getBinder(),
2179                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2180                    // Try very hard to release any references to this package
2181                    // so we don't risk the system server being killed due to
2182                    // open FDs
2183                    AttributeCache.instance().removePackage(ps.name);
2184                }
2185
2186                mSettings.onVolumeForgotten(fsUuid);
2187                mSettings.writeLPr();
2188            }
2189        }
2190    };
2191
2192    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2193        Bundle extras = null;
2194        switch (res.returnCode) {
2195            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2196                extras = new Bundle();
2197                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2198                        res.origPermission);
2199                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2200                        res.origPackage);
2201                break;
2202            }
2203            case PackageManager.INSTALL_SUCCEEDED: {
2204                extras = new Bundle();
2205                extras.putBoolean(Intent.EXTRA_REPLACING,
2206                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2207                break;
2208            }
2209        }
2210        return extras;
2211    }
2212
2213    void scheduleWriteSettingsLocked() {
2214        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2215            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2216        }
2217    }
2218
2219    void scheduleWritePackageListLocked(int userId) {
2220        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2221            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2222            msg.arg1 = userId;
2223            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2224        }
2225    }
2226
2227    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2228        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2229        scheduleWritePackageRestrictionsLocked(userId);
2230    }
2231
2232    void scheduleWritePackageRestrictionsLocked(int userId) {
2233        final int[] userIds = (userId == UserHandle.USER_ALL)
2234                ? sUserManager.getUserIds() : new int[]{userId};
2235        for (int nextUserId : userIds) {
2236            if (!sUserManager.exists(nextUserId)) return;
2237            mDirtyUsers.add(nextUserId);
2238            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2239                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2240            }
2241        }
2242    }
2243
2244    public static PackageManagerService main(Context context, Installer installer,
2245            boolean factoryTest, boolean onlyCore) {
2246        // Self-check for initial settings.
2247        PackageManagerServiceCompilerMapping.checkProperties();
2248
2249        PackageManagerService m = new PackageManagerService(context, installer,
2250                factoryTest, onlyCore);
2251        m.enableSystemUserPackages();
2252        ServiceManager.addService("package", m);
2253        final PackageManagerNative pmn = m.new PackageManagerNative();
2254        ServiceManager.addService("package_native", pmn);
2255        return m;
2256    }
2257
2258    private void enableSystemUserPackages() {
2259        if (!UserManager.isSplitSystemUser()) {
2260            return;
2261        }
2262        // For system user, enable apps based on the following conditions:
2263        // - app is whitelisted or belong to one of these groups:
2264        //   -- system app which has no launcher icons
2265        //   -- system app which has INTERACT_ACROSS_USERS permission
2266        //   -- system IME app
2267        // - app is not in the blacklist
2268        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2269        Set<String> enableApps = new ArraySet<>();
2270        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2271                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2272                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2273        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2274        enableApps.addAll(wlApps);
2275        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2276                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2277        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2278        enableApps.removeAll(blApps);
2279        Log.i(TAG, "Applications installed for system user: " + enableApps);
2280        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2281                UserHandle.SYSTEM);
2282        final int allAppsSize = allAps.size();
2283        synchronized (mPackages) {
2284            for (int i = 0; i < allAppsSize; i++) {
2285                String pName = allAps.get(i);
2286                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2287                // Should not happen, but we shouldn't be failing if it does
2288                if (pkgSetting == null) {
2289                    continue;
2290                }
2291                boolean install = enableApps.contains(pName);
2292                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2293                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2294                            + " for system user");
2295                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2296                }
2297            }
2298            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2299        }
2300    }
2301
2302    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2303        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2304                Context.DISPLAY_SERVICE);
2305        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2306    }
2307
2308    /**
2309     * Requests that files preopted on a secondary system partition be copied to the data partition
2310     * if possible.  Note that the actual copying of the files is accomplished by init for security
2311     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2312     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2313     */
2314    private static void requestCopyPreoptedFiles() {
2315        final int WAIT_TIME_MS = 100;
2316        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2317        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2318            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2319            // We will wait for up to 100 seconds.
2320            final long timeStart = SystemClock.uptimeMillis();
2321            final long timeEnd = timeStart + 100 * 1000;
2322            long timeNow = timeStart;
2323            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2324                try {
2325                    Thread.sleep(WAIT_TIME_MS);
2326                } catch (InterruptedException e) {
2327                    // Do nothing
2328                }
2329                timeNow = SystemClock.uptimeMillis();
2330                if (timeNow > timeEnd) {
2331                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2332                    Slog.wtf(TAG, "cppreopt did not finish!");
2333                    break;
2334                }
2335            }
2336
2337            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2338        }
2339    }
2340
2341    public PackageManagerService(Context context, Installer installer,
2342            boolean factoryTest, boolean onlyCore) {
2343        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2344        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2345        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2346                SystemClock.uptimeMillis());
2347
2348        if (mSdkVersion <= 0) {
2349            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2350        }
2351
2352        mContext = context;
2353
2354        mFactoryTest = factoryTest;
2355        mOnlyCore = onlyCore;
2356        mMetrics = new DisplayMetrics();
2357        mInstaller = installer;
2358
2359        // Create sub-components that provide services / data. Order here is important.
2360        synchronized (mInstallLock) {
2361        synchronized (mPackages) {
2362            // Expose private service for system components to use.
2363            LocalServices.addService(
2364                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2365            sUserManager = new UserManagerService(context, this,
2366                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2367            mPermissionManager = PermissionManagerService.create(context,
2368                    new DefaultPermissionGrantedCallback() {
2369                        @Override
2370                        public void onDefaultRuntimePermissionsGranted(int userId) {
2371                            synchronized(mPackages) {
2372                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2373                            }
2374                        }
2375                    }, mPackages /*externalLock*/);
2376            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2377            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2378        }
2379        }
2380        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2381                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2382        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2383                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2384        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2385                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2386        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2387                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2388        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2389                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2390        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2391                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2392
2393        String separateProcesses = SystemProperties.get("debug.separate_processes");
2394        if (separateProcesses != null && separateProcesses.length() > 0) {
2395            if ("*".equals(separateProcesses)) {
2396                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2397                mSeparateProcesses = null;
2398                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2399            } else {
2400                mDefParseFlags = 0;
2401                mSeparateProcesses = separateProcesses.split(",");
2402                Slog.w(TAG, "Running with debug.separate_processes: "
2403                        + separateProcesses);
2404            }
2405        } else {
2406            mDefParseFlags = 0;
2407            mSeparateProcesses = null;
2408        }
2409
2410        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2411                "*dexopt*");
2412        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2413        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2414
2415        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2416                FgThread.get().getLooper());
2417
2418        getDefaultDisplayMetrics(context, mMetrics);
2419
2420        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2421        SystemConfig systemConfig = SystemConfig.getInstance();
2422        mAvailableFeatures = systemConfig.getAvailableFeatures();
2423        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2424
2425        mProtectedPackages = new ProtectedPackages(mContext);
2426
2427        synchronized (mInstallLock) {
2428        // writer
2429        synchronized (mPackages) {
2430            mHandlerThread = new ServiceThread(TAG,
2431                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2432            mHandlerThread.start();
2433            mHandler = new PackageHandler(mHandlerThread.getLooper());
2434            mProcessLoggingHandler = new ProcessLoggingHandler();
2435            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2436            mInstantAppRegistry = new InstantAppRegistry(this);
2437
2438            File dataDir = Environment.getDataDirectory();
2439            mAppInstallDir = new File(dataDir, "app");
2440            mAppLib32InstallDir = new File(dataDir, "app-lib");
2441            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2442
2443            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2444            final int builtInLibCount = libConfig.size();
2445            for (int i = 0; i < builtInLibCount; i++) {
2446                String name = libConfig.keyAt(i);
2447                String path = libConfig.valueAt(i);
2448                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2449                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2450            }
2451
2452            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2453
2454            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2455            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2456            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2457
2458            // Clean up orphaned packages for which the code path doesn't exist
2459            // and they are an update to a system app - caused by bug/32321269
2460            final int packageSettingCount = mSettings.mPackages.size();
2461            for (int i = packageSettingCount - 1; i >= 0; i--) {
2462                PackageSetting ps = mSettings.mPackages.valueAt(i);
2463                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2464                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2465                    mSettings.mPackages.removeAt(i);
2466                    mSettings.enableSystemPackageLPw(ps.name);
2467                }
2468            }
2469
2470            if (mFirstBoot) {
2471                requestCopyPreoptedFiles();
2472            }
2473
2474            String customResolverActivity = Resources.getSystem().getString(
2475                    R.string.config_customResolverActivity);
2476            if (TextUtils.isEmpty(customResolverActivity)) {
2477                customResolverActivity = null;
2478            } else {
2479                mCustomResolverComponentName = ComponentName.unflattenFromString(
2480                        customResolverActivity);
2481            }
2482
2483            long startTime = SystemClock.uptimeMillis();
2484
2485            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2486                    startTime);
2487
2488            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2489            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2490
2491            if (bootClassPath == null) {
2492                Slog.w(TAG, "No BOOTCLASSPATH found!");
2493            }
2494
2495            if (systemServerClassPath == null) {
2496                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2497            }
2498
2499            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2500
2501            final VersionInfo ver = mSettings.getInternalVersion();
2502            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2503            if (mIsUpgrade) {
2504                logCriticalInfo(Log.INFO,
2505                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2506            }
2507
2508            // when upgrading from pre-M, promote system app permissions from install to runtime
2509            mPromoteSystemApps =
2510                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2511
2512            // When upgrading from pre-N, we need to handle package extraction like first boot,
2513            // as there is no profiling data available.
2514            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2515
2516            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2517
2518            // save off the names of pre-existing system packages prior to scanning; we don't
2519            // want to automatically grant runtime permissions for new system apps
2520            if (mPromoteSystemApps) {
2521                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2522                while (pkgSettingIter.hasNext()) {
2523                    PackageSetting ps = pkgSettingIter.next();
2524                    if (isSystemApp(ps)) {
2525                        mExistingSystemPackages.add(ps.name);
2526                    }
2527                }
2528            }
2529
2530            mCacheDir = preparePackageParserCache(mIsUpgrade);
2531
2532            // Set flag to monitor and not change apk file paths when
2533            // scanning install directories.
2534            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2535
2536            if (mIsUpgrade || mFirstBoot) {
2537                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2538            }
2539
2540            // Collect vendor overlay packages. (Do this before scanning any apps.)
2541            // For security and version matching reason, only consider
2542            // overlay packages if they reside in the right directory.
2543            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2544                    | PackageParser.PARSE_IS_SYSTEM
2545                    | PackageParser.PARSE_IS_SYSTEM_DIR
2546                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2547
2548            mParallelPackageParserCallback.findStaticOverlayPackages();
2549
2550            // Find base frameworks (resource packages without code).
2551            scanDirTracedLI(frameworkDir, mDefParseFlags
2552                    | PackageParser.PARSE_IS_SYSTEM
2553                    | PackageParser.PARSE_IS_SYSTEM_DIR
2554                    | PackageParser.PARSE_IS_PRIVILEGED,
2555                    scanFlags | SCAN_NO_DEX, 0);
2556
2557            // Collected privileged system packages.
2558            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2559            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2560                    | PackageParser.PARSE_IS_SYSTEM
2561                    | PackageParser.PARSE_IS_SYSTEM_DIR
2562                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2563
2564            // Collect ordinary system packages.
2565            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2566            scanDirTracedLI(systemAppDir, mDefParseFlags
2567                    | PackageParser.PARSE_IS_SYSTEM
2568                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2569
2570            // Collect all vendor packages.
2571            File vendorAppDir = new File("/vendor/app");
2572            try {
2573                vendorAppDir = vendorAppDir.getCanonicalFile();
2574            } catch (IOException e) {
2575                // failed to look up canonical path, continue with original one
2576            }
2577            scanDirTracedLI(vendorAppDir, mDefParseFlags
2578                    | PackageParser.PARSE_IS_SYSTEM
2579                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2580
2581            // Collect all OEM packages.
2582            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2583            scanDirTracedLI(oemAppDir, mDefParseFlags
2584                    | PackageParser.PARSE_IS_SYSTEM
2585                    | PackageParser.PARSE_IS_SYSTEM_DIR
2586                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2587
2588            // Prune any system packages that no longer exist.
2589            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2590            // Stub packages must either be replaced with full versions in the /data
2591            // partition or be disabled.
2592            final List<String> stubSystemApps = new ArrayList<>();
2593            if (!mOnlyCore) {
2594                // do this first before mucking with mPackages for the "expecting better" case
2595                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2596                while (pkgIterator.hasNext()) {
2597                    final PackageParser.Package pkg = pkgIterator.next();
2598                    if (pkg.isStub) {
2599                        stubSystemApps.add(pkg.packageName);
2600                    }
2601                }
2602
2603                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2604                while (psit.hasNext()) {
2605                    PackageSetting ps = psit.next();
2606
2607                    /*
2608                     * If this is not a system app, it can't be a
2609                     * disable system app.
2610                     */
2611                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2612                        continue;
2613                    }
2614
2615                    /*
2616                     * If the package is scanned, it's not erased.
2617                     */
2618                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2619                    if (scannedPkg != null) {
2620                        /*
2621                         * If the system app is both scanned and in the
2622                         * disabled packages list, then it must have been
2623                         * added via OTA. Remove it from the currently
2624                         * scanned package so the previously user-installed
2625                         * application can be scanned.
2626                         */
2627                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2628                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2629                                    + ps.name + "; removing system app.  Last known codePath="
2630                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2631                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2632                                    + scannedPkg.mVersionCode);
2633                            removePackageLI(scannedPkg, true);
2634                            mExpectingBetter.put(ps.name, ps.codePath);
2635                        }
2636
2637                        continue;
2638                    }
2639
2640                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2641                        psit.remove();
2642                        logCriticalInfo(Log.WARN, "System package " + ps.name
2643                                + " no longer exists; it's data will be wiped");
2644                        // Actual deletion of code and data will be handled by later
2645                        // reconciliation step
2646                    } else {
2647                        // we still have a disabled system package, but, it still might have
2648                        // been removed. check the code path still exists and check there's
2649                        // still a package. the latter can happen if an OTA keeps the same
2650                        // code path, but, changes the package name.
2651                        final PackageSetting disabledPs =
2652                                mSettings.getDisabledSystemPkgLPr(ps.name);
2653                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2654                                || disabledPs.pkg == null) {
2655                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2656                        }
2657                    }
2658                }
2659            }
2660
2661            //look for any incomplete package installations
2662            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2663            for (int i = 0; i < deletePkgsList.size(); i++) {
2664                // Actual deletion of code and data will be handled by later
2665                // reconciliation step
2666                final String packageName = deletePkgsList.get(i).name;
2667                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2668                synchronized (mPackages) {
2669                    mSettings.removePackageLPw(packageName);
2670                }
2671            }
2672
2673            //delete tmp files
2674            deleteTempPackageFiles();
2675
2676            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2677
2678            // Remove any shared userIDs that have no associated packages
2679            mSettings.pruneSharedUsersLPw();
2680            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2681            final int systemPackagesCount = mPackages.size();
2682            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2683                    + " ms, packageCount: " + systemPackagesCount
2684                    + " , timePerPackage: "
2685                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2686                    + " , cached: " + cachedSystemApps);
2687            if (mIsUpgrade && systemPackagesCount > 0) {
2688                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2689                        ((int) systemScanTime) / systemPackagesCount);
2690            }
2691            if (!mOnlyCore) {
2692                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2693                        SystemClock.uptimeMillis());
2694                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2695
2696                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2697                        | PackageParser.PARSE_FORWARD_LOCK,
2698                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2699
2700                // Remove disable package settings for updated system apps that were
2701                // removed via an OTA. If the update is no longer present, remove the
2702                // app completely. Otherwise, revoke their system privileges.
2703                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2704                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2705                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2706
2707                    final String msg;
2708                    if (deletedPkg == null) {
2709                        // should have found an update, but, we didn't; remove everything
2710                        msg = "Updated system package " + deletedAppName
2711                                + " no longer exists; removing its data";
2712                        // Actual deletion of code and data will be handled by later
2713                        // reconciliation step
2714                    } else {
2715                        // found an update; revoke system privileges
2716                        msg = "Updated system package + " + deletedAppName
2717                                + " no longer exists; revoking system privileges";
2718
2719                        // Don't do anything if a stub is removed from the system image. If
2720                        // we were to remove the uncompressed version from the /data partition,
2721                        // this is where it'd be done.
2722
2723                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2724                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2725                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2726                    }
2727                    logCriticalInfo(Log.WARN, msg);
2728                }
2729
2730                /*
2731                 * Make sure all system apps that we expected to appear on
2732                 * the userdata partition actually showed up. If they never
2733                 * appeared, crawl back and revive the system version.
2734                 */
2735                for (int i = 0; i < mExpectingBetter.size(); i++) {
2736                    final String packageName = mExpectingBetter.keyAt(i);
2737                    if (!mPackages.containsKey(packageName)) {
2738                        final File scanFile = mExpectingBetter.valueAt(i);
2739
2740                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2741                                + " but never showed up; reverting to system");
2742
2743                        int reparseFlags = mDefParseFlags;
2744                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2745                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2746                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2747                                    | PackageParser.PARSE_IS_PRIVILEGED;
2748                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2749                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2750                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2751                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2752                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2753                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2754                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2755                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2756                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2757                                    | PackageParser.PARSE_IS_OEM;
2758                        } else {
2759                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2760                            continue;
2761                        }
2762
2763                        mSettings.enableSystemPackageLPw(packageName);
2764
2765                        try {
2766                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2767                        } catch (PackageManagerException e) {
2768                            Slog.e(TAG, "Failed to parse original system package: "
2769                                    + e.getMessage());
2770                        }
2771                    }
2772                }
2773
2774                // Uncompress and install any stubbed system applications.
2775                // This must be done last to ensure all stubs are replaced or disabled.
2776                decompressSystemApplications(stubSystemApps, scanFlags);
2777
2778                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2779                                - cachedSystemApps;
2780
2781                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2782                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2783                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2784                        + " ms, packageCount: " + dataPackagesCount
2785                        + " , timePerPackage: "
2786                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2787                        + " , cached: " + cachedNonSystemApps);
2788                if (mIsUpgrade && dataPackagesCount > 0) {
2789                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2790                            ((int) dataScanTime) / dataPackagesCount);
2791                }
2792            }
2793            mExpectingBetter.clear();
2794
2795            // Resolve the storage manager.
2796            mStorageManagerPackage = getStorageManagerPackageName();
2797
2798            // Resolve protected action filters. Only the setup wizard is allowed to
2799            // have a high priority filter for these actions.
2800            mSetupWizardPackage = getSetupWizardPackageName();
2801            if (mProtectedFilters.size() > 0) {
2802                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2803                    Slog.i(TAG, "No setup wizard;"
2804                        + " All protected intents capped to priority 0");
2805                }
2806                for (ActivityIntentInfo filter : mProtectedFilters) {
2807                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2808                        if (DEBUG_FILTERS) {
2809                            Slog.i(TAG, "Found setup wizard;"
2810                                + " allow priority " + filter.getPriority() + ";"
2811                                + " package: " + filter.activity.info.packageName
2812                                + " activity: " + filter.activity.className
2813                                + " priority: " + filter.getPriority());
2814                        }
2815                        // skip setup wizard; allow it to keep the high priority filter
2816                        continue;
2817                    }
2818                    if (DEBUG_FILTERS) {
2819                        Slog.i(TAG, "Protected action; cap priority to 0;"
2820                                + " package: " + filter.activity.info.packageName
2821                                + " activity: " + filter.activity.className
2822                                + " origPrio: " + filter.getPriority());
2823                    }
2824                    filter.setPriority(0);
2825                }
2826            }
2827            mDeferProtectedFilters = false;
2828            mProtectedFilters.clear();
2829
2830            // Now that we know all of the shared libraries, update all clients to have
2831            // the correct library paths.
2832            updateAllSharedLibrariesLPw(null);
2833
2834            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2835                // NOTE: We ignore potential failures here during a system scan (like
2836                // the rest of the commands above) because there's precious little we
2837                // can do about it. A settings error is reported, though.
2838                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2839            }
2840
2841            // Now that we know all the packages we are keeping,
2842            // read and update their last usage times.
2843            mPackageUsage.read(mPackages);
2844            mCompilerStats.read();
2845
2846            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2847                    SystemClock.uptimeMillis());
2848            Slog.i(TAG, "Time to scan packages: "
2849                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2850                    + " seconds");
2851
2852            // If the platform SDK has changed since the last time we booted,
2853            // we need to re-grant app permission to catch any new ones that
2854            // appear.  This is really a hack, and means that apps can in some
2855            // cases get permissions that the user didn't initially explicitly
2856            // allow...  it would be nice to have some better way to handle
2857            // this situation.
2858            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2859            if (sdkUpdated) {
2860                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2861                        + mSdkVersion + "; regranting permissions for internal storage");
2862            }
2863            mPermissionManager.updateAllPermissions(
2864                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2865                    mPermissionCallback);
2866            ver.sdkVersion = mSdkVersion;
2867
2868            // If this is the first boot or an update from pre-M, and it is a normal
2869            // boot, then we need to initialize the default preferred apps across
2870            // all defined users.
2871            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2872                for (UserInfo user : sUserManager.getUsers(true)) {
2873                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2874                    applyFactoryDefaultBrowserLPw(user.id);
2875                    primeDomainVerificationsLPw(user.id);
2876                }
2877            }
2878
2879            // Prepare storage for system user really early during boot,
2880            // since core system apps like SettingsProvider and SystemUI
2881            // can't wait for user to start
2882            final int storageFlags;
2883            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2884                storageFlags = StorageManager.FLAG_STORAGE_DE;
2885            } else {
2886                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2887            }
2888            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2889                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2890                    true /* onlyCoreApps */);
2891            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2892                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2893                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2894                traceLog.traceBegin("AppDataFixup");
2895                try {
2896                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2897                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2898                } catch (InstallerException e) {
2899                    Slog.w(TAG, "Trouble fixing GIDs", e);
2900                }
2901                traceLog.traceEnd();
2902
2903                traceLog.traceBegin("AppDataPrepare");
2904                if (deferPackages == null || deferPackages.isEmpty()) {
2905                    return;
2906                }
2907                int count = 0;
2908                for (String pkgName : deferPackages) {
2909                    PackageParser.Package pkg = null;
2910                    synchronized (mPackages) {
2911                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2912                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2913                            pkg = ps.pkg;
2914                        }
2915                    }
2916                    if (pkg != null) {
2917                        synchronized (mInstallLock) {
2918                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2919                                    true /* maybeMigrateAppData */);
2920                        }
2921                        count++;
2922                    }
2923                }
2924                traceLog.traceEnd();
2925                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2926            }, "prepareAppData");
2927
2928            // If this is first boot after an OTA, and a normal boot, then
2929            // we need to clear code cache directories.
2930            // Note that we do *not* clear the application profiles. These remain valid
2931            // across OTAs and are used to drive profile verification (post OTA) and
2932            // profile compilation (without waiting to collect a fresh set of profiles).
2933            if (mIsUpgrade && !onlyCore) {
2934                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2935                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2936                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2937                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2938                        // No apps are running this early, so no need to freeze
2939                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2940                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2941                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2942                    }
2943                }
2944                ver.fingerprint = Build.FINGERPRINT;
2945            }
2946
2947            checkDefaultBrowser();
2948
2949            // clear only after permissions and other defaults have been updated
2950            mExistingSystemPackages.clear();
2951            mPromoteSystemApps = false;
2952
2953            // All the changes are done during package scanning.
2954            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2955
2956            // can downgrade to reader
2957            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2958            mSettings.writeLPr();
2959            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2960            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2961                    SystemClock.uptimeMillis());
2962
2963            if (!mOnlyCore) {
2964                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2965                mRequiredInstallerPackage = getRequiredInstallerLPr();
2966                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2967                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2968                if (mIntentFilterVerifierComponent != null) {
2969                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2970                            mIntentFilterVerifierComponent);
2971                } else {
2972                    mIntentFilterVerifier = null;
2973                }
2974                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2975                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2976                        SharedLibraryInfo.VERSION_UNDEFINED);
2977                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2978                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2979                        SharedLibraryInfo.VERSION_UNDEFINED);
2980            } else {
2981                mRequiredVerifierPackage = null;
2982                mRequiredInstallerPackage = null;
2983                mRequiredUninstallerPackage = null;
2984                mIntentFilterVerifierComponent = null;
2985                mIntentFilterVerifier = null;
2986                mServicesSystemSharedLibraryPackageName = null;
2987                mSharedSystemSharedLibraryPackageName = null;
2988            }
2989
2990            mInstallerService = new PackageInstallerService(context, this);
2991            final Pair<ComponentName, String> instantAppResolverComponent =
2992                    getInstantAppResolverLPr();
2993            if (instantAppResolverComponent != null) {
2994                if (DEBUG_EPHEMERAL) {
2995                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2996                }
2997                mInstantAppResolverConnection = new EphemeralResolverConnection(
2998                        mContext, instantAppResolverComponent.first,
2999                        instantAppResolverComponent.second);
3000                mInstantAppResolverSettingsComponent =
3001                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3002            } else {
3003                mInstantAppResolverConnection = null;
3004                mInstantAppResolverSettingsComponent = null;
3005            }
3006            updateInstantAppInstallerLocked(null);
3007
3008            // Read and update the usage of dex files.
3009            // Do this at the end of PM init so that all the packages have their
3010            // data directory reconciled.
3011            // At this point we know the code paths of the packages, so we can validate
3012            // the disk file and build the internal cache.
3013            // The usage file is expected to be small so loading and verifying it
3014            // should take a fairly small time compare to the other activities (e.g. package
3015            // scanning).
3016            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3017            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3018            for (int userId : currentUserIds) {
3019                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3020            }
3021            mDexManager.load(userPackages);
3022            if (mIsUpgrade) {
3023                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3024                        (int) (SystemClock.uptimeMillis() - startTime));
3025            }
3026        } // synchronized (mPackages)
3027        } // synchronized (mInstallLock)
3028
3029        // Now after opening every single application zip, make sure they
3030        // are all flushed.  Not really needed, but keeps things nice and
3031        // tidy.
3032        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3033        Runtime.getRuntime().gc();
3034        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3035
3036        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3037        FallbackCategoryProvider.loadFallbacks();
3038        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3039
3040        // The initial scanning above does many calls into installd while
3041        // holding the mPackages lock, but we're mostly interested in yelling
3042        // once we have a booted system.
3043        mInstaller.setWarnIfHeld(mPackages);
3044
3045        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3046    }
3047
3048    /**
3049     * Uncompress and install stub applications.
3050     * <p>In order to save space on the system partition, some applications are shipped in a
3051     * compressed form. In addition the compressed bits for the full application, the
3052     * system image contains a tiny stub comprised of only the Android manifest.
3053     * <p>During the first boot, attempt to uncompress and install the full application. If
3054     * the application can't be installed for any reason, disable the stub and prevent
3055     * uncompressing the full application during future boots.
3056     * <p>In order to forcefully attempt an installation of a full application, go to app
3057     * settings and enable the application.
3058     */
3059    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3060        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3061            final String pkgName = stubSystemApps.get(i);
3062            // skip if the system package is already disabled
3063            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3064                stubSystemApps.remove(i);
3065                continue;
3066            }
3067            // skip if the package isn't installed (?!); this should never happen
3068            final PackageParser.Package pkg = mPackages.get(pkgName);
3069            if (pkg == null) {
3070                stubSystemApps.remove(i);
3071                continue;
3072            }
3073            // skip if the package has been disabled by the user
3074            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3075            if (ps != null) {
3076                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3077                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3078                    stubSystemApps.remove(i);
3079                    continue;
3080                }
3081            }
3082
3083            if (DEBUG_COMPRESSION) {
3084                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3085            }
3086
3087            // uncompress the binary to its eventual destination on /data
3088            final File scanFile = decompressPackage(pkg);
3089            if (scanFile == null) {
3090                continue;
3091            }
3092
3093            // install the package to replace the stub on /system
3094            try {
3095                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3096                removePackageLI(pkg, true /*chatty*/);
3097                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3098                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3099                        UserHandle.USER_SYSTEM, "android");
3100                stubSystemApps.remove(i);
3101                continue;
3102            } catch (PackageManagerException e) {
3103                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3104            }
3105
3106            // any failed attempt to install the package will be cleaned up later
3107        }
3108
3109        // disable any stub still left; these failed to install the full application
3110        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3111            final String pkgName = stubSystemApps.get(i);
3112            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3113            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3114                    UserHandle.USER_SYSTEM, "android");
3115            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3116        }
3117    }
3118
3119    /**
3120     * Decompresses the given package on the system image onto
3121     * the /data partition.
3122     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3123     */
3124    private File decompressPackage(PackageParser.Package pkg) {
3125        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3126        if (compressedFiles == null || compressedFiles.length == 0) {
3127            if (DEBUG_COMPRESSION) {
3128                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3129            }
3130            return null;
3131        }
3132        final File dstCodePath =
3133                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3134        int ret = PackageManager.INSTALL_SUCCEEDED;
3135        try {
3136            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3137            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3138            for (File srcFile : compressedFiles) {
3139                final String srcFileName = srcFile.getName();
3140                final String dstFileName = srcFileName.substring(
3141                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3142                final File dstFile = new File(dstCodePath, dstFileName);
3143                ret = decompressFile(srcFile, dstFile);
3144                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3145                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3146                            + "; pkg: " + pkg.packageName
3147                            + ", file: " + dstFileName);
3148                    break;
3149                }
3150            }
3151        } catch (ErrnoException e) {
3152            logCriticalInfo(Log.ERROR, "Failed to decompress"
3153                    + "; pkg: " + pkg.packageName
3154                    + ", err: " + e.errno);
3155        }
3156        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3157            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3158            NativeLibraryHelper.Handle handle = null;
3159            try {
3160                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3161                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3162                        null /*abiOverride*/);
3163            } catch (IOException e) {
3164                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3165                        + "; pkg: " + pkg.packageName);
3166                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3167            } finally {
3168                IoUtils.closeQuietly(handle);
3169            }
3170        }
3171        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3172            if (dstCodePath == null || !dstCodePath.exists()) {
3173                return null;
3174            }
3175            removeCodePathLI(dstCodePath);
3176            return null;
3177        }
3178
3179        return dstCodePath;
3180    }
3181
3182    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3183        // we're only interested in updating the installer appliction when 1) it's not
3184        // already set or 2) the modified package is the installer
3185        if (mInstantAppInstallerActivity != null
3186                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3187                        .equals(modifiedPackage)) {
3188            return;
3189        }
3190        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3191    }
3192
3193    private static File preparePackageParserCache(boolean isUpgrade) {
3194        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3195            return null;
3196        }
3197
3198        // Disable package parsing on eng builds to allow for faster incremental development.
3199        if (Build.IS_ENG) {
3200            return null;
3201        }
3202
3203        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3204            Slog.i(TAG, "Disabling package parser cache due to system property.");
3205            return null;
3206        }
3207
3208        // The base directory for the package parser cache lives under /data/system/.
3209        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3210                "package_cache");
3211        if (cacheBaseDir == null) {
3212            return null;
3213        }
3214
3215        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3216        // This also serves to "GC" unused entries when the package cache version changes (which
3217        // can only happen during upgrades).
3218        if (isUpgrade) {
3219            FileUtils.deleteContents(cacheBaseDir);
3220        }
3221
3222
3223        // Return the versioned package cache directory. This is something like
3224        // "/data/system/package_cache/1"
3225        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3226
3227        // The following is a workaround to aid development on non-numbered userdebug
3228        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3229        // the system partition is newer.
3230        //
3231        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3232        // that starts with "eng." to signify that this is an engineering build and not
3233        // destined for release.
3234        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3235            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3236
3237            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3238            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3239            // in general and should not be used for production changes. In this specific case,
3240            // we know that they will work.
3241            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3242            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3243                FileUtils.deleteContents(cacheBaseDir);
3244                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3245            }
3246        }
3247
3248        return cacheDir;
3249    }
3250
3251    @Override
3252    public boolean isFirstBoot() {
3253        // allow instant applications
3254        return mFirstBoot;
3255    }
3256
3257    @Override
3258    public boolean isOnlyCoreApps() {
3259        // allow instant applications
3260        return mOnlyCore;
3261    }
3262
3263    @Override
3264    public boolean isUpgrade() {
3265        // allow instant applications
3266        // The system property allows testing ota flow when upgraded to the same image.
3267        return mIsUpgrade || SystemProperties.getBoolean(
3268                "persist.pm.mock-upgrade", false /* default */);
3269    }
3270
3271    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3272        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3273
3274        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3275                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3276                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3277        if (matches.size() == 1) {
3278            return matches.get(0).getComponentInfo().packageName;
3279        } else if (matches.size() == 0) {
3280            Log.e(TAG, "There should probably be a verifier, but, none were found");
3281            return null;
3282        }
3283        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3284    }
3285
3286    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3287        synchronized (mPackages) {
3288            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3289            if (libraryEntry == null) {
3290                throw new IllegalStateException("Missing required shared library:" + name);
3291            }
3292            return libraryEntry.apk;
3293        }
3294    }
3295
3296    private @NonNull String getRequiredInstallerLPr() {
3297        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3298        intent.addCategory(Intent.CATEGORY_DEFAULT);
3299        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3300
3301        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3302                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3303                UserHandle.USER_SYSTEM);
3304        if (matches.size() == 1) {
3305            ResolveInfo resolveInfo = matches.get(0);
3306            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3307                throw new RuntimeException("The installer must be a privileged app");
3308            }
3309            return matches.get(0).getComponentInfo().packageName;
3310        } else {
3311            throw new RuntimeException("There must be exactly one installer; found " + matches);
3312        }
3313    }
3314
3315    private @NonNull String getRequiredUninstallerLPr() {
3316        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3317        intent.addCategory(Intent.CATEGORY_DEFAULT);
3318        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3319
3320        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3321                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3322                UserHandle.USER_SYSTEM);
3323        if (resolveInfo == null ||
3324                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3325            throw new RuntimeException("There must be exactly one uninstaller; found "
3326                    + resolveInfo);
3327        }
3328        return resolveInfo.getComponentInfo().packageName;
3329    }
3330
3331    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3332        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3333
3334        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3335                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3336                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3337        ResolveInfo best = null;
3338        final int N = matches.size();
3339        for (int i = 0; i < N; i++) {
3340            final ResolveInfo cur = matches.get(i);
3341            final String packageName = cur.getComponentInfo().packageName;
3342            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3343                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3344                continue;
3345            }
3346
3347            if (best == null || cur.priority > best.priority) {
3348                best = cur;
3349            }
3350        }
3351
3352        if (best != null) {
3353            return best.getComponentInfo().getComponentName();
3354        }
3355        Slog.w(TAG, "Intent filter verifier not found");
3356        return null;
3357    }
3358
3359    @Override
3360    public @Nullable ComponentName getInstantAppResolverComponent() {
3361        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3362            return null;
3363        }
3364        synchronized (mPackages) {
3365            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3366            if (instantAppResolver == null) {
3367                return null;
3368            }
3369            return instantAppResolver.first;
3370        }
3371    }
3372
3373    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3374        final String[] packageArray =
3375                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3376        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3377            if (DEBUG_EPHEMERAL) {
3378                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3379            }
3380            return null;
3381        }
3382
3383        final int callingUid = Binder.getCallingUid();
3384        final int resolveFlags =
3385                MATCH_DIRECT_BOOT_AWARE
3386                | MATCH_DIRECT_BOOT_UNAWARE
3387                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3388        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3389        final Intent resolverIntent = new Intent(actionName);
3390        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3391                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3392        // temporarily look for the old action
3393        if (resolvers.size() == 0) {
3394            if (DEBUG_EPHEMERAL) {
3395                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3396            }
3397            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3398            resolverIntent.setAction(actionName);
3399            resolvers = queryIntentServicesInternal(resolverIntent, null,
3400                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3401        }
3402        final int N = resolvers.size();
3403        if (N == 0) {
3404            if (DEBUG_EPHEMERAL) {
3405                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3406            }
3407            return null;
3408        }
3409
3410        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3411        for (int i = 0; i < N; i++) {
3412            final ResolveInfo info = resolvers.get(i);
3413
3414            if (info.serviceInfo == null) {
3415                continue;
3416            }
3417
3418            final String packageName = info.serviceInfo.packageName;
3419            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3420                if (DEBUG_EPHEMERAL) {
3421                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3422                            + " pkg: " + packageName + ", info:" + info);
3423                }
3424                continue;
3425            }
3426
3427            if (DEBUG_EPHEMERAL) {
3428                Slog.v(TAG, "Ephemeral resolver found;"
3429                        + " pkg: " + packageName + ", info:" + info);
3430            }
3431            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3432        }
3433        if (DEBUG_EPHEMERAL) {
3434            Slog.v(TAG, "Ephemeral resolver NOT found");
3435        }
3436        return null;
3437    }
3438
3439    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3440        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3441        intent.addCategory(Intent.CATEGORY_DEFAULT);
3442        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3443
3444        final int resolveFlags =
3445                MATCH_DIRECT_BOOT_AWARE
3446                | MATCH_DIRECT_BOOT_UNAWARE
3447                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3448        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3449                resolveFlags, UserHandle.USER_SYSTEM);
3450        // temporarily look for the old action
3451        if (matches.isEmpty()) {
3452            if (DEBUG_EPHEMERAL) {
3453                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3454            }
3455            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3456            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3457                    resolveFlags, UserHandle.USER_SYSTEM);
3458        }
3459        Iterator<ResolveInfo> iter = matches.iterator();
3460        while (iter.hasNext()) {
3461            final ResolveInfo rInfo = iter.next();
3462            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3463            if (ps != null) {
3464                final PermissionsState permissionsState = ps.getPermissionsState();
3465                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3466                    continue;
3467                }
3468            }
3469            iter.remove();
3470        }
3471        if (matches.size() == 0) {
3472            return null;
3473        } else if (matches.size() == 1) {
3474            return (ActivityInfo) matches.get(0).getComponentInfo();
3475        } else {
3476            throw new RuntimeException(
3477                    "There must be at most one ephemeral installer; found " + matches);
3478        }
3479    }
3480
3481    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3482            @NonNull ComponentName resolver) {
3483        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3484                .addCategory(Intent.CATEGORY_DEFAULT)
3485                .setPackage(resolver.getPackageName());
3486        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3487        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3488                UserHandle.USER_SYSTEM);
3489        // temporarily look for the old action
3490        if (matches.isEmpty()) {
3491            if (DEBUG_EPHEMERAL) {
3492                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3493            }
3494            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3495            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3496                    UserHandle.USER_SYSTEM);
3497        }
3498        if (matches.isEmpty()) {
3499            return null;
3500        }
3501        return matches.get(0).getComponentInfo().getComponentName();
3502    }
3503
3504    private void primeDomainVerificationsLPw(int userId) {
3505        if (DEBUG_DOMAIN_VERIFICATION) {
3506            Slog.d(TAG, "Priming domain verifications in user " + userId);
3507        }
3508
3509        SystemConfig systemConfig = SystemConfig.getInstance();
3510        ArraySet<String> packages = systemConfig.getLinkedApps();
3511
3512        for (String packageName : packages) {
3513            PackageParser.Package pkg = mPackages.get(packageName);
3514            if (pkg != null) {
3515                if (!pkg.isSystem()) {
3516                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3517                    continue;
3518                }
3519
3520                ArraySet<String> domains = null;
3521                for (PackageParser.Activity a : pkg.activities) {
3522                    for (ActivityIntentInfo filter : a.intents) {
3523                        if (hasValidDomains(filter)) {
3524                            if (domains == null) {
3525                                domains = new ArraySet<String>();
3526                            }
3527                            domains.addAll(filter.getHostsList());
3528                        }
3529                    }
3530                }
3531
3532                if (domains != null && domains.size() > 0) {
3533                    if (DEBUG_DOMAIN_VERIFICATION) {
3534                        Slog.v(TAG, "      + " + packageName);
3535                    }
3536                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3537                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3538                    // and then 'always' in the per-user state actually used for intent resolution.
3539                    final IntentFilterVerificationInfo ivi;
3540                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3541                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3542                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3543                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3544                } else {
3545                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3546                            + "' does not handle web links");
3547                }
3548            } else {
3549                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3550            }
3551        }
3552
3553        scheduleWritePackageRestrictionsLocked(userId);
3554        scheduleWriteSettingsLocked();
3555    }
3556
3557    private void applyFactoryDefaultBrowserLPw(int userId) {
3558        // The default browser app's package name is stored in a string resource,
3559        // with a product-specific overlay used for vendor customization.
3560        String browserPkg = mContext.getResources().getString(
3561                com.android.internal.R.string.default_browser);
3562        if (!TextUtils.isEmpty(browserPkg)) {
3563            // non-empty string => required to be a known package
3564            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3565            if (ps == null) {
3566                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3567                browserPkg = null;
3568            } else {
3569                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3570            }
3571        }
3572
3573        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3574        // default.  If there's more than one, just leave everything alone.
3575        if (browserPkg == null) {
3576            calculateDefaultBrowserLPw(userId);
3577        }
3578    }
3579
3580    private void calculateDefaultBrowserLPw(int userId) {
3581        List<String> allBrowsers = resolveAllBrowserApps(userId);
3582        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3583        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3584    }
3585
3586    private List<String> resolveAllBrowserApps(int userId) {
3587        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3588        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3589                PackageManager.MATCH_ALL, userId);
3590
3591        final int count = list.size();
3592        List<String> result = new ArrayList<String>(count);
3593        for (int i=0; i<count; i++) {
3594            ResolveInfo info = list.get(i);
3595            if (info.activityInfo == null
3596                    || !info.handleAllWebDataURI
3597                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3598                    || result.contains(info.activityInfo.packageName)) {
3599                continue;
3600            }
3601            result.add(info.activityInfo.packageName);
3602        }
3603
3604        return result;
3605    }
3606
3607    private boolean packageIsBrowser(String packageName, int userId) {
3608        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3609                PackageManager.MATCH_ALL, userId);
3610        final int N = list.size();
3611        for (int i = 0; i < N; i++) {
3612            ResolveInfo info = list.get(i);
3613            if (packageName.equals(info.activityInfo.packageName)) {
3614                return true;
3615            }
3616        }
3617        return false;
3618    }
3619
3620    private void checkDefaultBrowser() {
3621        final int myUserId = UserHandle.myUserId();
3622        final String packageName = getDefaultBrowserPackageName(myUserId);
3623        if (packageName != null) {
3624            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3625            if (info == null) {
3626                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3627                synchronized (mPackages) {
3628                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3629                }
3630            }
3631        }
3632    }
3633
3634    @Override
3635    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3636            throws RemoteException {
3637        try {
3638            return super.onTransact(code, data, reply, flags);
3639        } catch (RuntimeException e) {
3640            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3641                Slog.wtf(TAG, "Package Manager Crash", e);
3642            }
3643            throw e;
3644        }
3645    }
3646
3647    static int[] appendInts(int[] cur, int[] add) {
3648        if (add == null) return cur;
3649        if (cur == null) return add;
3650        final int N = add.length;
3651        for (int i=0; i<N; i++) {
3652            cur = appendInt(cur, add[i]);
3653        }
3654        return cur;
3655    }
3656
3657    /**
3658     * Returns whether or not a full application can see an instant application.
3659     * <p>
3660     * Currently, there are three cases in which this can occur:
3661     * <ol>
3662     * <li>The calling application is a "special" process. Special processes
3663     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3664     * <li>The calling application has the permission
3665     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3666     * <li>The calling application is the default launcher on the
3667     *     system partition.</li>
3668     * </ol>
3669     */
3670    private boolean canViewInstantApps(int callingUid, int userId) {
3671        if (callingUid < Process.FIRST_APPLICATION_UID) {
3672            return true;
3673        }
3674        if (mContext.checkCallingOrSelfPermission(
3675                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3676            return true;
3677        }
3678        if (mContext.checkCallingOrSelfPermission(
3679                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3680            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3681            if (homeComponent != null
3682                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3683                return true;
3684            }
3685        }
3686        return false;
3687    }
3688
3689    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3690        if (!sUserManager.exists(userId)) return null;
3691        if (ps == null) {
3692            return null;
3693        }
3694        PackageParser.Package p = ps.pkg;
3695        if (p == null) {
3696            return null;
3697        }
3698        final int callingUid = Binder.getCallingUid();
3699        // Filter out ephemeral app metadata:
3700        //   * The system/shell/root can see metadata for any app
3701        //   * An installed app can see metadata for 1) other installed apps
3702        //     and 2) ephemeral apps that have explicitly interacted with it
3703        //   * Ephemeral apps can only see their own data and exposed installed apps
3704        //   * Holding a signature permission allows seeing instant apps
3705        if (filterAppAccessLPr(ps, callingUid, userId)) {
3706            return null;
3707        }
3708
3709        final PermissionsState permissionsState = ps.getPermissionsState();
3710
3711        // Compute GIDs only if requested
3712        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3713                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3714        // Compute granted permissions only if package has requested permissions
3715        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3716                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3717        final PackageUserState state = ps.readUserState(userId);
3718
3719        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3720                && ps.isSystem()) {
3721            flags |= MATCH_ANY_USER;
3722        }
3723
3724        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3725                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3726
3727        if (packageInfo == null) {
3728            return null;
3729        }
3730
3731        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3732                resolveExternalPackageNameLPr(p);
3733
3734        return packageInfo;
3735    }
3736
3737    @Override
3738    public void checkPackageStartable(String packageName, int userId) {
3739        final int callingUid = Binder.getCallingUid();
3740        if (getInstantAppPackageName(callingUid) != null) {
3741            throw new SecurityException("Instant applications don't have access to this method");
3742        }
3743        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3744        synchronized (mPackages) {
3745            final PackageSetting ps = mSettings.mPackages.get(packageName);
3746            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3747                throw new SecurityException("Package " + packageName + " was not found!");
3748            }
3749
3750            if (!ps.getInstalled(userId)) {
3751                throw new SecurityException(
3752                        "Package " + packageName + " was not installed for user " + userId + "!");
3753            }
3754
3755            if (mSafeMode && !ps.isSystem()) {
3756                throw new SecurityException("Package " + packageName + " not a system app!");
3757            }
3758
3759            if (mFrozenPackages.contains(packageName)) {
3760                throw new SecurityException("Package " + packageName + " is currently frozen!");
3761            }
3762
3763            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3764                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3765            }
3766        }
3767    }
3768
3769    @Override
3770    public boolean isPackageAvailable(String packageName, int userId) {
3771        if (!sUserManager.exists(userId)) return false;
3772        final int callingUid = Binder.getCallingUid();
3773        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3774                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3775        synchronized (mPackages) {
3776            PackageParser.Package p = mPackages.get(packageName);
3777            if (p != null) {
3778                final PackageSetting ps = (PackageSetting) p.mExtras;
3779                if (filterAppAccessLPr(ps, callingUid, userId)) {
3780                    return false;
3781                }
3782                if (ps != null) {
3783                    final PackageUserState state = ps.readUserState(userId);
3784                    if (state != null) {
3785                        return PackageParser.isAvailable(state);
3786                    }
3787                }
3788            }
3789        }
3790        return false;
3791    }
3792
3793    @Override
3794    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3795        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3796                flags, Binder.getCallingUid(), userId);
3797    }
3798
3799    @Override
3800    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3801            int flags, int userId) {
3802        return getPackageInfoInternal(versionedPackage.getPackageName(),
3803                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3804    }
3805
3806    /**
3807     * Important: The provided filterCallingUid is used exclusively to filter out packages
3808     * that can be seen based on user state. It's typically the original caller uid prior
3809     * to clearing. Because it can only be provided by trusted code, it's value can be
3810     * trusted and will be used as-is; unlike userId which will be validated by this method.
3811     */
3812    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3813            int flags, int filterCallingUid, int userId) {
3814        if (!sUserManager.exists(userId)) return null;
3815        flags = updateFlagsForPackage(flags, userId, packageName);
3816        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3817                false /* requireFullPermission */, false /* checkShell */, "get package info");
3818
3819        // reader
3820        synchronized (mPackages) {
3821            // Normalize package name to handle renamed packages and static libs
3822            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3823
3824            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3825            if (matchFactoryOnly) {
3826                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3827                if (ps != null) {
3828                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3829                        return null;
3830                    }
3831                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3832                        return null;
3833                    }
3834                    return generatePackageInfo(ps, flags, userId);
3835                }
3836            }
3837
3838            PackageParser.Package p = mPackages.get(packageName);
3839            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3840                return null;
3841            }
3842            if (DEBUG_PACKAGE_INFO)
3843                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3844            if (p != null) {
3845                final PackageSetting ps = (PackageSetting) p.mExtras;
3846                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3847                    return null;
3848                }
3849                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3850                    return null;
3851                }
3852                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3853            }
3854            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3855                final PackageSetting ps = mSettings.mPackages.get(packageName);
3856                if (ps == null) return null;
3857                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3858                    return null;
3859                }
3860                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3861                    return null;
3862                }
3863                return generatePackageInfo(ps, flags, userId);
3864            }
3865        }
3866        return null;
3867    }
3868
3869    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3870        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3871            return true;
3872        }
3873        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3874            return true;
3875        }
3876        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3877            return true;
3878        }
3879        return false;
3880    }
3881
3882    private boolean isComponentVisibleToInstantApp(
3883            @Nullable ComponentName component, @ComponentType int type) {
3884        if (type == TYPE_ACTIVITY) {
3885            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3886            return activity != null
3887                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3888                    : false;
3889        } else if (type == TYPE_RECEIVER) {
3890            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3891            return activity != null
3892                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3893                    : false;
3894        } else if (type == TYPE_SERVICE) {
3895            final PackageParser.Service service = mServices.mServices.get(component);
3896            return service != null
3897                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3898                    : false;
3899        } else if (type == TYPE_PROVIDER) {
3900            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3901            return provider != null
3902                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3903                    : false;
3904        } else if (type == TYPE_UNKNOWN) {
3905            return isComponentVisibleToInstantApp(component);
3906        }
3907        return false;
3908    }
3909
3910    /**
3911     * Returns whether or not access to the application should be filtered.
3912     * <p>
3913     * Access may be limited based upon whether the calling or target applications
3914     * are instant applications.
3915     *
3916     * @see #canAccessInstantApps(int)
3917     */
3918    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3919            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3920        // if we're in an isolated process, get the real calling UID
3921        if (Process.isIsolated(callingUid)) {
3922            callingUid = mIsolatedOwners.get(callingUid);
3923        }
3924        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3925        final boolean callerIsInstantApp = instantAppPkgName != null;
3926        if (ps == null) {
3927            if (callerIsInstantApp) {
3928                // pretend the application exists, but, needs to be filtered
3929                return true;
3930            }
3931            return false;
3932        }
3933        // if the target and caller are the same application, don't filter
3934        if (isCallerSameApp(ps.name, callingUid)) {
3935            return false;
3936        }
3937        if (callerIsInstantApp) {
3938            // request for a specific component; if it hasn't been explicitly exposed, filter
3939            if (component != null) {
3940                return !isComponentVisibleToInstantApp(component, componentType);
3941            }
3942            // request for application; if no components have been explicitly exposed, filter
3943            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3944        }
3945        if (ps.getInstantApp(userId)) {
3946            // caller can see all components of all instant applications, don't filter
3947            if (canViewInstantApps(callingUid, userId)) {
3948                return false;
3949            }
3950            // request for a specific instant application component, filter
3951            if (component != null) {
3952                return true;
3953            }
3954            // request for an instant application; if the caller hasn't been granted access, filter
3955            return !mInstantAppRegistry.isInstantAccessGranted(
3956                    userId, UserHandle.getAppId(callingUid), ps.appId);
3957        }
3958        return false;
3959    }
3960
3961    /**
3962     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3963     */
3964    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3965        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3966    }
3967
3968    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3969            int flags) {
3970        // Callers can access only the libs they depend on, otherwise they need to explicitly
3971        // ask for the shared libraries given the caller is allowed to access all static libs.
3972        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3973            // System/shell/root get to see all static libs
3974            final int appId = UserHandle.getAppId(uid);
3975            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3976                    || appId == Process.ROOT_UID) {
3977                return false;
3978            }
3979        }
3980
3981        // No package means no static lib as it is always on internal storage
3982        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3983            return false;
3984        }
3985
3986        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3987                ps.pkg.staticSharedLibVersion);
3988        if (libEntry == null) {
3989            return false;
3990        }
3991
3992        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3993        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3994        if (uidPackageNames == null) {
3995            return true;
3996        }
3997
3998        for (String uidPackageName : uidPackageNames) {
3999            if (ps.name.equals(uidPackageName)) {
4000                return false;
4001            }
4002            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4003            if (uidPs != null) {
4004                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4005                        libEntry.info.getName());
4006                if (index < 0) {
4007                    continue;
4008                }
4009                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4010                    return false;
4011                }
4012            }
4013        }
4014        return true;
4015    }
4016
4017    @Override
4018    public String[] currentToCanonicalPackageNames(String[] names) {
4019        final int callingUid = Binder.getCallingUid();
4020        if (getInstantAppPackageName(callingUid) != null) {
4021            return names;
4022        }
4023        final String[] out = new String[names.length];
4024        // reader
4025        synchronized (mPackages) {
4026            final int callingUserId = UserHandle.getUserId(callingUid);
4027            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4028            for (int i=names.length-1; i>=0; i--) {
4029                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4030                boolean translateName = false;
4031                if (ps != null && ps.realName != null) {
4032                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4033                    translateName = !targetIsInstantApp
4034                            || canViewInstantApps
4035                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4036                                    UserHandle.getAppId(callingUid), ps.appId);
4037                }
4038                out[i] = translateName ? ps.realName : names[i];
4039            }
4040        }
4041        return out;
4042    }
4043
4044    @Override
4045    public String[] canonicalToCurrentPackageNames(String[] names) {
4046        final int callingUid = Binder.getCallingUid();
4047        if (getInstantAppPackageName(callingUid) != null) {
4048            return names;
4049        }
4050        final String[] out = new String[names.length];
4051        // reader
4052        synchronized (mPackages) {
4053            final int callingUserId = UserHandle.getUserId(callingUid);
4054            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4055            for (int i=names.length-1; i>=0; i--) {
4056                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4057                boolean translateName = false;
4058                if (cur != null) {
4059                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4060                    final boolean targetIsInstantApp =
4061                            ps != null && ps.getInstantApp(callingUserId);
4062                    translateName = !targetIsInstantApp
4063                            || canViewInstantApps
4064                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4065                                    UserHandle.getAppId(callingUid), ps.appId);
4066                }
4067                out[i] = translateName ? cur : names[i];
4068            }
4069        }
4070        return out;
4071    }
4072
4073    @Override
4074    public int getPackageUid(String packageName, int flags, int userId) {
4075        if (!sUserManager.exists(userId)) return -1;
4076        final int callingUid = Binder.getCallingUid();
4077        flags = updateFlagsForPackage(flags, userId, packageName);
4078        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4079                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4080
4081        // reader
4082        synchronized (mPackages) {
4083            final PackageParser.Package p = mPackages.get(packageName);
4084            if (p != null && p.isMatch(flags)) {
4085                PackageSetting ps = (PackageSetting) p.mExtras;
4086                if (filterAppAccessLPr(ps, callingUid, userId)) {
4087                    return -1;
4088                }
4089                return UserHandle.getUid(userId, p.applicationInfo.uid);
4090            }
4091            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4092                final PackageSetting ps = mSettings.mPackages.get(packageName);
4093                if (ps != null && ps.isMatch(flags)
4094                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4095                    return UserHandle.getUid(userId, ps.appId);
4096                }
4097            }
4098        }
4099
4100        return -1;
4101    }
4102
4103    @Override
4104    public int[] getPackageGids(String packageName, int flags, int userId) {
4105        if (!sUserManager.exists(userId)) return null;
4106        final int callingUid = Binder.getCallingUid();
4107        flags = updateFlagsForPackage(flags, userId, packageName);
4108        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4109                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4110
4111        // reader
4112        synchronized (mPackages) {
4113            final PackageParser.Package p = mPackages.get(packageName);
4114            if (p != null && p.isMatch(flags)) {
4115                PackageSetting ps = (PackageSetting) p.mExtras;
4116                if (filterAppAccessLPr(ps, callingUid, userId)) {
4117                    return null;
4118                }
4119                // TODO: Shouldn't this be checking for package installed state for userId and
4120                // return null?
4121                return ps.getPermissionsState().computeGids(userId);
4122            }
4123            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4124                final PackageSetting ps = mSettings.mPackages.get(packageName);
4125                if (ps != null && ps.isMatch(flags)
4126                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4127                    return ps.getPermissionsState().computeGids(userId);
4128                }
4129            }
4130        }
4131
4132        return null;
4133    }
4134
4135    @Override
4136    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4137        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4138    }
4139
4140    @Override
4141    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4142            int flags) {
4143        final List<PermissionInfo> permissionList =
4144                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4145        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4146    }
4147
4148    @Override
4149    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4150        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4151    }
4152
4153    @Override
4154    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4155        final List<PermissionGroupInfo> permissionList =
4156                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4157        return (permissionList == null)
4158                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4159    }
4160
4161    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4162            int filterCallingUid, int userId) {
4163        if (!sUserManager.exists(userId)) return null;
4164        PackageSetting ps = mSettings.mPackages.get(packageName);
4165        if (ps != null) {
4166            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4167                return null;
4168            }
4169            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4170                return null;
4171            }
4172            if (ps.pkg == null) {
4173                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4174                if (pInfo != null) {
4175                    return pInfo.applicationInfo;
4176                }
4177                return null;
4178            }
4179            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4180                    ps.readUserState(userId), userId);
4181            if (ai != null) {
4182                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4183            }
4184            return ai;
4185        }
4186        return null;
4187    }
4188
4189    @Override
4190    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4191        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4192    }
4193
4194    /**
4195     * Important: The provided filterCallingUid is used exclusively to filter out applications
4196     * that can be seen based on user state. It's typically the original caller uid prior
4197     * to clearing. Because it can only be provided by trusted code, it's value can be
4198     * trusted and will be used as-is; unlike userId which will be validated by this method.
4199     */
4200    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4201            int filterCallingUid, int userId) {
4202        if (!sUserManager.exists(userId)) return null;
4203        flags = updateFlagsForApplication(flags, userId, packageName);
4204        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4205                false /* requireFullPermission */, false /* checkShell */, "get application info");
4206
4207        // writer
4208        synchronized (mPackages) {
4209            // Normalize package name to handle renamed packages and static libs
4210            packageName = resolveInternalPackageNameLPr(packageName,
4211                    PackageManager.VERSION_CODE_HIGHEST);
4212
4213            PackageParser.Package p = mPackages.get(packageName);
4214            if (DEBUG_PACKAGE_INFO) Log.v(
4215                    TAG, "getApplicationInfo " + packageName
4216                    + ": " + p);
4217            if (p != null) {
4218                PackageSetting ps = mSettings.mPackages.get(packageName);
4219                if (ps == null) return null;
4220                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4221                    return null;
4222                }
4223                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4224                    return null;
4225                }
4226                // Note: isEnabledLP() does not apply here - always return info
4227                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4228                        p, flags, ps.readUserState(userId), userId);
4229                if (ai != null) {
4230                    ai.packageName = resolveExternalPackageNameLPr(p);
4231                }
4232                return ai;
4233            }
4234            if ("android".equals(packageName)||"system".equals(packageName)) {
4235                return mAndroidApplication;
4236            }
4237            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4238                // Already generates the external package name
4239                return generateApplicationInfoFromSettingsLPw(packageName,
4240                        flags, filterCallingUid, userId);
4241            }
4242        }
4243        return null;
4244    }
4245
4246    private String normalizePackageNameLPr(String packageName) {
4247        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4248        return normalizedPackageName != null ? normalizedPackageName : packageName;
4249    }
4250
4251    @Override
4252    public void deletePreloadsFileCache() {
4253        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4254            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4255        }
4256        File dir = Environment.getDataPreloadsFileCacheDirectory();
4257        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4258        FileUtils.deleteContents(dir);
4259    }
4260
4261    @Override
4262    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4263            final int storageFlags, final IPackageDataObserver observer) {
4264        mContext.enforceCallingOrSelfPermission(
4265                android.Manifest.permission.CLEAR_APP_CACHE, null);
4266        mHandler.post(() -> {
4267            boolean success = false;
4268            try {
4269                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4270                success = true;
4271            } catch (IOException e) {
4272                Slog.w(TAG, e);
4273            }
4274            if (observer != null) {
4275                try {
4276                    observer.onRemoveCompleted(null, success);
4277                } catch (RemoteException e) {
4278                    Slog.w(TAG, e);
4279                }
4280            }
4281        });
4282    }
4283
4284    @Override
4285    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4286            final int storageFlags, final IntentSender pi) {
4287        mContext.enforceCallingOrSelfPermission(
4288                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4289        mHandler.post(() -> {
4290            boolean success = false;
4291            try {
4292                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4293                success = true;
4294            } catch (IOException e) {
4295                Slog.w(TAG, e);
4296            }
4297            if (pi != null) {
4298                try {
4299                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4300                } catch (SendIntentException e) {
4301                    Slog.w(TAG, e);
4302                }
4303            }
4304        });
4305    }
4306
4307    /**
4308     * Blocking call to clear various types of cached data across the system
4309     * until the requested bytes are available.
4310     */
4311    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4312        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4313        final File file = storage.findPathForUuid(volumeUuid);
4314        if (file.getUsableSpace() >= bytes) return;
4315
4316        if (ENABLE_FREE_CACHE_V2) {
4317            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4318                    volumeUuid);
4319            final boolean aggressive = (storageFlags
4320                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4321            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4322
4323            // 1. Pre-flight to determine if we have any chance to succeed
4324            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4325            if (internalVolume && (aggressive || SystemProperties
4326                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4327                deletePreloadsFileCache();
4328                if (file.getUsableSpace() >= bytes) return;
4329            }
4330
4331            // 3. Consider parsed APK data (aggressive only)
4332            if (internalVolume && aggressive) {
4333                FileUtils.deleteContents(mCacheDir);
4334                if (file.getUsableSpace() >= bytes) return;
4335            }
4336
4337            // 4. Consider cached app data (above quotas)
4338            try {
4339                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4340                        Installer.FLAG_FREE_CACHE_V2);
4341            } catch (InstallerException ignored) {
4342            }
4343            if (file.getUsableSpace() >= bytes) return;
4344
4345            // 5. Consider shared libraries with refcount=0 and age>min cache period
4346            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4347                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4348                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4349                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4350                return;
4351            }
4352
4353            // 6. Consider dexopt output (aggressive only)
4354            // TODO: Implement
4355
4356            // 7. Consider installed instant apps unused longer than min cache period
4357            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4358                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4359                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4360                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4361                return;
4362            }
4363
4364            // 8. Consider cached app data (below quotas)
4365            try {
4366                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4367                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4368            } catch (InstallerException ignored) {
4369            }
4370            if (file.getUsableSpace() >= bytes) return;
4371
4372            // 9. Consider DropBox entries
4373            // TODO: Implement
4374
4375            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4376            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4377                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4378                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4379                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4380                return;
4381            }
4382        } else {
4383            try {
4384                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4385            } catch (InstallerException ignored) {
4386            }
4387            if (file.getUsableSpace() >= bytes) return;
4388        }
4389
4390        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4391    }
4392
4393    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4394            throws IOException {
4395        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4396        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4397
4398        List<VersionedPackage> packagesToDelete = null;
4399        final long now = System.currentTimeMillis();
4400
4401        synchronized (mPackages) {
4402            final int[] allUsers = sUserManager.getUserIds();
4403            final int libCount = mSharedLibraries.size();
4404            for (int i = 0; i < libCount; i++) {
4405                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4406                if (versionedLib == null) {
4407                    continue;
4408                }
4409                final int versionCount = versionedLib.size();
4410                for (int j = 0; j < versionCount; j++) {
4411                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4412                    // Skip packages that are not static shared libs.
4413                    if (!libInfo.isStatic()) {
4414                        break;
4415                    }
4416                    // Important: We skip static shared libs used for some user since
4417                    // in such a case we need to keep the APK on the device. The check for
4418                    // a lib being used for any user is performed by the uninstall call.
4419                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4420                    // Resolve the package name - we use synthetic package names internally
4421                    final String internalPackageName = resolveInternalPackageNameLPr(
4422                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4423                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4424                    // Skip unused static shared libs cached less than the min period
4425                    // to prevent pruning a lib needed by a subsequently installed package.
4426                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4427                        continue;
4428                    }
4429                    if (packagesToDelete == null) {
4430                        packagesToDelete = new ArrayList<>();
4431                    }
4432                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4433                            declaringPackage.getVersionCode()));
4434                }
4435            }
4436        }
4437
4438        if (packagesToDelete != null) {
4439            final int packageCount = packagesToDelete.size();
4440            for (int i = 0; i < packageCount; i++) {
4441                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4442                // Delete the package synchronously (will fail of the lib used for any user).
4443                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4444                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4445                                == PackageManager.DELETE_SUCCEEDED) {
4446                    if (volume.getUsableSpace() >= neededSpace) {
4447                        return true;
4448                    }
4449                }
4450            }
4451        }
4452
4453        return false;
4454    }
4455
4456    /**
4457     * Update given flags based on encryption status of current user.
4458     */
4459    private int updateFlags(int flags, int userId) {
4460        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4461                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4462            // Caller expressed an explicit opinion about what encryption
4463            // aware/unaware components they want to see, so fall through and
4464            // give them what they want
4465        } else {
4466            // Caller expressed no opinion, so match based on user state
4467            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4468                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4469            } else {
4470                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4471            }
4472        }
4473        return flags;
4474    }
4475
4476    private UserManagerInternal getUserManagerInternal() {
4477        if (mUserManagerInternal == null) {
4478            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4479        }
4480        return mUserManagerInternal;
4481    }
4482
4483    private DeviceIdleController.LocalService getDeviceIdleController() {
4484        if (mDeviceIdleController == null) {
4485            mDeviceIdleController =
4486                    LocalServices.getService(DeviceIdleController.LocalService.class);
4487        }
4488        return mDeviceIdleController;
4489    }
4490
4491    /**
4492     * Update given flags when being used to request {@link PackageInfo}.
4493     */
4494    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4495        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4496        boolean triaged = true;
4497        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4498                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4499            // Caller is asking for component details, so they'd better be
4500            // asking for specific encryption matching behavior, or be triaged
4501            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4502                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4503                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4504                triaged = false;
4505            }
4506        }
4507        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4508                | PackageManager.MATCH_SYSTEM_ONLY
4509                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4510            triaged = false;
4511        }
4512        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4513            mPermissionManager.enforceCrossUserPermission(
4514                    Binder.getCallingUid(), userId, false, false,
4515                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4516                    + Debug.getCallers(5));
4517        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4518                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4519            // If the caller wants all packages and has a restricted profile associated with it,
4520            // then match all users. This is to make sure that launchers that need to access work
4521            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4522            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4523            flags |= PackageManager.MATCH_ANY_USER;
4524        }
4525        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4526            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4527                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4528        }
4529        return updateFlags(flags, userId);
4530    }
4531
4532    /**
4533     * Update given flags when being used to request {@link ApplicationInfo}.
4534     */
4535    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4536        return updateFlagsForPackage(flags, userId, cookie);
4537    }
4538
4539    /**
4540     * Update given flags when being used to request {@link ComponentInfo}.
4541     */
4542    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4543        if (cookie instanceof Intent) {
4544            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4545                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4546            }
4547        }
4548
4549        boolean triaged = true;
4550        // Caller is asking for component details, so they'd better be
4551        // asking for specific encryption matching behavior, or be triaged
4552        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4553                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4554                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4555            triaged = false;
4556        }
4557        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4558            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4559                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4560        }
4561
4562        return updateFlags(flags, userId);
4563    }
4564
4565    /**
4566     * Update given intent when being used to request {@link ResolveInfo}.
4567     */
4568    private Intent updateIntentForResolve(Intent intent) {
4569        if (intent.getSelector() != null) {
4570            intent = intent.getSelector();
4571        }
4572        if (DEBUG_PREFERRED) {
4573            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4574        }
4575        return intent;
4576    }
4577
4578    /**
4579     * Update given flags when being used to request {@link ResolveInfo}.
4580     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4581     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4582     * flag set. However, this flag is only honoured in three circumstances:
4583     * <ul>
4584     * <li>when called from a system process</li>
4585     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4586     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4587     * action and a {@code android.intent.category.BROWSABLE} category</li>
4588     * </ul>
4589     */
4590    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4591        return updateFlagsForResolve(flags, userId, intent, callingUid,
4592                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4593    }
4594    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4595            boolean wantInstantApps) {
4596        return updateFlagsForResolve(flags, userId, intent, callingUid,
4597                wantInstantApps, false /*onlyExposedExplicitly*/);
4598    }
4599    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4600            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4601        // Safe mode means we shouldn't match any third-party components
4602        if (mSafeMode) {
4603            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4604        }
4605        if (getInstantAppPackageName(callingUid) != null) {
4606            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4607            if (onlyExposedExplicitly) {
4608                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4609            }
4610            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4611            flags |= PackageManager.MATCH_INSTANT;
4612        } else {
4613            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4614            final boolean allowMatchInstant =
4615                    (wantInstantApps
4616                            && Intent.ACTION_VIEW.equals(intent.getAction())
4617                            && hasWebURI(intent))
4618                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4619            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4620                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4621            if (!allowMatchInstant) {
4622                flags &= ~PackageManager.MATCH_INSTANT;
4623            }
4624        }
4625        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4626    }
4627
4628    @Override
4629    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4630        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4631    }
4632
4633    /**
4634     * Important: The provided filterCallingUid is used exclusively to filter out activities
4635     * that can be seen based on user state. It's typically the original caller uid prior
4636     * to clearing. Because it can only be provided by trusted code, it's value can be
4637     * trusted and will be used as-is; unlike userId which will be validated by this method.
4638     */
4639    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4640            int filterCallingUid, int userId) {
4641        if (!sUserManager.exists(userId)) return null;
4642        flags = updateFlagsForComponent(flags, userId, component);
4643        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4644                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4645        synchronized (mPackages) {
4646            PackageParser.Activity a = mActivities.mActivities.get(component);
4647
4648            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4649            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4650                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4651                if (ps == null) return null;
4652                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4653                    return null;
4654                }
4655                return PackageParser.generateActivityInfo(
4656                        a, flags, ps.readUserState(userId), userId);
4657            }
4658            if (mResolveComponentName.equals(component)) {
4659                return PackageParser.generateActivityInfo(
4660                        mResolveActivity, flags, new PackageUserState(), userId);
4661            }
4662        }
4663        return null;
4664    }
4665
4666    @Override
4667    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4668            String resolvedType) {
4669        synchronized (mPackages) {
4670            if (component.equals(mResolveComponentName)) {
4671                // The resolver supports EVERYTHING!
4672                return true;
4673            }
4674            final int callingUid = Binder.getCallingUid();
4675            final int callingUserId = UserHandle.getUserId(callingUid);
4676            PackageParser.Activity a = mActivities.mActivities.get(component);
4677            if (a == null) {
4678                return false;
4679            }
4680            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4681            if (ps == null) {
4682                return false;
4683            }
4684            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4685                return false;
4686            }
4687            for (int i=0; i<a.intents.size(); i++) {
4688                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4689                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4690                    return true;
4691                }
4692            }
4693            return false;
4694        }
4695    }
4696
4697    @Override
4698    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4699        if (!sUserManager.exists(userId)) return null;
4700        final int callingUid = Binder.getCallingUid();
4701        flags = updateFlagsForComponent(flags, userId, component);
4702        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4703                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4704        synchronized (mPackages) {
4705            PackageParser.Activity a = mReceivers.mActivities.get(component);
4706            if (DEBUG_PACKAGE_INFO) Log.v(
4707                TAG, "getReceiverInfo " + component + ": " + a);
4708            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4709                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4710                if (ps == null) return null;
4711                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4712                    return null;
4713                }
4714                return PackageParser.generateActivityInfo(
4715                        a, flags, ps.readUserState(userId), userId);
4716            }
4717        }
4718        return null;
4719    }
4720
4721    @Override
4722    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4723            int flags, int userId) {
4724        if (!sUserManager.exists(userId)) return null;
4725        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4726        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4727            return null;
4728        }
4729
4730        flags = updateFlagsForPackage(flags, userId, null);
4731
4732        final boolean canSeeStaticLibraries =
4733                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4734                        == PERMISSION_GRANTED
4735                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4736                        == PERMISSION_GRANTED
4737                || canRequestPackageInstallsInternal(packageName,
4738                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4739                        false  /* throwIfPermNotDeclared*/)
4740                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4741                        == PERMISSION_GRANTED;
4742
4743        synchronized (mPackages) {
4744            List<SharedLibraryInfo> result = null;
4745
4746            final int libCount = mSharedLibraries.size();
4747            for (int i = 0; i < libCount; i++) {
4748                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4749                if (versionedLib == null) {
4750                    continue;
4751                }
4752
4753                final int versionCount = versionedLib.size();
4754                for (int j = 0; j < versionCount; j++) {
4755                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4756                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4757                        break;
4758                    }
4759                    final long identity = Binder.clearCallingIdentity();
4760                    try {
4761                        PackageInfo packageInfo = getPackageInfoVersioned(
4762                                libInfo.getDeclaringPackage(), flags
4763                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4764                        if (packageInfo == null) {
4765                            continue;
4766                        }
4767                    } finally {
4768                        Binder.restoreCallingIdentity(identity);
4769                    }
4770
4771                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4772                            libInfo.getVersion(), libInfo.getType(),
4773                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4774                            flags, userId));
4775
4776                    if (result == null) {
4777                        result = new ArrayList<>();
4778                    }
4779                    result.add(resLibInfo);
4780                }
4781            }
4782
4783            return result != null ? new ParceledListSlice<>(result) : null;
4784        }
4785    }
4786
4787    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4788            SharedLibraryInfo libInfo, int flags, int userId) {
4789        List<VersionedPackage> versionedPackages = null;
4790        final int packageCount = mSettings.mPackages.size();
4791        for (int i = 0; i < packageCount; i++) {
4792            PackageSetting ps = mSettings.mPackages.valueAt(i);
4793
4794            if (ps == null) {
4795                continue;
4796            }
4797
4798            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4799                continue;
4800            }
4801
4802            final String libName = libInfo.getName();
4803            if (libInfo.isStatic()) {
4804                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4805                if (libIdx < 0) {
4806                    continue;
4807                }
4808                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4809                    continue;
4810                }
4811                if (versionedPackages == null) {
4812                    versionedPackages = new ArrayList<>();
4813                }
4814                // If the dependent is a static shared lib, use the public package name
4815                String dependentPackageName = ps.name;
4816                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4817                    dependentPackageName = ps.pkg.manifestPackageName;
4818                }
4819                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4820            } else if (ps.pkg != null) {
4821                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4822                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4823                    if (versionedPackages == null) {
4824                        versionedPackages = new ArrayList<>();
4825                    }
4826                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4827                }
4828            }
4829        }
4830
4831        return versionedPackages;
4832    }
4833
4834    @Override
4835    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4836        if (!sUserManager.exists(userId)) return null;
4837        final int callingUid = Binder.getCallingUid();
4838        flags = updateFlagsForComponent(flags, userId, component);
4839        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4840                false /* requireFullPermission */, false /* checkShell */, "get service info");
4841        synchronized (mPackages) {
4842            PackageParser.Service s = mServices.mServices.get(component);
4843            if (DEBUG_PACKAGE_INFO) Log.v(
4844                TAG, "getServiceInfo " + component + ": " + s);
4845            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4846                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4847                if (ps == null) return null;
4848                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4849                    return null;
4850                }
4851                return PackageParser.generateServiceInfo(
4852                        s, flags, ps.readUserState(userId), userId);
4853            }
4854        }
4855        return null;
4856    }
4857
4858    @Override
4859    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4860        if (!sUserManager.exists(userId)) return null;
4861        final int callingUid = Binder.getCallingUid();
4862        flags = updateFlagsForComponent(flags, userId, component);
4863        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4864                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4865        synchronized (mPackages) {
4866            PackageParser.Provider p = mProviders.mProviders.get(component);
4867            if (DEBUG_PACKAGE_INFO) Log.v(
4868                TAG, "getProviderInfo " + component + ": " + p);
4869            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4870                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4871                if (ps == null) return null;
4872                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4873                    return null;
4874                }
4875                return PackageParser.generateProviderInfo(
4876                        p, flags, ps.readUserState(userId), userId);
4877            }
4878        }
4879        return null;
4880    }
4881
4882    @Override
4883    public String[] getSystemSharedLibraryNames() {
4884        // allow instant applications
4885        synchronized (mPackages) {
4886            Set<String> libs = null;
4887            final int libCount = mSharedLibraries.size();
4888            for (int i = 0; i < libCount; i++) {
4889                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4890                if (versionedLib == null) {
4891                    continue;
4892                }
4893                final int versionCount = versionedLib.size();
4894                for (int j = 0; j < versionCount; j++) {
4895                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4896                    if (!libEntry.info.isStatic()) {
4897                        if (libs == null) {
4898                            libs = new ArraySet<>();
4899                        }
4900                        libs.add(libEntry.info.getName());
4901                        break;
4902                    }
4903                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4904                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4905                            UserHandle.getUserId(Binder.getCallingUid()),
4906                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4907                        if (libs == null) {
4908                            libs = new ArraySet<>();
4909                        }
4910                        libs.add(libEntry.info.getName());
4911                        break;
4912                    }
4913                }
4914            }
4915
4916            if (libs != null) {
4917                String[] libsArray = new String[libs.size()];
4918                libs.toArray(libsArray);
4919                return libsArray;
4920            }
4921
4922            return null;
4923        }
4924    }
4925
4926    @Override
4927    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4928        // allow instant applications
4929        synchronized (mPackages) {
4930            return mServicesSystemSharedLibraryPackageName;
4931        }
4932    }
4933
4934    @Override
4935    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4936        // allow instant applications
4937        synchronized (mPackages) {
4938            return mSharedSystemSharedLibraryPackageName;
4939        }
4940    }
4941
4942    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4943        for (int i = userList.length - 1; i >= 0; --i) {
4944            final int userId = userList[i];
4945            // don't add instant app to the list of updates
4946            if (pkgSetting.getInstantApp(userId)) {
4947                continue;
4948            }
4949            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4950            if (changedPackages == null) {
4951                changedPackages = new SparseArray<>();
4952                mChangedPackages.put(userId, changedPackages);
4953            }
4954            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4955            if (sequenceNumbers == null) {
4956                sequenceNumbers = new HashMap<>();
4957                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4958            }
4959            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4960            if (sequenceNumber != null) {
4961                changedPackages.remove(sequenceNumber);
4962            }
4963            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4964            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4965        }
4966        mChangedPackagesSequenceNumber++;
4967    }
4968
4969    @Override
4970    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4971        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4972            return null;
4973        }
4974        synchronized (mPackages) {
4975            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4976                return null;
4977            }
4978            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4979            if (changedPackages == null) {
4980                return null;
4981            }
4982            final List<String> packageNames =
4983                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4984            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4985                final String packageName = changedPackages.get(i);
4986                if (packageName != null) {
4987                    packageNames.add(packageName);
4988                }
4989            }
4990            return packageNames.isEmpty()
4991                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4992        }
4993    }
4994
4995    @Override
4996    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4997        // allow instant applications
4998        ArrayList<FeatureInfo> res;
4999        synchronized (mAvailableFeatures) {
5000            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5001            res.addAll(mAvailableFeatures.values());
5002        }
5003        final FeatureInfo fi = new FeatureInfo();
5004        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5005                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5006        res.add(fi);
5007
5008        return new ParceledListSlice<>(res);
5009    }
5010
5011    @Override
5012    public boolean hasSystemFeature(String name, int version) {
5013        // allow instant applications
5014        synchronized (mAvailableFeatures) {
5015            final FeatureInfo feat = mAvailableFeatures.get(name);
5016            if (feat == null) {
5017                return false;
5018            } else {
5019                return feat.version >= version;
5020            }
5021        }
5022    }
5023
5024    @Override
5025    public int checkPermission(String permName, String pkgName, int userId) {
5026        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5027    }
5028
5029    @Override
5030    public int checkUidPermission(String permName, int uid) {
5031        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5032    }
5033
5034    @Override
5035    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5036        if (UserHandle.getCallingUserId() != userId) {
5037            mContext.enforceCallingPermission(
5038                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5039                    "isPermissionRevokedByPolicy for user " + userId);
5040        }
5041
5042        if (checkPermission(permission, packageName, userId)
5043                == PackageManager.PERMISSION_GRANTED) {
5044            return false;
5045        }
5046
5047        final int callingUid = Binder.getCallingUid();
5048        if (getInstantAppPackageName(callingUid) != null) {
5049            if (!isCallerSameApp(packageName, callingUid)) {
5050                return false;
5051            }
5052        } else {
5053            if (isInstantApp(packageName, userId)) {
5054                return false;
5055            }
5056        }
5057
5058        final long identity = Binder.clearCallingIdentity();
5059        try {
5060            final int flags = getPermissionFlags(permission, packageName, userId);
5061            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5062        } finally {
5063            Binder.restoreCallingIdentity(identity);
5064        }
5065    }
5066
5067    @Override
5068    public String getPermissionControllerPackageName() {
5069        synchronized (mPackages) {
5070            return mRequiredInstallerPackage;
5071        }
5072    }
5073
5074    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5075        return mPermissionManager.addDynamicPermission(
5076                info, async, getCallingUid(), new PermissionCallback() {
5077                    @Override
5078                    public void onPermissionChanged() {
5079                        if (!async) {
5080                            mSettings.writeLPr();
5081                        } else {
5082                            scheduleWriteSettingsLocked();
5083                        }
5084                    }
5085                });
5086    }
5087
5088    @Override
5089    public boolean addPermission(PermissionInfo info) {
5090        synchronized (mPackages) {
5091            return addDynamicPermission(info, false);
5092        }
5093    }
5094
5095    @Override
5096    public boolean addPermissionAsync(PermissionInfo info) {
5097        synchronized (mPackages) {
5098            return addDynamicPermission(info, true);
5099        }
5100    }
5101
5102    @Override
5103    public void removePermission(String permName) {
5104        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5105    }
5106
5107    @Override
5108    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5109        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5110                getCallingUid(), userId, mPermissionCallback);
5111    }
5112
5113    @Override
5114    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5115        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5116                getCallingUid(), userId, mPermissionCallback);
5117    }
5118
5119    /**
5120     * Get the first event id for the permission.
5121     *
5122     * <p>There are four events for each permission: <ul>
5123     *     <li>Request permission: first id + 0</li>
5124     *     <li>Grant permission: first id + 1</li>
5125     *     <li>Request for permission denied: first id + 2</li>
5126     *     <li>Revoke permission: first id + 3</li>
5127     * </ul></p>
5128     *
5129     * @param name name of the permission
5130     *
5131     * @return The first event id for the permission
5132     */
5133    private static int getBaseEventId(@NonNull String name) {
5134        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5135
5136        if (eventIdIndex == -1) {
5137            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5138                    || Build.IS_USER) {
5139                Log.i(TAG, "Unknown permission " + name);
5140
5141                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5142            } else {
5143                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5144                //
5145                // Also update
5146                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5147                // - metrics_constants.proto
5148                throw new IllegalStateException("Unknown permission " + name);
5149            }
5150        }
5151
5152        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5153    }
5154
5155    /**
5156     * Log that a permission was revoked.
5157     *
5158     * @param context Context of the caller
5159     * @param name name of the permission
5160     * @param packageName package permission if for
5161     */
5162    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5163            @NonNull String packageName) {
5164        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5165    }
5166
5167    /**
5168     * Log that a permission request was granted.
5169     *
5170     * @param context Context of the caller
5171     * @param name name of the permission
5172     * @param packageName package permission if for
5173     */
5174    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5175            @NonNull String packageName) {
5176        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5177    }
5178
5179    @Override
5180    public void resetRuntimePermissions() {
5181        mContext.enforceCallingOrSelfPermission(
5182                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5183                "revokeRuntimePermission");
5184
5185        int callingUid = Binder.getCallingUid();
5186        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5187            mContext.enforceCallingOrSelfPermission(
5188                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5189                    "resetRuntimePermissions");
5190        }
5191
5192        synchronized (mPackages) {
5193            mPermissionManager.updateAllPermissions(
5194                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5195                    mPermissionCallback);
5196            for (int userId : UserManagerService.getInstance().getUserIds()) {
5197                final int packageCount = mPackages.size();
5198                for (int i = 0; i < packageCount; i++) {
5199                    PackageParser.Package pkg = mPackages.valueAt(i);
5200                    if (!(pkg.mExtras instanceof PackageSetting)) {
5201                        continue;
5202                    }
5203                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5204                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5205                }
5206            }
5207        }
5208    }
5209
5210    @Override
5211    public int getPermissionFlags(String permName, String packageName, int userId) {
5212        return mPermissionManager.getPermissionFlags(
5213                permName, packageName, getCallingUid(), userId);
5214    }
5215
5216    @Override
5217    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5218            int flagValues, int userId) {
5219        mPermissionManager.updatePermissionFlags(
5220                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5221                mPermissionCallback);
5222    }
5223
5224    /**
5225     * Update the permission flags for all packages and runtime permissions of a user in order
5226     * to allow device or profile owner to remove POLICY_FIXED.
5227     */
5228    @Override
5229    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5230        synchronized (mPackages) {
5231            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5232                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5233                    mPermissionCallback);
5234            if (changed) {
5235                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5236            }
5237        }
5238    }
5239
5240    @Override
5241    public boolean shouldShowRequestPermissionRationale(String permissionName,
5242            String packageName, int userId) {
5243        if (UserHandle.getCallingUserId() != userId) {
5244            mContext.enforceCallingPermission(
5245                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5246                    "canShowRequestPermissionRationale for user " + userId);
5247        }
5248
5249        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5250        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5251            return false;
5252        }
5253
5254        if (checkPermission(permissionName, packageName, userId)
5255                == PackageManager.PERMISSION_GRANTED) {
5256            return false;
5257        }
5258
5259        final int flags;
5260
5261        final long identity = Binder.clearCallingIdentity();
5262        try {
5263            flags = getPermissionFlags(permissionName,
5264                    packageName, userId);
5265        } finally {
5266            Binder.restoreCallingIdentity(identity);
5267        }
5268
5269        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5270                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5271                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5272
5273        if ((flags & fixedFlags) != 0) {
5274            return false;
5275        }
5276
5277        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5278    }
5279
5280    @Override
5281    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5282        mContext.enforceCallingOrSelfPermission(
5283                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5284                "addOnPermissionsChangeListener");
5285
5286        synchronized (mPackages) {
5287            mOnPermissionChangeListeners.addListenerLocked(listener);
5288        }
5289    }
5290
5291    @Override
5292    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5293        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5294            throw new SecurityException("Instant applications don't have access to this method");
5295        }
5296        synchronized (mPackages) {
5297            mOnPermissionChangeListeners.removeListenerLocked(listener);
5298        }
5299    }
5300
5301    @Override
5302    public boolean isProtectedBroadcast(String actionName) {
5303        // allow instant applications
5304        synchronized (mProtectedBroadcasts) {
5305            if (mProtectedBroadcasts.contains(actionName)) {
5306                return true;
5307            } else if (actionName != null) {
5308                // TODO: remove these terrible hacks
5309                if (actionName.startsWith("android.net.netmon.lingerExpired")
5310                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5311                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5312                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5313                    return true;
5314                }
5315            }
5316        }
5317        return false;
5318    }
5319
5320    @Override
5321    public int checkSignatures(String pkg1, String pkg2) {
5322        synchronized (mPackages) {
5323            final PackageParser.Package p1 = mPackages.get(pkg1);
5324            final PackageParser.Package p2 = mPackages.get(pkg2);
5325            if (p1 == null || p1.mExtras == null
5326                    || p2 == null || p2.mExtras == null) {
5327                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5328            }
5329            final int callingUid = Binder.getCallingUid();
5330            final int callingUserId = UserHandle.getUserId(callingUid);
5331            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5332            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5333            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5334                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5335                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5336            }
5337            return compareSignatures(p1.mSignatures, p2.mSignatures);
5338        }
5339    }
5340
5341    @Override
5342    public int checkUidSignatures(int uid1, int uid2) {
5343        final int callingUid = Binder.getCallingUid();
5344        final int callingUserId = UserHandle.getUserId(callingUid);
5345        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5346        // Map to base uids.
5347        uid1 = UserHandle.getAppId(uid1);
5348        uid2 = UserHandle.getAppId(uid2);
5349        // reader
5350        synchronized (mPackages) {
5351            Signature[] s1;
5352            Signature[] s2;
5353            Object obj = mSettings.getUserIdLPr(uid1);
5354            if (obj != null) {
5355                if (obj instanceof SharedUserSetting) {
5356                    if (isCallerInstantApp) {
5357                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5358                    }
5359                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5360                } else if (obj instanceof PackageSetting) {
5361                    final PackageSetting ps = (PackageSetting) obj;
5362                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5363                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5364                    }
5365                    s1 = ps.signatures.mSignatures;
5366                } else {
5367                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5368                }
5369            } else {
5370                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5371            }
5372            obj = mSettings.getUserIdLPr(uid2);
5373            if (obj != null) {
5374                if (obj instanceof SharedUserSetting) {
5375                    if (isCallerInstantApp) {
5376                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5377                    }
5378                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5379                } else if (obj instanceof PackageSetting) {
5380                    final PackageSetting ps = (PackageSetting) obj;
5381                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5382                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5383                    }
5384                    s2 = ps.signatures.mSignatures;
5385                } else {
5386                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5387                }
5388            } else {
5389                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5390            }
5391            return compareSignatures(s1, s2);
5392        }
5393    }
5394
5395    /**
5396     * This method should typically only be used when granting or revoking
5397     * permissions, since the app may immediately restart after this call.
5398     * <p>
5399     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5400     * guard your work against the app being relaunched.
5401     */
5402    private void killUid(int appId, int userId, String reason) {
5403        final long identity = Binder.clearCallingIdentity();
5404        try {
5405            IActivityManager am = ActivityManager.getService();
5406            if (am != null) {
5407                try {
5408                    am.killUid(appId, userId, reason);
5409                } catch (RemoteException e) {
5410                    /* ignore - same process */
5411                }
5412            }
5413        } finally {
5414            Binder.restoreCallingIdentity(identity);
5415        }
5416    }
5417
5418    /**
5419     * If the database version for this type of package (internal storage or
5420     * external storage) is less than the version where package signatures
5421     * were updated, return true.
5422     */
5423    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5424        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5425        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5426    }
5427
5428    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5429        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5430        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5431    }
5432
5433    @Override
5434    public List<String> getAllPackages() {
5435        final int callingUid = Binder.getCallingUid();
5436        final int callingUserId = UserHandle.getUserId(callingUid);
5437        synchronized (mPackages) {
5438            if (canViewInstantApps(callingUid, callingUserId)) {
5439                return new ArrayList<String>(mPackages.keySet());
5440            }
5441            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5442            final List<String> result = new ArrayList<>();
5443            if (instantAppPkgName != null) {
5444                // caller is an instant application; filter unexposed applications
5445                for (PackageParser.Package pkg : mPackages.values()) {
5446                    if (!pkg.visibleToInstantApps) {
5447                        continue;
5448                    }
5449                    result.add(pkg.packageName);
5450                }
5451            } else {
5452                // caller is a normal application; filter instant applications
5453                for (PackageParser.Package pkg : mPackages.values()) {
5454                    final PackageSetting ps =
5455                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5456                    if (ps != null
5457                            && ps.getInstantApp(callingUserId)
5458                            && !mInstantAppRegistry.isInstantAccessGranted(
5459                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5460                        continue;
5461                    }
5462                    result.add(pkg.packageName);
5463                }
5464            }
5465            return result;
5466        }
5467    }
5468
5469    @Override
5470    public String[] getPackagesForUid(int uid) {
5471        final int callingUid = Binder.getCallingUid();
5472        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5473        final int userId = UserHandle.getUserId(uid);
5474        uid = UserHandle.getAppId(uid);
5475        // reader
5476        synchronized (mPackages) {
5477            Object obj = mSettings.getUserIdLPr(uid);
5478            if (obj instanceof SharedUserSetting) {
5479                if (isCallerInstantApp) {
5480                    return null;
5481                }
5482                final SharedUserSetting sus = (SharedUserSetting) obj;
5483                final int N = sus.packages.size();
5484                String[] res = new String[N];
5485                final Iterator<PackageSetting> it = sus.packages.iterator();
5486                int i = 0;
5487                while (it.hasNext()) {
5488                    PackageSetting ps = it.next();
5489                    if (ps.getInstalled(userId)) {
5490                        res[i++] = ps.name;
5491                    } else {
5492                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5493                    }
5494                }
5495                return res;
5496            } else if (obj instanceof PackageSetting) {
5497                final PackageSetting ps = (PackageSetting) obj;
5498                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5499                    return new String[]{ps.name};
5500                }
5501            }
5502        }
5503        return null;
5504    }
5505
5506    @Override
5507    public String getNameForUid(int uid) {
5508        final int callingUid = Binder.getCallingUid();
5509        if (getInstantAppPackageName(callingUid) != null) {
5510            return null;
5511        }
5512        synchronized (mPackages) {
5513            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5514            if (obj instanceof SharedUserSetting) {
5515                final SharedUserSetting sus = (SharedUserSetting) obj;
5516                return sus.name + ":" + sus.userId;
5517            } else if (obj instanceof PackageSetting) {
5518                final PackageSetting ps = (PackageSetting) obj;
5519                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5520                    return null;
5521                }
5522                return ps.name;
5523            }
5524            return null;
5525        }
5526    }
5527
5528    @Override
5529    public String[] getNamesForUids(int[] uids) {
5530        if (uids == null || uids.length == 0) {
5531            return null;
5532        }
5533        final int callingUid = Binder.getCallingUid();
5534        if (getInstantAppPackageName(callingUid) != null) {
5535            return null;
5536        }
5537        final String[] names = new String[uids.length];
5538        synchronized (mPackages) {
5539            for (int i = uids.length - 1; i >= 0; i--) {
5540                final int uid = uids[i];
5541                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5542                if (obj instanceof SharedUserSetting) {
5543                    final SharedUserSetting sus = (SharedUserSetting) obj;
5544                    names[i] = "shared:" + sus.name;
5545                } else if (obj instanceof PackageSetting) {
5546                    final PackageSetting ps = (PackageSetting) obj;
5547                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5548                        names[i] = null;
5549                    } else {
5550                        names[i] = ps.name;
5551                    }
5552                } else {
5553                    names[i] = null;
5554                }
5555            }
5556        }
5557        return names;
5558    }
5559
5560    @Override
5561    public int getUidForSharedUser(String sharedUserName) {
5562        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5563            return -1;
5564        }
5565        if (sharedUserName == null) {
5566            return -1;
5567        }
5568        // reader
5569        synchronized (mPackages) {
5570            SharedUserSetting suid;
5571            try {
5572                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5573                if (suid != null) {
5574                    return suid.userId;
5575                }
5576            } catch (PackageManagerException ignore) {
5577                // can't happen, but, still need to catch it
5578            }
5579            return -1;
5580        }
5581    }
5582
5583    @Override
5584    public int getFlagsForUid(int uid) {
5585        final int callingUid = Binder.getCallingUid();
5586        if (getInstantAppPackageName(callingUid) != null) {
5587            return 0;
5588        }
5589        synchronized (mPackages) {
5590            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5591            if (obj instanceof SharedUserSetting) {
5592                final SharedUserSetting sus = (SharedUserSetting) obj;
5593                return sus.pkgFlags;
5594            } else if (obj instanceof PackageSetting) {
5595                final PackageSetting ps = (PackageSetting) obj;
5596                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5597                    return 0;
5598                }
5599                return ps.pkgFlags;
5600            }
5601        }
5602        return 0;
5603    }
5604
5605    @Override
5606    public int getPrivateFlagsForUid(int uid) {
5607        final int callingUid = Binder.getCallingUid();
5608        if (getInstantAppPackageName(callingUid) != null) {
5609            return 0;
5610        }
5611        synchronized (mPackages) {
5612            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5613            if (obj instanceof SharedUserSetting) {
5614                final SharedUserSetting sus = (SharedUserSetting) obj;
5615                return sus.pkgPrivateFlags;
5616            } else if (obj instanceof PackageSetting) {
5617                final PackageSetting ps = (PackageSetting) obj;
5618                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5619                    return 0;
5620                }
5621                return ps.pkgPrivateFlags;
5622            }
5623        }
5624        return 0;
5625    }
5626
5627    @Override
5628    public boolean isUidPrivileged(int uid) {
5629        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5630            return false;
5631        }
5632        uid = UserHandle.getAppId(uid);
5633        // reader
5634        synchronized (mPackages) {
5635            Object obj = mSettings.getUserIdLPr(uid);
5636            if (obj instanceof SharedUserSetting) {
5637                final SharedUserSetting sus = (SharedUserSetting) obj;
5638                final Iterator<PackageSetting> it = sus.packages.iterator();
5639                while (it.hasNext()) {
5640                    if (it.next().isPrivileged()) {
5641                        return true;
5642                    }
5643                }
5644            } else if (obj instanceof PackageSetting) {
5645                final PackageSetting ps = (PackageSetting) obj;
5646                return ps.isPrivileged();
5647            }
5648        }
5649        return false;
5650    }
5651
5652    @Override
5653    public String[] getAppOpPermissionPackages(String permName) {
5654        return mPermissionManager.getAppOpPermissionPackages(permName);
5655    }
5656
5657    @Override
5658    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5659            int flags, int userId) {
5660        return resolveIntentInternal(
5661                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5662    }
5663
5664    /**
5665     * Normally instant apps can only be resolved when they're visible to the caller.
5666     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5667     * since we need to allow the system to start any installed application.
5668     */
5669    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5670            int flags, int userId, boolean resolveForStart) {
5671        try {
5672            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5673
5674            if (!sUserManager.exists(userId)) return null;
5675            final int callingUid = Binder.getCallingUid();
5676            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5677            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5678                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5679
5680            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5681            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5682                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5683            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5684
5685            final ResolveInfo bestChoice =
5686                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5687            return bestChoice;
5688        } finally {
5689            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5690        }
5691    }
5692
5693    @Override
5694    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5695        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5696            throw new SecurityException(
5697                    "findPersistentPreferredActivity can only be run by the system");
5698        }
5699        if (!sUserManager.exists(userId)) {
5700            return null;
5701        }
5702        final int callingUid = Binder.getCallingUid();
5703        intent = updateIntentForResolve(intent);
5704        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5705        final int flags = updateFlagsForResolve(
5706                0, userId, intent, callingUid, false /*includeInstantApps*/);
5707        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5708                userId);
5709        synchronized (mPackages) {
5710            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5711                    userId);
5712        }
5713    }
5714
5715    @Override
5716    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5717            IntentFilter filter, int match, ComponentName activity) {
5718        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5719            return;
5720        }
5721        final int userId = UserHandle.getCallingUserId();
5722        if (DEBUG_PREFERRED) {
5723            Log.v(TAG, "setLastChosenActivity intent=" + intent
5724                + " resolvedType=" + resolvedType
5725                + " flags=" + flags
5726                + " filter=" + filter
5727                + " match=" + match
5728                + " activity=" + activity);
5729            filter.dump(new PrintStreamPrinter(System.out), "    ");
5730        }
5731        intent.setComponent(null);
5732        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5733                userId);
5734        // Find any earlier preferred or last chosen entries and nuke them
5735        findPreferredActivity(intent, resolvedType,
5736                flags, query, 0, false, true, false, userId);
5737        // Add the new activity as the last chosen for this filter
5738        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5739                "Setting last chosen");
5740    }
5741
5742    @Override
5743    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5744        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5745            return null;
5746        }
5747        final int userId = UserHandle.getCallingUserId();
5748        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5749        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5750                userId);
5751        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5752                false, false, false, userId);
5753    }
5754
5755    /**
5756     * Returns whether or not instant apps have been disabled remotely.
5757     */
5758    private boolean isEphemeralDisabled() {
5759        return mEphemeralAppsDisabled;
5760    }
5761
5762    private boolean isInstantAppAllowed(
5763            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5764            boolean skipPackageCheck) {
5765        if (mInstantAppResolverConnection == null) {
5766            return false;
5767        }
5768        if (mInstantAppInstallerActivity == null) {
5769            return false;
5770        }
5771        if (intent.getComponent() != null) {
5772            return false;
5773        }
5774        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5775            return false;
5776        }
5777        if (!skipPackageCheck && intent.getPackage() != null) {
5778            return false;
5779        }
5780        final boolean isWebUri = hasWebURI(intent);
5781        if (!isWebUri || intent.getData().getHost() == null) {
5782            return false;
5783        }
5784        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5785        // Or if there's already an ephemeral app installed that handles the action
5786        synchronized (mPackages) {
5787            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5788            for (int n = 0; n < count; n++) {
5789                final ResolveInfo info = resolvedActivities.get(n);
5790                final String packageName = info.activityInfo.packageName;
5791                final PackageSetting ps = mSettings.mPackages.get(packageName);
5792                if (ps != null) {
5793                    // only check domain verification status if the app is not a browser
5794                    if (!info.handleAllWebDataURI) {
5795                        // Try to get the status from User settings first
5796                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5797                        final int status = (int) (packedStatus >> 32);
5798                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5799                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5800                            if (DEBUG_EPHEMERAL) {
5801                                Slog.v(TAG, "DENY instant app;"
5802                                    + " pkg: " + packageName + ", status: " + status);
5803                            }
5804                            return false;
5805                        }
5806                    }
5807                    if (ps.getInstantApp(userId)) {
5808                        if (DEBUG_EPHEMERAL) {
5809                            Slog.v(TAG, "DENY instant app installed;"
5810                                    + " pkg: " + packageName);
5811                        }
5812                        return false;
5813                    }
5814                }
5815            }
5816        }
5817        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5818        return true;
5819    }
5820
5821    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5822            Intent origIntent, String resolvedType, String callingPackage,
5823            Bundle verificationBundle, int userId) {
5824        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5825                new InstantAppRequest(responseObj, origIntent, resolvedType,
5826                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5827        mHandler.sendMessage(msg);
5828    }
5829
5830    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5831            int flags, List<ResolveInfo> query, int userId) {
5832        if (query != null) {
5833            final int N = query.size();
5834            if (N == 1) {
5835                return query.get(0);
5836            } else if (N > 1) {
5837                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5838                // If there is more than one activity with the same priority,
5839                // then let the user decide between them.
5840                ResolveInfo r0 = query.get(0);
5841                ResolveInfo r1 = query.get(1);
5842                if (DEBUG_INTENT_MATCHING || debug) {
5843                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5844                            + r1.activityInfo.name + "=" + r1.priority);
5845                }
5846                // If the first activity has a higher priority, or a different
5847                // default, then it is always desirable to pick it.
5848                if (r0.priority != r1.priority
5849                        || r0.preferredOrder != r1.preferredOrder
5850                        || r0.isDefault != r1.isDefault) {
5851                    return query.get(0);
5852                }
5853                // If we have saved a preference for a preferred activity for
5854                // this Intent, use that.
5855                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5856                        flags, query, r0.priority, true, false, debug, userId);
5857                if (ri != null) {
5858                    return ri;
5859                }
5860                // If we have an ephemeral app, use it
5861                for (int i = 0; i < N; i++) {
5862                    ri = query.get(i);
5863                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5864                        final String packageName = ri.activityInfo.packageName;
5865                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5866                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5867                        final int status = (int)(packedStatus >> 32);
5868                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5869                            return ri;
5870                        }
5871                    }
5872                }
5873                ri = new ResolveInfo(mResolveInfo);
5874                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5875                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5876                // If all of the options come from the same package, show the application's
5877                // label and icon instead of the generic resolver's.
5878                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5879                // and then throw away the ResolveInfo itself, meaning that the caller loses
5880                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5881                // a fallback for this case; we only set the target package's resources on
5882                // the ResolveInfo, not the ActivityInfo.
5883                final String intentPackage = intent.getPackage();
5884                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5885                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5886                    ri.resolvePackageName = intentPackage;
5887                    if (userNeedsBadging(userId)) {
5888                        ri.noResourceId = true;
5889                    } else {
5890                        ri.icon = appi.icon;
5891                    }
5892                    ri.iconResourceId = appi.icon;
5893                    ri.labelRes = appi.labelRes;
5894                }
5895                ri.activityInfo.applicationInfo = new ApplicationInfo(
5896                        ri.activityInfo.applicationInfo);
5897                if (userId != 0) {
5898                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5899                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5900                }
5901                // Make sure that the resolver is displayable in car mode
5902                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5903                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5904                return ri;
5905            }
5906        }
5907        return null;
5908    }
5909
5910    /**
5911     * Return true if the given list is not empty and all of its contents have
5912     * an activityInfo with the given package name.
5913     */
5914    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5915        if (ArrayUtils.isEmpty(list)) {
5916            return false;
5917        }
5918        for (int i = 0, N = list.size(); i < N; i++) {
5919            final ResolveInfo ri = list.get(i);
5920            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5921            if (ai == null || !packageName.equals(ai.packageName)) {
5922                return false;
5923            }
5924        }
5925        return true;
5926    }
5927
5928    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5929            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5930        final int N = query.size();
5931        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5932                .get(userId);
5933        // Get the list of persistent preferred activities that handle the intent
5934        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5935        List<PersistentPreferredActivity> pprefs = ppir != null
5936                ? ppir.queryIntent(intent, resolvedType,
5937                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5938                        userId)
5939                : null;
5940        if (pprefs != null && pprefs.size() > 0) {
5941            final int M = pprefs.size();
5942            for (int i=0; i<M; i++) {
5943                final PersistentPreferredActivity ppa = pprefs.get(i);
5944                if (DEBUG_PREFERRED || debug) {
5945                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5946                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5947                            + "\n  component=" + ppa.mComponent);
5948                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5949                }
5950                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5951                        flags | MATCH_DISABLED_COMPONENTS, userId);
5952                if (DEBUG_PREFERRED || debug) {
5953                    Slog.v(TAG, "Found persistent preferred activity:");
5954                    if (ai != null) {
5955                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5956                    } else {
5957                        Slog.v(TAG, "  null");
5958                    }
5959                }
5960                if (ai == null) {
5961                    // This previously registered persistent preferred activity
5962                    // component is no longer known. Ignore it and do NOT remove it.
5963                    continue;
5964                }
5965                for (int j=0; j<N; j++) {
5966                    final ResolveInfo ri = query.get(j);
5967                    if (!ri.activityInfo.applicationInfo.packageName
5968                            .equals(ai.applicationInfo.packageName)) {
5969                        continue;
5970                    }
5971                    if (!ri.activityInfo.name.equals(ai.name)) {
5972                        continue;
5973                    }
5974                    //  Found a persistent preference that can handle the intent.
5975                    if (DEBUG_PREFERRED || debug) {
5976                        Slog.v(TAG, "Returning persistent preferred activity: " +
5977                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5978                    }
5979                    return ri;
5980                }
5981            }
5982        }
5983        return null;
5984    }
5985
5986    // TODO: handle preferred activities missing while user has amnesia
5987    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5988            List<ResolveInfo> query, int priority, boolean always,
5989            boolean removeMatches, boolean debug, int userId) {
5990        if (!sUserManager.exists(userId)) return null;
5991        final int callingUid = Binder.getCallingUid();
5992        flags = updateFlagsForResolve(
5993                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5994        intent = updateIntentForResolve(intent);
5995        // writer
5996        synchronized (mPackages) {
5997            // Try to find a matching persistent preferred activity.
5998            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5999                    debug, userId);
6000
6001            // If a persistent preferred activity matched, use it.
6002            if (pri != null) {
6003                return pri;
6004            }
6005
6006            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6007            // Get the list of preferred activities that handle the intent
6008            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6009            List<PreferredActivity> prefs = pir != null
6010                    ? pir.queryIntent(intent, resolvedType,
6011                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6012                            userId)
6013                    : null;
6014            if (prefs != null && prefs.size() > 0) {
6015                boolean changed = false;
6016                try {
6017                    // First figure out how good the original match set is.
6018                    // We will only allow preferred activities that came
6019                    // from the same match quality.
6020                    int match = 0;
6021
6022                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6023
6024                    final int N = query.size();
6025                    for (int j=0; j<N; j++) {
6026                        final ResolveInfo ri = query.get(j);
6027                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6028                                + ": 0x" + Integer.toHexString(match));
6029                        if (ri.match > match) {
6030                            match = ri.match;
6031                        }
6032                    }
6033
6034                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6035                            + Integer.toHexString(match));
6036
6037                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6038                    final int M = prefs.size();
6039                    for (int i=0; i<M; i++) {
6040                        final PreferredActivity pa = prefs.get(i);
6041                        if (DEBUG_PREFERRED || debug) {
6042                            Slog.v(TAG, "Checking PreferredActivity ds="
6043                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6044                                    + "\n  component=" + pa.mPref.mComponent);
6045                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6046                        }
6047                        if (pa.mPref.mMatch != match) {
6048                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6049                                    + Integer.toHexString(pa.mPref.mMatch));
6050                            continue;
6051                        }
6052                        // If it's not an "always" type preferred activity and that's what we're
6053                        // looking for, skip it.
6054                        if (always && !pa.mPref.mAlways) {
6055                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6056                            continue;
6057                        }
6058                        final ActivityInfo ai = getActivityInfo(
6059                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6060                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6061                                userId);
6062                        if (DEBUG_PREFERRED || debug) {
6063                            Slog.v(TAG, "Found preferred activity:");
6064                            if (ai != null) {
6065                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6066                            } else {
6067                                Slog.v(TAG, "  null");
6068                            }
6069                        }
6070                        if (ai == null) {
6071                            // This previously registered preferred activity
6072                            // component is no longer known.  Most likely an update
6073                            // to the app was installed and in the new version this
6074                            // component no longer exists.  Clean it up by removing
6075                            // it from the preferred activities list, and skip it.
6076                            Slog.w(TAG, "Removing dangling preferred activity: "
6077                                    + pa.mPref.mComponent);
6078                            pir.removeFilter(pa);
6079                            changed = true;
6080                            continue;
6081                        }
6082                        for (int j=0; j<N; j++) {
6083                            final ResolveInfo ri = query.get(j);
6084                            if (!ri.activityInfo.applicationInfo.packageName
6085                                    .equals(ai.applicationInfo.packageName)) {
6086                                continue;
6087                            }
6088                            if (!ri.activityInfo.name.equals(ai.name)) {
6089                                continue;
6090                            }
6091
6092                            if (removeMatches) {
6093                                pir.removeFilter(pa);
6094                                changed = true;
6095                                if (DEBUG_PREFERRED) {
6096                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6097                                }
6098                                break;
6099                            }
6100
6101                            // Okay we found a previously set preferred or last chosen app.
6102                            // If the result set is different from when this
6103                            // was created, and is not a subset of the preferred set, we need to
6104                            // clear it and re-ask the user their preference, if we're looking for
6105                            // an "always" type entry.
6106                            if (always && !pa.mPref.sameSet(query)) {
6107                                if (pa.mPref.isSuperset(query)) {
6108                                    // some components of the set are no longer present in
6109                                    // the query, but the preferred activity can still be reused
6110                                    if (DEBUG_PREFERRED) {
6111                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6112                                                + " still valid as only non-preferred components"
6113                                                + " were removed for " + intent + " type "
6114                                                + resolvedType);
6115                                    }
6116                                    // remove obsolete components and re-add the up-to-date filter
6117                                    PreferredActivity freshPa = new PreferredActivity(pa,
6118                                            pa.mPref.mMatch,
6119                                            pa.mPref.discardObsoleteComponents(query),
6120                                            pa.mPref.mComponent,
6121                                            pa.mPref.mAlways);
6122                                    pir.removeFilter(pa);
6123                                    pir.addFilter(freshPa);
6124                                    changed = true;
6125                                } else {
6126                                    Slog.i(TAG,
6127                                            "Result set changed, dropping preferred activity for "
6128                                                    + intent + " type " + resolvedType);
6129                                    if (DEBUG_PREFERRED) {
6130                                        Slog.v(TAG, "Removing preferred activity since set changed "
6131                                                + pa.mPref.mComponent);
6132                                    }
6133                                    pir.removeFilter(pa);
6134                                    // Re-add the filter as a "last chosen" entry (!always)
6135                                    PreferredActivity lastChosen = new PreferredActivity(
6136                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6137                                    pir.addFilter(lastChosen);
6138                                    changed = true;
6139                                    return null;
6140                                }
6141                            }
6142
6143                            // Yay! Either the set matched or we're looking for the last chosen
6144                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6145                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6146                            return ri;
6147                        }
6148                    }
6149                } finally {
6150                    if (changed) {
6151                        if (DEBUG_PREFERRED) {
6152                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6153                        }
6154                        scheduleWritePackageRestrictionsLocked(userId);
6155                    }
6156                }
6157            }
6158        }
6159        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6160        return null;
6161    }
6162
6163    /*
6164     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6165     */
6166    @Override
6167    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6168            int targetUserId) {
6169        mContext.enforceCallingOrSelfPermission(
6170                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6171        List<CrossProfileIntentFilter> matches =
6172                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6173        if (matches != null) {
6174            int size = matches.size();
6175            for (int i = 0; i < size; i++) {
6176                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6177            }
6178        }
6179        if (hasWebURI(intent)) {
6180            // cross-profile app linking works only towards the parent.
6181            final int callingUid = Binder.getCallingUid();
6182            final UserInfo parent = getProfileParent(sourceUserId);
6183            synchronized(mPackages) {
6184                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6185                        false /*includeInstantApps*/);
6186                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6187                        intent, resolvedType, flags, sourceUserId, parent.id);
6188                return xpDomainInfo != null;
6189            }
6190        }
6191        return false;
6192    }
6193
6194    private UserInfo getProfileParent(int userId) {
6195        final long identity = Binder.clearCallingIdentity();
6196        try {
6197            return sUserManager.getProfileParent(userId);
6198        } finally {
6199            Binder.restoreCallingIdentity(identity);
6200        }
6201    }
6202
6203    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6204            String resolvedType, int userId) {
6205        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6206        if (resolver != null) {
6207            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6208        }
6209        return null;
6210    }
6211
6212    @Override
6213    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6214            String resolvedType, int flags, int userId) {
6215        try {
6216            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6217
6218            return new ParceledListSlice<>(
6219                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6220        } finally {
6221            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6222        }
6223    }
6224
6225    /**
6226     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6227     * instant, returns {@code null}.
6228     */
6229    private String getInstantAppPackageName(int callingUid) {
6230        synchronized (mPackages) {
6231            // If the caller is an isolated app use the owner's uid for the lookup.
6232            if (Process.isIsolated(callingUid)) {
6233                callingUid = mIsolatedOwners.get(callingUid);
6234            }
6235            final int appId = UserHandle.getAppId(callingUid);
6236            final Object obj = mSettings.getUserIdLPr(appId);
6237            if (obj instanceof PackageSetting) {
6238                final PackageSetting ps = (PackageSetting) obj;
6239                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6240                return isInstantApp ? ps.pkg.packageName : null;
6241            }
6242        }
6243        return null;
6244    }
6245
6246    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6247            String resolvedType, int flags, int userId) {
6248        return queryIntentActivitiesInternal(
6249                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6250                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6251    }
6252
6253    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6254            String resolvedType, int flags, int filterCallingUid, int userId,
6255            boolean resolveForStart, boolean allowDynamicSplits) {
6256        if (!sUserManager.exists(userId)) return Collections.emptyList();
6257        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6258        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6259                false /* requireFullPermission */, false /* checkShell */,
6260                "query intent activities");
6261        final String pkgName = intent.getPackage();
6262        ComponentName comp = intent.getComponent();
6263        if (comp == null) {
6264            if (intent.getSelector() != null) {
6265                intent = intent.getSelector();
6266                comp = intent.getComponent();
6267            }
6268        }
6269
6270        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6271                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6272        if (comp != null) {
6273            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6274            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6275            if (ai != null) {
6276                // When specifying an explicit component, we prevent the activity from being
6277                // used when either 1) the calling package is normal and the activity is within
6278                // an ephemeral application or 2) the calling package is ephemeral and the
6279                // activity is not visible to ephemeral applications.
6280                final boolean matchInstantApp =
6281                        (flags & PackageManager.MATCH_INSTANT) != 0;
6282                final boolean matchVisibleToInstantAppOnly =
6283                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6284                final boolean matchExplicitlyVisibleOnly =
6285                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6286                final boolean isCallerInstantApp =
6287                        instantAppPkgName != null;
6288                final boolean isTargetSameInstantApp =
6289                        comp.getPackageName().equals(instantAppPkgName);
6290                final boolean isTargetInstantApp =
6291                        (ai.applicationInfo.privateFlags
6292                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6293                final boolean isTargetVisibleToInstantApp =
6294                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6295                final boolean isTargetExplicitlyVisibleToInstantApp =
6296                        isTargetVisibleToInstantApp
6297                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6298                final boolean isTargetHiddenFromInstantApp =
6299                        !isTargetVisibleToInstantApp
6300                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6301                final boolean blockResolution =
6302                        !isTargetSameInstantApp
6303                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6304                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6305                                        && isTargetHiddenFromInstantApp));
6306                if (!blockResolution) {
6307                    final ResolveInfo ri = new ResolveInfo();
6308                    ri.activityInfo = ai;
6309                    list.add(ri);
6310                }
6311            }
6312            return applyPostResolutionFilter(
6313                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6314        }
6315
6316        // reader
6317        boolean sortResult = false;
6318        boolean addEphemeral = false;
6319        List<ResolveInfo> result;
6320        final boolean ephemeralDisabled = isEphemeralDisabled();
6321        synchronized (mPackages) {
6322            if (pkgName == null) {
6323                List<CrossProfileIntentFilter> matchingFilters =
6324                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6325                // Check for results that need to skip the current profile.
6326                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6327                        resolvedType, flags, userId);
6328                if (xpResolveInfo != null) {
6329                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6330                    xpResult.add(xpResolveInfo);
6331                    return applyPostResolutionFilter(
6332                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6333                            allowDynamicSplits, filterCallingUid, userId);
6334                }
6335
6336                // Check for results in the current profile.
6337                result = filterIfNotSystemUser(mActivities.queryIntent(
6338                        intent, resolvedType, flags, userId), userId);
6339                addEphemeral = !ephemeralDisabled
6340                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6341                // Check for cross profile results.
6342                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6343                xpResolveInfo = queryCrossProfileIntents(
6344                        matchingFilters, intent, resolvedType, flags, userId,
6345                        hasNonNegativePriorityResult);
6346                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6347                    boolean isVisibleToUser = filterIfNotSystemUser(
6348                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6349                    if (isVisibleToUser) {
6350                        result.add(xpResolveInfo);
6351                        sortResult = true;
6352                    }
6353                }
6354                if (hasWebURI(intent)) {
6355                    CrossProfileDomainInfo xpDomainInfo = null;
6356                    final UserInfo parent = getProfileParent(userId);
6357                    if (parent != null) {
6358                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6359                                flags, userId, parent.id);
6360                    }
6361                    if (xpDomainInfo != null) {
6362                        if (xpResolveInfo != null) {
6363                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6364                            // in the result.
6365                            result.remove(xpResolveInfo);
6366                        }
6367                        if (result.size() == 0 && !addEphemeral) {
6368                            // No result in current profile, but found candidate in parent user.
6369                            // And we are not going to add emphemeral app, so we can return the
6370                            // result straight away.
6371                            result.add(xpDomainInfo.resolveInfo);
6372                            return applyPostResolutionFilter(result, instantAppPkgName,
6373                                    allowDynamicSplits, filterCallingUid, userId);
6374                        }
6375                    } else if (result.size() <= 1 && !addEphemeral) {
6376                        // No result in parent user and <= 1 result in current profile, and we
6377                        // are not going to add emphemeral app, so we can return the result without
6378                        // further processing.
6379                        return applyPostResolutionFilter(result, instantAppPkgName,
6380                                allowDynamicSplits, filterCallingUid, userId);
6381                    }
6382                    // We have more than one candidate (combining results from current and parent
6383                    // profile), so we need filtering and sorting.
6384                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6385                            intent, flags, result, xpDomainInfo, userId);
6386                    sortResult = true;
6387                }
6388            } else {
6389                final PackageParser.Package pkg = mPackages.get(pkgName);
6390                result = null;
6391                if (pkg != null) {
6392                    result = filterIfNotSystemUser(
6393                            mActivities.queryIntentForPackage(
6394                                    intent, resolvedType, flags, pkg.activities, userId),
6395                            userId);
6396                }
6397                if (result == null || result.size() == 0) {
6398                    // the caller wants to resolve for a particular package; however, there
6399                    // were no installed results, so, try to find an ephemeral result
6400                    addEphemeral = !ephemeralDisabled
6401                            && isInstantAppAllowed(
6402                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6403                    if (result == null) {
6404                        result = new ArrayList<>();
6405                    }
6406                }
6407            }
6408        }
6409        if (addEphemeral) {
6410            result = maybeAddInstantAppInstaller(
6411                    result, intent, resolvedType, flags, userId, resolveForStart);
6412        }
6413        if (sortResult) {
6414            Collections.sort(result, mResolvePrioritySorter);
6415        }
6416        return applyPostResolutionFilter(
6417                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6418    }
6419
6420    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6421            String resolvedType, int flags, int userId, boolean resolveForStart) {
6422        // first, check to see if we've got an instant app already installed
6423        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6424        ResolveInfo localInstantApp = null;
6425        boolean blockResolution = false;
6426        if (!alreadyResolvedLocally) {
6427            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6428                    flags
6429                        | PackageManager.GET_RESOLVED_FILTER
6430                        | PackageManager.MATCH_INSTANT
6431                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6432                    userId);
6433            for (int i = instantApps.size() - 1; i >= 0; --i) {
6434                final ResolveInfo info = instantApps.get(i);
6435                final String packageName = info.activityInfo.packageName;
6436                final PackageSetting ps = mSettings.mPackages.get(packageName);
6437                if (ps.getInstantApp(userId)) {
6438                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6439                    final int status = (int)(packedStatus >> 32);
6440                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6441                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6442                        // there's a local instant application installed, but, the user has
6443                        // chosen to never use it; skip resolution and don't acknowledge
6444                        // an instant application is even available
6445                        if (DEBUG_EPHEMERAL) {
6446                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6447                        }
6448                        blockResolution = true;
6449                        break;
6450                    } else {
6451                        // we have a locally installed instant application; skip resolution
6452                        // but acknowledge there's an instant application available
6453                        if (DEBUG_EPHEMERAL) {
6454                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6455                        }
6456                        localInstantApp = info;
6457                        break;
6458                    }
6459                }
6460            }
6461        }
6462        // no app installed, let's see if one's available
6463        AuxiliaryResolveInfo auxiliaryResponse = null;
6464        if (!blockResolution) {
6465            if (localInstantApp == null) {
6466                // we don't have an instant app locally, resolve externally
6467                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6468                final InstantAppRequest requestObject = new InstantAppRequest(
6469                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6470                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6471                        resolveForStart);
6472                auxiliaryResponse =
6473                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6474                                mContext, mInstantAppResolverConnection, requestObject);
6475                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6476            } else {
6477                // we have an instant application locally, but, we can't admit that since
6478                // callers shouldn't be able to determine prior browsing. create a dummy
6479                // auxiliary response so the downstream code behaves as if there's an
6480                // instant application available externally. when it comes time to start
6481                // the instant application, we'll do the right thing.
6482                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6483                auxiliaryResponse = new AuxiliaryResolveInfo(
6484                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6485                        ai.versionCode, null /*failureIntent*/);
6486            }
6487        }
6488        if (auxiliaryResponse != null) {
6489            if (DEBUG_EPHEMERAL) {
6490                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6491            }
6492            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6493            final PackageSetting ps =
6494                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6495            if (ps != null) {
6496                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6497                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6498                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6499                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6500                // make sure this resolver is the default
6501                ephemeralInstaller.isDefault = true;
6502                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6503                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6504                // add a non-generic filter
6505                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6506                ephemeralInstaller.filter.addDataPath(
6507                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6508                ephemeralInstaller.isInstantAppAvailable = true;
6509                result.add(ephemeralInstaller);
6510            }
6511        }
6512        return result;
6513    }
6514
6515    private static class CrossProfileDomainInfo {
6516        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6517        ResolveInfo resolveInfo;
6518        /* Best domain verification status of the activities found in the other profile */
6519        int bestDomainVerificationStatus;
6520    }
6521
6522    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6523            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6524        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6525                sourceUserId)) {
6526            return null;
6527        }
6528        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6529                resolvedType, flags, parentUserId);
6530
6531        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6532            return null;
6533        }
6534        CrossProfileDomainInfo result = null;
6535        int size = resultTargetUser.size();
6536        for (int i = 0; i < size; i++) {
6537            ResolveInfo riTargetUser = resultTargetUser.get(i);
6538            // Intent filter verification is only for filters that specify a host. So don't return
6539            // those that handle all web uris.
6540            if (riTargetUser.handleAllWebDataURI) {
6541                continue;
6542            }
6543            String packageName = riTargetUser.activityInfo.packageName;
6544            PackageSetting ps = mSettings.mPackages.get(packageName);
6545            if (ps == null) {
6546                continue;
6547            }
6548            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6549            int status = (int)(verificationState >> 32);
6550            if (result == null) {
6551                result = new CrossProfileDomainInfo();
6552                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6553                        sourceUserId, parentUserId);
6554                result.bestDomainVerificationStatus = status;
6555            } else {
6556                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6557                        result.bestDomainVerificationStatus);
6558            }
6559        }
6560        // Don't consider matches with status NEVER across profiles.
6561        if (result != null && result.bestDomainVerificationStatus
6562                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6563            return null;
6564        }
6565        return result;
6566    }
6567
6568    /**
6569     * Verification statuses are ordered from the worse to the best, except for
6570     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6571     */
6572    private int bestDomainVerificationStatus(int status1, int status2) {
6573        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6574            return status2;
6575        }
6576        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6577            return status1;
6578        }
6579        return (int) MathUtils.max(status1, status2);
6580    }
6581
6582    private boolean isUserEnabled(int userId) {
6583        long callingId = Binder.clearCallingIdentity();
6584        try {
6585            UserInfo userInfo = sUserManager.getUserInfo(userId);
6586            return userInfo != null && userInfo.isEnabled();
6587        } finally {
6588            Binder.restoreCallingIdentity(callingId);
6589        }
6590    }
6591
6592    /**
6593     * Filter out activities with systemUserOnly flag set, when current user is not System.
6594     *
6595     * @return filtered list
6596     */
6597    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6598        if (userId == UserHandle.USER_SYSTEM) {
6599            return resolveInfos;
6600        }
6601        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6602            ResolveInfo info = resolveInfos.get(i);
6603            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6604                resolveInfos.remove(i);
6605            }
6606        }
6607        return resolveInfos;
6608    }
6609
6610    /**
6611     * Filters out ephemeral activities.
6612     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6613     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6614     *
6615     * @param resolveInfos The pre-filtered list of resolved activities
6616     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6617     *          is performed.
6618     * @return A filtered list of resolved activities.
6619     */
6620    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6621            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6622        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6623            final ResolveInfo info = resolveInfos.get(i);
6624            // allow activities that are defined in the provided package
6625            if (allowDynamicSplits
6626                    && info.activityInfo.splitName != null
6627                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6628                            info.activityInfo.splitName)) {
6629                if (mInstantAppInstallerInfo == null) {
6630                    if (DEBUG_INSTALL) {
6631                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6632                    }
6633                    resolveInfos.remove(i);
6634                    continue;
6635                }
6636                // requested activity is defined in a split that hasn't been installed yet.
6637                // add the installer to the resolve list
6638                if (DEBUG_INSTALL) {
6639                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6640                }
6641                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6642                final ComponentName installFailureActivity = findInstallFailureActivity(
6643                        info.activityInfo.packageName,  filterCallingUid, userId);
6644                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6645                        info.activityInfo.packageName, info.activityInfo.splitName,
6646                        installFailureActivity,
6647                        info.activityInfo.applicationInfo.versionCode,
6648                        null /*failureIntent*/);
6649                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6650                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6651                // add a non-generic filter
6652                installerInfo.filter = new IntentFilter();
6653
6654                // This resolve info may appear in the chooser UI, so let us make it
6655                // look as the one it replaces as far as the user is concerned which
6656                // requires loading the correct label and icon for the resolve info.
6657                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6658                installerInfo.labelRes = info.resolveLabelResId();
6659                installerInfo.icon = info.resolveIconResId();
6660
6661                // propagate priority/preferred order/default
6662                installerInfo.priority = info.priority;
6663                installerInfo.preferredOrder = info.preferredOrder;
6664                installerInfo.isDefault = info.isDefault;
6665                resolveInfos.set(i, installerInfo);
6666                continue;
6667            }
6668            // caller is a full app, don't need to apply any other filtering
6669            if (ephemeralPkgName == null) {
6670                continue;
6671            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6672                // caller is same app; don't need to apply any other filtering
6673                continue;
6674            }
6675            // allow activities that have been explicitly exposed to ephemeral apps
6676            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6677            if (!isEphemeralApp
6678                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6679                continue;
6680            }
6681            resolveInfos.remove(i);
6682        }
6683        return resolveInfos;
6684    }
6685
6686    /**
6687     * Returns the activity component that can handle install failures.
6688     * <p>By default, the instant application installer handles failures. However, an
6689     * application may want to handle failures on its own. Applications do this by
6690     * creating an activity with an intent filter that handles the action
6691     * {@link Intent#ACTION_INSTALL_FAILURE}.
6692     */
6693    private @Nullable ComponentName findInstallFailureActivity(
6694            String packageName, int filterCallingUid, int userId) {
6695        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6696        failureActivityIntent.setPackage(packageName);
6697        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6698        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6699                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6700                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6701        final int NR = result.size();
6702        if (NR > 0) {
6703            for (int i = 0; i < NR; i++) {
6704                final ResolveInfo info = result.get(i);
6705                if (info.activityInfo.splitName != null) {
6706                    continue;
6707                }
6708                return new ComponentName(packageName, info.activityInfo.name);
6709            }
6710        }
6711        return null;
6712    }
6713
6714    /**
6715     * @param resolveInfos list of resolve infos in descending priority order
6716     * @return if the list contains a resolve info with non-negative priority
6717     */
6718    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6719        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6720    }
6721
6722    private static boolean hasWebURI(Intent intent) {
6723        if (intent.getData() == null) {
6724            return false;
6725        }
6726        final String scheme = intent.getScheme();
6727        if (TextUtils.isEmpty(scheme)) {
6728            return false;
6729        }
6730        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6731    }
6732
6733    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6734            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6735            int userId) {
6736        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6737
6738        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6739            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6740                    candidates.size());
6741        }
6742
6743        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6744        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6745        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6746        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6747        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6748        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6749
6750        synchronized (mPackages) {
6751            final int count = candidates.size();
6752            // First, try to use linked apps. Partition the candidates into four lists:
6753            // one for the final results, one for the "do not use ever", one for "undefined status"
6754            // and finally one for "browser app type".
6755            for (int n=0; n<count; n++) {
6756                ResolveInfo info = candidates.get(n);
6757                String packageName = info.activityInfo.packageName;
6758                PackageSetting ps = mSettings.mPackages.get(packageName);
6759                if (ps != null) {
6760                    // Add to the special match all list (Browser use case)
6761                    if (info.handleAllWebDataURI) {
6762                        matchAllList.add(info);
6763                        continue;
6764                    }
6765                    // Try to get the status from User settings first
6766                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6767                    int status = (int)(packedStatus >> 32);
6768                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6769                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6770                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6771                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6772                                    + " : linkgen=" + linkGeneration);
6773                        }
6774                        // Use link-enabled generation as preferredOrder, i.e.
6775                        // prefer newly-enabled over earlier-enabled.
6776                        info.preferredOrder = linkGeneration;
6777                        alwaysList.add(info);
6778                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6779                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6780                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6781                        }
6782                        neverList.add(info);
6783                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6784                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6785                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6786                        }
6787                        alwaysAskList.add(info);
6788                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6789                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6790                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6791                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6792                        }
6793                        undefinedList.add(info);
6794                    }
6795                }
6796            }
6797
6798            // We'll want to include browser possibilities in a few cases
6799            boolean includeBrowser = false;
6800
6801            // First try to add the "always" resolution(s) for the current user, if any
6802            if (alwaysList.size() > 0) {
6803                result.addAll(alwaysList);
6804            } else {
6805                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6806                result.addAll(undefinedList);
6807                // Maybe add one for the other profile.
6808                if (xpDomainInfo != null && (
6809                        xpDomainInfo.bestDomainVerificationStatus
6810                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6811                    result.add(xpDomainInfo.resolveInfo);
6812                }
6813                includeBrowser = true;
6814            }
6815
6816            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6817            // If there were 'always' entries their preferred order has been set, so we also
6818            // back that off to make the alternatives equivalent
6819            if (alwaysAskList.size() > 0) {
6820                for (ResolveInfo i : result) {
6821                    i.preferredOrder = 0;
6822                }
6823                result.addAll(alwaysAskList);
6824                includeBrowser = true;
6825            }
6826
6827            if (includeBrowser) {
6828                // Also add browsers (all of them or only the default one)
6829                if (DEBUG_DOMAIN_VERIFICATION) {
6830                    Slog.v(TAG, "   ...including browsers in candidate set");
6831                }
6832                if ((matchFlags & MATCH_ALL) != 0) {
6833                    result.addAll(matchAllList);
6834                } else {
6835                    // Browser/generic handling case.  If there's a default browser, go straight
6836                    // to that (but only if there is no other higher-priority match).
6837                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6838                    int maxMatchPrio = 0;
6839                    ResolveInfo defaultBrowserMatch = null;
6840                    final int numCandidates = matchAllList.size();
6841                    for (int n = 0; n < numCandidates; n++) {
6842                        ResolveInfo info = matchAllList.get(n);
6843                        // track the highest overall match priority...
6844                        if (info.priority > maxMatchPrio) {
6845                            maxMatchPrio = info.priority;
6846                        }
6847                        // ...and the highest-priority default browser match
6848                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6849                            if (defaultBrowserMatch == null
6850                                    || (defaultBrowserMatch.priority < info.priority)) {
6851                                if (debug) {
6852                                    Slog.v(TAG, "Considering default browser match " + info);
6853                                }
6854                                defaultBrowserMatch = info;
6855                            }
6856                        }
6857                    }
6858                    if (defaultBrowserMatch != null
6859                            && defaultBrowserMatch.priority >= maxMatchPrio
6860                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6861                    {
6862                        if (debug) {
6863                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6864                        }
6865                        result.add(defaultBrowserMatch);
6866                    } else {
6867                        result.addAll(matchAllList);
6868                    }
6869                }
6870
6871                // If there is nothing selected, add all candidates and remove the ones that the user
6872                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6873                if (result.size() == 0) {
6874                    result.addAll(candidates);
6875                    result.removeAll(neverList);
6876                }
6877            }
6878        }
6879        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6880            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6881                    result.size());
6882            for (ResolveInfo info : result) {
6883                Slog.v(TAG, "  + " + info.activityInfo);
6884            }
6885        }
6886        return result;
6887    }
6888
6889    // Returns a packed value as a long:
6890    //
6891    // high 'int'-sized word: link status: undefined/ask/never/always.
6892    // low 'int'-sized word: relative priority among 'always' results.
6893    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6894        long result = ps.getDomainVerificationStatusForUser(userId);
6895        // if none available, get the master status
6896        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6897            if (ps.getIntentFilterVerificationInfo() != null) {
6898                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6899            }
6900        }
6901        return result;
6902    }
6903
6904    private ResolveInfo querySkipCurrentProfileIntents(
6905            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6906            int flags, int sourceUserId) {
6907        if (matchingFilters != null) {
6908            int size = matchingFilters.size();
6909            for (int i = 0; i < size; i ++) {
6910                CrossProfileIntentFilter filter = matchingFilters.get(i);
6911                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6912                    // Checking if there are activities in the target user that can handle the
6913                    // intent.
6914                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6915                            resolvedType, flags, sourceUserId);
6916                    if (resolveInfo != null) {
6917                        return resolveInfo;
6918                    }
6919                }
6920            }
6921        }
6922        return null;
6923    }
6924
6925    // Return matching ResolveInfo in target user if any.
6926    private ResolveInfo queryCrossProfileIntents(
6927            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6928            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6929        if (matchingFilters != null) {
6930            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6931            // match the same intent. For performance reasons, it is better not to
6932            // run queryIntent twice for the same userId
6933            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6934            int size = matchingFilters.size();
6935            for (int i = 0; i < size; i++) {
6936                CrossProfileIntentFilter filter = matchingFilters.get(i);
6937                int targetUserId = filter.getTargetUserId();
6938                boolean skipCurrentProfile =
6939                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6940                boolean skipCurrentProfileIfNoMatchFound =
6941                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6942                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6943                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6944                    // Checking if there are activities in the target user that can handle the
6945                    // intent.
6946                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6947                            resolvedType, flags, sourceUserId);
6948                    if (resolveInfo != null) return resolveInfo;
6949                    alreadyTriedUserIds.put(targetUserId, true);
6950                }
6951            }
6952        }
6953        return null;
6954    }
6955
6956    /**
6957     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6958     * will forward the intent to the filter's target user.
6959     * Otherwise, returns null.
6960     */
6961    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6962            String resolvedType, int flags, int sourceUserId) {
6963        int targetUserId = filter.getTargetUserId();
6964        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6965                resolvedType, flags, targetUserId);
6966        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6967            // If all the matches in the target profile are suspended, return null.
6968            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6969                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6970                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6971                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6972                            targetUserId);
6973                }
6974            }
6975        }
6976        return null;
6977    }
6978
6979    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6980            int sourceUserId, int targetUserId) {
6981        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6982        long ident = Binder.clearCallingIdentity();
6983        boolean targetIsProfile;
6984        try {
6985            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6986        } finally {
6987            Binder.restoreCallingIdentity(ident);
6988        }
6989        String className;
6990        if (targetIsProfile) {
6991            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6992        } else {
6993            className = FORWARD_INTENT_TO_PARENT;
6994        }
6995        ComponentName forwardingActivityComponentName = new ComponentName(
6996                mAndroidApplication.packageName, className);
6997        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6998                sourceUserId);
6999        if (!targetIsProfile) {
7000            forwardingActivityInfo.showUserIcon = targetUserId;
7001            forwardingResolveInfo.noResourceId = true;
7002        }
7003        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7004        forwardingResolveInfo.priority = 0;
7005        forwardingResolveInfo.preferredOrder = 0;
7006        forwardingResolveInfo.match = 0;
7007        forwardingResolveInfo.isDefault = true;
7008        forwardingResolveInfo.filter = filter;
7009        forwardingResolveInfo.targetUserId = targetUserId;
7010        return forwardingResolveInfo;
7011    }
7012
7013    @Override
7014    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7015            Intent[] specifics, String[] specificTypes, Intent intent,
7016            String resolvedType, int flags, int userId) {
7017        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7018                specificTypes, intent, resolvedType, flags, userId));
7019    }
7020
7021    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7022            Intent[] specifics, String[] specificTypes, Intent intent,
7023            String resolvedType, int flags, int userId) {
7024        if (!sUserManager.exists(userId)) return Collections.emptyList();
7025        final int callingUid = Binder.getCallingUid();
7026        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7027                false /*includeInstantApps*/);
7028        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7029                false /*requireFullPermission*/, false /*checkShell*/,
7030                "query intent activity options");
7031        final String resultsAction = intent.getAction();
7032
7033        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7034                | PackageManager.GET_RESOLVED_FILTER, userId);
7035
7036        if (DEBUG_INTENT_MATCHING) {
7037            Log.v(TAG, "Query " + intent + ": " + results);
7038        }
7039
7040        int specificsPos = 0;
7041        int N;
7042
7043        // todo: note that the algorithm used here is O(N^2).  This
7044        // isn't a problem in our current environment, but if we start running
7045        // into situations where we have more than 5 or 10 matches then this
7046        // should probably be changed to something smarter...
7047
7048        // First we go through and resolve each of the specific items
7049        // that were supplied, taking care of removing any corresponding
7050        // duplicate items in the generic resolve list.
7051        if (specifics != null) {
7052            for (int i=0; i<specifics.length; i++) {
7053                final Intent sintent = specifics[i];
7054                if (sintent == null) {
7055                    continue;
7056                }
7057
7058                if (DEBUG_INTENT_MATCHING) {
7059                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7060                }
7061
7062                String action = sintent.getAction();
7063                if (resultsAction != null && resultsAction.equals(action)) {
7064                    // If this action was explicitly requested, then don't
7065                    // remove things that have it.
7066                    action = null;
7067                }
7068
7069                ResolveInfo ri = null;
7070                ActivityInfo ai = null;
7071
7072                ComponentName comp = sintent.getComponent();
7073                if (comp == null) {
7074                    ri = resolveIntent(
7075                        sintent,
7076                        specificTypes != null ? specificTypes[i] : null,
7077                            flags, userId);
7078                    if (ri == null) {
7079                        continue;
7080                    }
7081                    if (ri == mResolveInfo) {
7082                        // ACK!  Must do something better with this.
7083                    }
7084                    ai = ri.activityInfo;
7085                    comp = new ComponentName(ai.applicationInfo.packageName,
7086                            ai.name);
7087                } else {
7088                    ai = getActivityInfo(comp, flags, userId);
7089                    if (ai == null) {
7090                        continue;
7091                    }
7092                }
7093
7094                // Look for any generic query activities that are duplicates
7095                // of this specific one, and remove them from the results.
7096                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7097                N = results.size();
7098                int j;
7099                for (j=specificsPos; j<N; j++) {
7100                    ResolveInfo sri = results.get(j);
7101                    if ((sri.activityInfo.name.equals(comp.getClassName())
7102                            && sri.activityInfo.applicationInfo.packageName.equals(
7103                                    comp.getPackageName()))
7104                        || (action != null && sri.filter.matchAction(action))) {
7105                        results.remove(j);
7106                        if (DEBUG_INTENT_MATCHING) Log.v(
7107                            TAG, "Removing duplicate item from " + j
7108                            + " due to specific " + specificsPos);
7109                        if (ri == null) {
7110                            ri = sri;
7111                        }
7112                        j--;
7113                        N--;
7114                    }
7115                }
7116
7117                // Add this specific item to its proper place.
7118                if (ri == null) {
7119                    ri = new ResolveInfo();
7120                    ri.activityInfo = ai;
7121                }
7122                results.add(specificsPos, ri);
7123                ri.specificIndex = i;
7124                specificsPos++;
7125            }
7126        }
7127
7128        // Now we go through the remaining generic results and remove any
7129        // duplicate actions that are found here.
7130        N = results.size();
7131        for (int i=specificsPos; i<N-1; i++) {
7132            final ResolveInfo rii = results.get(i);
7133            if (rii.filter == null) {
7134                continue;
7135            }
7136
7137            // Iterate over all of the actions of this result's intent
7138            // filter...  typically this should be just one.
7139            final Iterator<String> it = rii.filter.actionsIterator();
7140            if (it == null) {
7141                continue;
7142            }
7143            while (it.hasNext()) {
7144                final String action = it.next();
7145                if (resultsAction != null && resultsAction.equals(action)) {
7146                    // If this action was explicitly requested, then don't
7147                    // remove things that have it.
7148                    continue;
7149                }
7150                for (int j=i+1; j<N; j++) {
7151                    final ResolveInfo rij = results.get(j);
7152                    if (rij.filter != null && rij.filter.hasAction(action)) {
7153                        results.remove(j);
7154                        if (DEBUG_INTENT_MATCHING) Log.v(
7155                            TAG, "Removing duplicate item from " + j
7156                            + " due to action " + action + " at " + i);
7157                        j--;
7158                        N--;
7159                    }
7160                }
7161            }
7162
7163            // If the caller didn't request filter information, drop it now
7164            // so we don't have to marshall/unmarshall it.
7165            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7166                rii.filter = null;
7167            }
7168        }
7169
7170        // Filter out the caller activity if so requested.
7171        if (caller != null) {
7172            N = results.size();
7173            for (int i=0; i<N; i++) {
7174                ActivityInfo ainfo = results.get(i).activityInfo;
7175                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7176                        && caller.getClassName().equals(ainfo.name)) {
7177                    results.remove(i);
7178                    break;
7179                }
7180            }
7181        }
7182
7183        // If the caller didn't request filter information,
7184        // drop them now so we don't have to
7185        // marshall/unmarshall it.
7186        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7187            N = results.size();
7188            for (int i=0; i<N; i++) {
7189                results.get(i).filter = null;
7190            }
7191        }
7192
7193        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7194        return results;
7195    }
7196
7197    @Override
7198    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7199            String resolvedType, int flags, int userId) {
7200        return new ParceledListSlice<>(
7201                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7202                        false /*allowDynamicSplits*/));
7203    }
7204
7205    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7206            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7207        if (!sUserManager.exists(userId)) return Collections.emptyList();
7208        final int callingUid = Binder.getCallingUid();
7209        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7210                false /*requireFullPermission*/, false /*checkShell*/,
7211                "query intent receivers");
7212        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7213        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7214                false /*includeInstantApps*/);
7215        ComponentName comp = intent.getComponent();
7216        if (comp == null) {
7217            if (intent.getSelector() != null) {
7218                intent = intent.getSelector();
7219                comp = intent.getComponent();
7220            }
7221        }
7222        if (comp != null) {
7223            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7224            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7225            if (ai != null) {
7226                // When specifying an explicit component, we prevent the activity from being
7227                // used when either 1) the calling package is normal and the activity is within
7228                // an instant application or 2) the calling package is ephemeral and the
7229                // activity is not visible to instant applications.
7230                final boolean matchInstantApp =
7231                        (flags & PackageManager.MATCH_INSTANT) != 0;
7232                final boolean matchVisibleToInstantAppOnly =
7233                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7234                final boolean matchExplicitlyVisibleOnly =
7235                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7236                final boolean isCallerInstantApp =
7237                        instantAppPkgName != null;
7238                final boolean isTargetSameInstantApp =
7239                        comp.getPackageName().equals(instantAppPkgName);
7240                final boolean isTargetInstantApp =
7241                        (ai.applicationInfo.privateFlags
7242                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7243                final boolean isTargetVisibleToInstantApp =
7244                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7245                final boolean isTargetExplicitlyVisibleToInstantApp =
7246                        isTargetVisibleToInstantApp
7247                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7248                final boolean isTargetHiddenFromInstantApp =
7249                        !isTargetVisibleToInstantApp
7250                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7251                final boolean blockResolution =
7252                        !isTargetSameInstantApp
7253                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7254                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7255                                        && isTargetHiddenFromInstantApp));
7256                if (!blockResolution) {
7257                    ResolveInfo ri = new ResolveInfo();
7258                    ri.activityInfo = ai;
7259                    list.add(ri);
7260                }
7261            }
7262            return applyPostResolutionFilter(
7263                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7264        }
7265
7266        // reader
7267        synchronized (mPackages) {
7268            String pkgName = intent.getPackage();
7269            if (pkgName == null) {
7270                final List<ResolveInfo> result =
7271                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7272                return applyPostResolutionFilter(
7273                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7274            }
7275            final PackageParser.Package pkg = mPackages.get(pkgName);
7276            if (pkg != null) {
7277                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7278                        intent, resolvedType, flags, pkg.receivers, userId);
7279                return applyPostResolutionFilter(
7280                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7281            }
7282            return Collections.emptyList();
7283        }
7284    }
7285
7286    @Override
7287    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7288        final int callingUid = Binder.getCallingUid();
7289        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7290    }
7291
7292    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7293            int userId, int callingUid) {
7294        if (!sUserManager.exists(userId)) return null;
7295        flags = updateFlagsForResolve(
7296                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7297        List<ResolveInfo> query = queryIntentServicesInternal(
7298                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7299        if (query != null) {
7300            if (query.size() >= 1) {
7301                // If there is more than one service with the same priority,
7302                // just arbitrarily pick the first one.
7303                return query.get(0);
7304            }
7305        }
7306        return null;
7307    }
7308
7309    @Override
7310    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7311            String resolvedType, int flags, int userId) {
7312        final int callingUid = Binder.getCallingUid();
7313        return new ParceledListSlice<>(queryIntentServicesInternal(
7314                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7315    }
7316
7317    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7318            String resolvedType, int flags, int userId, int callingUid,
7319            boolean includeInstantApps) {
7320        if (!sUserManager.exists(userId)) return Collections.emptyList();
7321        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7322                false /*requireFullPermission*/, false /*checkShell*/,
7323                "query intent receivers");
7324        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7325        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7326        ComponentName comp = intent.getComponent();
7327        if (comp == null) {
7328            if (intent.getSelector() != null) {
7329                intent = intent.getSelector();
7330                comp = intent.getComponent();
7331            }
7332        }
7333        if (comp != null) {
7334            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7335            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7336            if (si != null) {
7337                // When specifying an explicit component, we prevent the service from being
7338                // used when either 1) the service is in an instant application and the
7339                // caller is not the same instant application or 2) the calling package is
7340                // ephemeral and the activity is not visible to ephemeral applications.
7341                final boolean matchInstantApp =
7342                        (flags & PackageManager.MATCH_INSTANT) != 0;
7343                final boolean matchVisibleToInstantAppOnly =
7344                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7345                final boolean isCallerInstantApp =
7346                        instantAppPkgName != null;
7347                final boolean isTargetSameInstantApp =
7348                        comp.getPackageName().equals(instantAppPkgName);
7349                final boolean isTargetInstantApp =
7350                        (si.applicationInfo.privateFlags
7351                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7352                final boolean isTargetHiddenFromInstantApp =
7353                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7354                final boolean blockResolution =
7355                        !isTargetSameInstantApp
7356                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7357                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7358                                        && isTargetHiddenFromInstantApp));
7359                if (!blockResolution) {
7360                    final ResolveInfo ri = new ResolveInfo();
7361                    ri.serviceInfo = si;
7362                    list.add(ri);
7363                }
7364            }
7365            return list;
7366        }
7367
7368        // reader
7369        synchronized (mPackages) {
7370            String pkgName = intent.getPackage();
7371            if (pkgName == null) {
7372                return applyPostServiceResolutionFilter(
7373                        mServices.queryIntent(intent, resolvedType, flags, userId),
7374                        instantAppPkgName);
7375            }
7376            final PackageParser.Package pkg = mPackages.get(pkgName);
7377            if (pkg != null) {
7378                return applyPostServiceResolutionFilter(
7379                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7380                                userId),
7381                        instantAppPkgName);
7382            }
7383            return Collections.emptyList();
7384        }
7385    }
7386
7387    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7388            String instantAppPkgName) {
7389        if (instantAppPkgName == null) {
7390            return resolveInfos;
7391        }
7392        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7393            final ResolveInfo info = resolveInfos.get(i);
7394            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7395            // allow services that are defined in the provided package
7396            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7397                if (info.serviceInfo.splitName != null
7398                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7399                                info.serviceInfo.splitName)) {
7400                    // requested service is defined in a split that hasn't been installed yet.
7401                    // add the installer to the resolve list
7402                    if (DEBUG_EPHEMERAL) {
7403                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7404                    }
7405                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7406                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7407                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7408                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7409                            null /*failureIntent*/);
7410                    // make sure this resolver is the default
7411                    installerInfo.isDefault = true;
7412                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7413                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7414                    // add a non-generic filter
7415                    installerInfo.filter = new IntentFilter();
7416                    // load resources from the correct package
7417                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7418                    resolveInfos.set(i, installerInfo);
7419                }
7420                continue;
7421            }
7422            // allow services that have been explicitly exposed to ephemeral apps
7423            if (!isEphemeralApp
7424                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7425                continue;
7426            }
7427            resolveInfos.remove(i);
7428        }
7429        return resolveInfos;
7430    }
7431
7432    @Override
7433    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7434            String resolvedType, int flags, int userId) {
7435        return new ParceledListSlice<>(
7436                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7437    }
7438
7439    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7440            Intent intent, String resolvedType, int flags, int userId) {
7441        if (!sUserManager.exists(userId)) return Collections.emptyList();
7442        final int callingUid = Binder.getCallingUid();
7443        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7444        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7445                false /*includeInstantApps*/);
7446        ComponentName comp = intent.getComponent();
7447        if (comp == null) {
7448            if (intent.getSelector() != null) {
7449                intent = intent.getSelector();
7450                comp = intent.getComponent();
7451            }
7452        }
7453        if (comp != null) {
7454            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7455            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7456            if (pi != null) {
7457                // When specifying an explicit component, we prevent the provider from being
7458                // used when either 1) the provider is in an instant application and the
7459                // caller is not the same instant application or 2) the calling package is an
7460                // instant application and the provider is not visible to instant applications.
7461                final boolean matchInstantApp =
7462                        (flags & PackageManager.MATCH_INSTANT) != 0;
7463                final boolean matchVisibleToInstantAppOnly =
7464                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7465                final boolean isCallerInstantApp =
7466                        instantAppPkgName != null;
7467                final boolean isTargetSameInstantApp =
7468                        comp.getPackageName().equals(instantAppPkgName);
7469                final boolean isTargetInstantApp =
7470                        (pi.applicationInfo.privateFlags
7471                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7472                final boolean isTargetHiddenFromInstantApp =
7473                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7474                final boolean blockResolution =
7475                        !isTargetSameInstantApp
7476                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7477                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7478                                        && isTargetHiddenFromInstantApp));
7479                if (!blockResolution) {
7480                    final ResolveInfo ri = new ResolveInfo();
7481                    ri.providerInfo = pi;
7482                    list.add(ri);
7483                }
7484            }
7485            return list;
7486        }
7487
7488        // reader
7489        synchronized (mPackages) {
7490            String pkgName = intent.getPackage();
7491            if (pkgName == null) {
7492                return applyPostContentProviderResolutionFilter(
7493                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7494                        instantAppPkgName);
7495            }
7496            final PackageParser.Package pkg = mPackages.get(pkgName);
7497            if (pkg != null) {
7498                return applyPostContentProviderResolutionFilter(
7499                        mProviders.queryIntentForPackage(
7500                        intent, resolvedType, flags, pkg.providers, userId),
7501                        instantAppPkgName);
7502            }
7503            return Collections.emptyList();
7504        }
7505    }
7506
7507    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7508            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7509        if (instantAppPkgName == null) {
7510            return resolveInfos;
7511        }
7512        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7513            final ResolveInfo info = resolveInfos.get(i);
7514            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7515            // allow providers that are defined in the provided package
7516            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7517                if (info.providerInfo.splitName != null
7518                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7519                                info.providerInfo.splitName)) {
7520                    // requested provider is defined in a split that hasn't been installed yet.
7521                    // add the installer to the resolve list
7522                    if (DEBUG_EPHEMERAL) {
7523                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7524                    }
7525                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7526                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7527                            info.providerInfo.packageName, info.providerInfo.splitName,
7528                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7529                            null /*failureIntent*/);
7530                    // make sure this resolver is the default
7531                    installerInfo.isDefault = true;
7532                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7533                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7534                    // add a non-generic filter
7535                    installerInfo.filter = new IntentFilter();
7536                    // load resources from the correct package
7537                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7538                    resolveInfos.set(i, installerInfo);
7539                }
7540                continue;
7541            }
7542            // allow providers that have been explicitly exposed to instant applications
7543            if (!isEphemeralApp
7544                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7545                continue;
7546            }
7547            resolveInfos.remove(i);
7548        }
7549        return resolveInfos;
7550    }
7551
7552    @Override
7553    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7554        final int callingUid = Binder.getCallingUid();
7555        if (getInstantAppPackageName(callingUid) != null) {
7556            return ParceledListSlice.emptyList();
7557        }
7558        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7559        flags = updateFlagsForPackage(flags, userId, null);
7560        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7561        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7562                true /* requireFullPermission */, false /* checkShell */,
7563                "get installed packages");
7564
7565        // writer
7566        synchronized (mPackages) {
7567            ArrayList<PackageInfo> list;
7568            if (listUninstalled) {
7569                list = new ArrayList<>(mSettings.mPackages.size());
7570                for (PackageSetting ps : mSettings.mPackages.values()) {
7571                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7572                        continue;
7573                    }
7574                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7575                        continue;
7576                    }
7577                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7578                    if (pi != null) {
7579                        list.add(pi);
7580                    }
7581                }
7582            } else {
7583                list = new ArrayList<>(mPackages.size());
7584                for (PackageParser.Package p : mPackages.values()) {
7585                    final PackageSetting ps = (PackageSetting) p.mExtras;
7586                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7587                        continue;
7588                    }
7589                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7590                        continue;
7591                    }
7592                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7593                            p.mExtras, flags, userId);
7594                    if (pi != null) {
7595                        list.add(pi);
7596                    }
7597                }
7598            }
7599
7600            return new ParceledListSlice<>(list);
7601        }
7602    }
7603
7604    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7605            String[] permissions, boolean[] tmp, int flags, int userId) {
7606        int numMatch = 0;
7607        final PermissionsState permissionsState = ps.getPermissionsState();
7608        for (int i=0; i<permissions.length; i++) {
7609            final String permission = permissions[i];
7610            if (permissionsState.hasPermission(permission, userId)) {
7611                tmp[i] = true;
7612                numMatch++;
7613            } else {
7614                tmp[i] = false;
7615            }
7616        }
7617        if (numMatch == 0) {
7618            return;
7619        }
7620        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7621
7622        // The above might return null in cases of uninstalled apps or install-state
7623        // skew across users/profiles.
7624        if (pi != null) {
7625            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7626                if (numMatch == permissions.length) {
7627                    pi.requestedPermissions = permissions;
7628                } else {
7629                    pi.requestedPermissions = new String[numMatch];
7630                    numMatch = 0;
7631                    for (int i=0; i<permissions.length; i++) {
7632                        if (tmp[i]) {
7633                            pi.requestedPermissions[numMatch] = permissions[i];
7634                            numMatch++;
7635                        }
7636                    }
7637                }
7638            }
7639            list.add(pi);
7640        }
7641    }
7642
7643    @Override
7644    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7645            String[] permissions, int flags, int userId) {
7646        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7647        flags = updateFlagsForPackage(flags, userId, permissions);
7648        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7649                true /* requireFullPermission */, false /* checkShell */,
7650                "get packages holding permissions");
7651        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7652
7653        // writer
7654        synchronized (mPackages) {
7655            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7656            boolean[] tmpBools = new boolean[permissions.length];
7657            if (listUninstalled) {
7658                for (PackageSetting ps : mSettings.mPackages.values()) {
7659                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7660                            userId);
7661                }
7662            } else {
7663                for (PackageParser.Package pkg : mPackages.values()) {
7664                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7665                    if (ps != null) {
7666                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7667                                userId);
7668                    }
7669                }
7670            }
7671
7672            return new ParceledListSlice<PackageInfo>(list);
7673        }
7674    }
7675
7676    @Override
7677    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7678        final int callingUid = Binder.getCallingUid();
7679        if (getInstantAppPackageName(callingUid) != null) {
7680            return ParceledListSlice.emptyList();
7681        }
7682        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7683        flags = updateFlagsForApplication(flags, userId, null);
7684        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7685
7686        // writer
7687        synchronized (mPackages) {
7688            ArrayList<ApplicationInfo> list;
7689            if (listUninstalled) {
7690                list = new ArrayList<>(mSettings.mPackages.size());
7691                for (PackageSetting ps : mSettings.mPackages.values()) {
7692                    ApplicationInfo ai;
7693                    int effectiveFlags = flags;
7694                    if (ps.isSystem()) {
7695                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7696                    }
7697                    if (ps.pkg != null) {
7698                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7699                            continue;
7700                        }
7701                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7702                            continue;
7703                        }
7704                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7705                                ps.readUserState(userId), userId);
7706                        if (ai != null) {
7707                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7708                        }
7709                    } else {
7710                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7711                        // and already converts to externally visible package name
7712                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7713                                callingUid, effectiveFlags, userId);
7714                    }
7715                    if (ai != null) {
7716                        list.add(ai);
7717                    }
7718                }
7719            } else {
7720                list = new ArrayList<>(mPackages.size());
7721                for (PackageParser.Package p : mPackages.values()) {
7722                    if (p.mExtras != null) {
7723                        PackageSetting ps = (PackageSetting) p.mExtras;
7724                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7725                            continue;
7726                        }
7727                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7728                            continue;
7729                        }
7730                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7731                                ps.readUserState(userId), userId);
7732                        if (ai != null) {
7733                            ai.packageName = resolveExternalPackageNameLPr(p);
7734                            list.add(ai);
7735                        }
7736                    }
7737                }
7738            }
7739
7740            return new ParceledListSlice<>(list);
7741        }
7742    }
7743
7744    @Override
7745    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7746        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7747            return null;
7748        }
7749        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7750            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7751                    "getEphemeralApplications");
7752        }
7753        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7754                true /* requireFullPermission */, false /* checkShell */,
7755                "getEphemeralApplications");
7756        synchronized (mPackages) {
7757            List<InstantAppInfo> instantApps = mInstantAppRegistry
7758                    .getInstantAppsLPr(userId);
7759            if (instantApps != null) {
7760                return new ParceledListSlice<>(instantApps);
7761            }
7762        }
7763        return null;
7764    }
7765
7766    @Override
7767    public boolean isInstantApp(String packageName, int userId) {
7768        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7769                true /* requireFullPermission */, false /* checkShell */,
7770                "isInstantApp");
7771        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7772            return false;
7773        }
7774
7775        synchronized (mPackages) {
7776            int callingUid = Binder.getCallingUid();
7777            if (Process.isIsolated(callingUid)) {
7778                callingUid = mIsolatedOwners.get(callingUid);
7779            }
7780            final PackageSetting ps = mSettings.mPackages.get(packageName);
7781            PackageParser.Package pkg = mPackages.get(packageName);
7782            final boolean returnAllowed =
7783                    ps != null
7784                    && (isCallerSameApp(packageName, callingUid)
7785                            || canViewInstantApps(callingUid, userId)
7786                            || mInstantAppRegistry.isInstantAccessGranted(
7787                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7788            if (returnAllowed) {
7789                return ps.getInstantApp(userId);
7790            }
7791        }
7792        return false;
7793    }
7794
7795    @Override
7796    public byte[] getInstantAppCookie(String packageName, int userId) {
7797        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7798            return null;
7799        }
7800
7801        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7802                true /* requireFullPermission */, false /* checkShell */,
7803                "getInstantAppCookie");
7804        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7805            return null;
7806        }
7807        synchronized (mPackages) {
7808            return mInstantAppRegistry.getInstantAppCookieLPw(
7809                    packageName, userId);
7810        }
7811    }
7812
7813    @Override
7814    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7815        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7816            return true;
7817        }
7818
7819        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7820                true /* requireFullPermission */, true /* checkShell */,
7821                "setInstantAppCookie");
7822        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7823            return false;
7824        }
7825        synchronized (mPackages) {
7826            return mInstantAppRegistry.setInstantAppCookieLPw(
7827                    packageName, cookie, userId);
7828        }
7829    }
7830
7831    @Override
7832    public Bitmap getInstantAppIcon(String packageName, int userId) {
7833        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7834            return null;
7835        }
7836
7837        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7838            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7839                    "getInstantAppIcon");
7840        }
7841        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7842                true /* requireFullPermission */, false /* checkShell */,
7843                "getInstantAppIcon");
7844
7845        synchronized (mPackages) {
7846            return mInstantAppRegistry.getInstantAppIconLPw(
7847                    packageName, userId);
7848        }
7849    }
7850
7851    private boolean isCallerSameApp(String packageName, int uid) {
7852        PackageParser.Package pkg = mPackages.get(packageName);
7853        return pkg != null
7854                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7855    }
7856
7857    @Override
7858    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7859        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7860            return ParceledListSlice.emptyList();
7861        }
7862        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7863    }
7864
7865    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7866        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7867
7868        // reader
7869        synchronized (mPackages) {
7870            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7871            final int userId = UserHandle.getCallingUserId();
7872            while (i.hasNext()) {
7873                final PackageParser.Package p = i.next();
7874                if (p.applicationInfo == null) continue;
7875
7876                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7877                        && !p.applicationInfo.isDirectBootAware();
7878                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7879                        && p.applicationInfo.isDirectBootAware();
7880
7881                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7882                        && (!mSafeMode || isSystemApp(p))
7883                        && (matchesUnaware || matchesAware)) {
7884                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7885                    if (ps != null) {
7886                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7887                                ps.readUserState(userId), userId);
7888                        if (ai != null) {
7889                            finalList.add(ai);
7890                        }
7891                    }
7892                }
7893            }
7894        }
7895
7896        return finalList;
7897    }
7898
7899    @Override
7900    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7901        return resolveContentProviderInternal(name, flags, userId);
7902    }
7903
7904    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7905        if (!sUserManager.exists(userId)) return null;
7906        flags = updateFlagsForComponent(flags, userId, name);
7907        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7908        // reader
7909        synchronized (mPackages) {
7910            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7911            PackageSetting ps = provider != null
7912                    ? mSettings.mPackages.get(provider.owner.packageName)
7913                    : null;
7914            if (ps != null) {
7915                final boolean isInstantApp = ps.getInstantApp(userId);
7916                // normal application; filter out instant application provider
7917                if (instantAppPkgName == null && isInstantApp) {
7918                    return null;
7919                }
7920                // instant application; filter out other instant applications
7921                if (instantAppPkgName != null
7922                        && isInstantApp
7923                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7924                    return null;
7925                }
7926                // instant application; filter out non-exposed provider
7927                if (instantAppPkgName != null
7928                        && !isInstantApp
7929                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7930                    return null;
7931                }
7932                // provider not enabled
7933                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7934                    return null;
7935                }
7936                return PackageParser.generateProviderInfo(
7937                        provider, flags, ps.readUserState(userId), userId);
7938            }
7939            return null;
7940        }
7941    }
7942
7943    /**
7944     * @deprecated
7945     */
7946    @Deprecated
7947    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7948        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7949            return;
7950        }
7951        // reader
7952        synchronized (mPackages) {
7953            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7954                    .entrySet().iterator();
7955            final int userId = UserHandle.getCallingUserId();
7956            while (i.hasNext()) {
7957                Map.Entry<String, PackageParser.Provider> entry = i.next();
7958                PackageParser.Provider p = entry.getValue();
7959                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7960
7961                if (ps != null && p.syncable
7962                        && (!mSafeMode || (p.info.applicationInfo.flags
7963                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7964                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7965                            ps.readUserState(userId), userId);
7966                    if (info != null) {
7967                        outNames.add(entry.getKey());
7968                        outInfo.add(info);
7969                    }
7970                }
7971            }
7972        }
7973    }
7974
7975    @Override
7976    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7977            int uid, int flags, String metaDataKey) {
7978        final int callingUid = Binder.getCallingUid();
7979        final int userId = processName != null ? UserHandle.getUserId(uid)
7980                : UserHandle.getCallingUserId();
7981        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7982        flags = updateFlagsForComponent(flags, userId, processName);
7983        ArrayList<ProviderInfo> finalList = null;
7984        // reader
7985        synchronized (mPackages) {
7986            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7987            while (i.hasNext()) {
7988                final PackageParser.Provider p = i.next();
7989                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7990                if (ps != null && p.info.authority != null
7991                        && (processName == null
7992                                || (p.info.processName.equals(processName)
7993                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7994                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7995
7996                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7997                    // parameter.
7998                    if (metaDataKey != null
7999                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8000                        continue;
8001                    }
8002                    final ComponentName component =
8003                            new ComponentName(p.info.packageName, p.info.name);
8004                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8005                        continue;
8006                    }
8007                    if (finalList == null) {
8008                        finalList = new ArrayList<ProviderInfo>(3);
8009                    }
8010                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8011                            ps.readUserState(userId), userId);
8012                    if (info != null) {
8013                        finalList.add(info);
8014                    }
8015                }
8016            }
8017        }
8018
8019        if (finalList != null) {
8020            Collections.sort(finalList, mProviderInitOrderSorter);
8021            return new ParceledListSlice<ProviderInfo>(finalList);
8022        }
8023
8024        return ParceledListSlice.emptyList();
8025    }
8026
8027    @Override
8028    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8029        // reader
8030        synchronized (mPackages) {
8031            final int callingUid = Binder.getCallingUid();
8032            final int callingUserId = UserHandle.getUserId(callingUid);
8033            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8034            if (ps == null) return null;
8035            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8036                return null;
8037            }
8038            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8039            return PackageParser.generateInstrumentationInfo(i, flags);
8040        }
8041    }
8042
8043    @Override
8044    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8045            String targetPackage, int flags) {
8046        final int callingUid = Binder.getCallingUid();
8047        final int callingUserId = UserHandle.getUserId(callingUid);
8048        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8049        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8050            return ParceledListSlice.emptyList();
8051        }
8052        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8053    }
8054
8055    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8056            int flags) {
8057        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8058
8059        // reader
8060        synchronized (mPackages) {
8061            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8062            while (i.hasNext()) {
8063                final PackageParser.Instrumentation p = i.next();
8064                if (targetPackage == null
8065                        || targetPackage.equals(p.info.targetPackage)) {
8066                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8067                            flags);
8068                    if (ii != null) {
8069                        finalList.add(ii);
8070                    }
8071                }
8072            }
8073        }
8074
8075        return finalList;
8076    }
8077
8078    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8079        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8080        try {
8081            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8082        } finally {
8083            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8084        }
8085    }
8086
8087    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8088        final File[] files = dir.listFiles();
8089        if (ArrayUtils.isEmpty(files)) {
8090            Log.d(TAG, "No files in app dir " + dir);
8091            return;
8092        }
8093
8094        if (DEBUG_PACKAGE_SCANNING) {
8095            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8096                    + " flags=0x" + Integer.toHexString(parseFlags));
8097        }
8098        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8099                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8100                mParallelPackageParserCallback);
8101
8102        // Submit files for parsing in parallel
8103        int fileCount = 0;
8104        for (File file : files) {
8105            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8106                    && !PackageInstallerService.isStageName(file.getName());
8107            if (!isPackage) {
8108                // Ignore entries which are not packages
8109                continue;
8110            }
8111            parallelPackageParser.submit(file, parseFlags);
8112            fileCount++;
8113        }
8114
8115        // Process results one by one
8116        for (; fileCount > 0; fileCount--) {
8117            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8118            Throwable throwable = parseResult.throwable;
8119            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8120
8121            if (throwable == null) {
8122                // Static shared libraries have synthetic package names
8123                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8124                    renameStaticSharedLibraryPackage(parseResult.pkg);
8125                }
8126                try {
8127                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8128                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8129                                currentTime, null);
8130                    }
8131                } catch (PackageManagerException e) {
8132                    errorCode = e.error;
8133                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8134                }
8135            } else if (throwable instanceof PackageParser.PackageParserException) {
8136                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8137                        throwable;
8138                errorCode = e.error;
8139                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8140            } else {
8141                throw new IllegalStateException("Unexpected exception occurred while parsing "
8142                        + parseResult.scanFile, throwable);
8143            }
8144
8145            // Delete invalid userdata apps
8146            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8147                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8148                logCriticalInfo(Log.WARN,
8149                        "Deleting invalid package at " + parseResult.scanFile);
8150                removeCodePathLI(parseResult.scanFile);
8151            }
8152        }
8153        parallelPackageParser.close();
8154    }
8155
8156    public static void reportSettingsProblem(int priority, String msg) {
8157        logCriticalInfo(priority, msg);
8158    }
8159
8160    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8161            final int policyFlags) throws PackageManagerException {
8162        // When upgrading from pre-N MR1, verify the package time stamp using the package
8163        // directory and not the APK file.
8164        final long lastModifiedTime = mIsPreNMR1Upgrade
8165                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8166        if (ps != null
8167                && ps.codePath.equals(srcFile)
8168                && ps.timeStamp == lastModifiedTime
8169                && !isCompatSignatureUpdateNeeded(pkg)
8170                && !isRecoverSignatureUpdateNeeded(pkg)) {
8171            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8172            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
8173            ArraySet<PublicKey> signingKs;
8174            synchronized (mPackages) {
8175                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8176            }
8177            if (ps.signatures.mSignatures != null
8178                    && ps.signatures.mSignatures.length != 0
8179                    && signingKs != null) {
8180                // Optimization: reuse the existing cached certificates
8181                // if the package appears to be unchanged.
8182                pkg.mSignatures = ps.signatures.mSignatures;
8183                pkg.mSigningKeys = signingKs;
8184                return;
8185            }
8186
8187            Slog.w(TAG, "PackageSetting for " + ps.name
8188                    + " is missing signatures.  Collecting certs again to recover them.");
8189        } else {
8190            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8191        }
8192
8193        try {
8194            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8195            PackageParser.collectCertificates(pkg, policyFlags);
8196        } catch (PackageParserException e) {
8197            throw PackageManagerException.from(e);
8198        } finally {
8199            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8200        }
8201    }
8202
8203    /**
8204     *  Traces a package scan.
8205     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8206     */
8207    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8208            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8209        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8210        try {
8211            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8212        } finally {
8213            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8214        }
8215    }
8216
8217    /**
8218     *  Scans a package and returns the newly parsed package.
8219     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8220     */
8221    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8222            long currentTime, UserHandle user) throws PackageManagerException {
8223        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8224        PackageParser pp = new PackageParser();
8225        pp.setSeparateProcesses(mSeparateProcesses);
8226        pp.setOnlyCoreApps(mOnlyCore);
8227        pp.setDisplayMetrics(mMetrics);
8228        pp.setCallback(mPackageParserCallback);
8229
8230        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8231            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8232        }
8233
8234        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8235        final PackageParser.Package pkg;
8236        try {
8237            pkg = pp.parsePackage(scanFile, parseFlags);
8238        } catch (PackageParserException e) {
8239            throw PackageManagerException.from(e);
8240        } finally {
8241            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8242        }
8243
8244        // Static shared libraries have synthetic package names
8245        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8246            renameStaticSharedLibraryPackage(pkg);
8247        }
8248
8249        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8250    }
8251
8252    /**
8253     *  Scans a package and returns the newly parsed package.
8254     *  @throws PackageManagerException on a parse error.
8255     */
8256    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8257            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8258            throws PackageManagerException {
8259        // If the package has children and this is the first dive in the function
8260        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8261        // packages (parent and children) would be successfully scanned before the
8262        // actual scan since scanning mutates internal state and we want to atomically
8263        // install the package and its children.
8264        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8265            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8266                scanFlags |= SCAN_CHECK_ONLY;
8267            }
8268        } else {
8269            scanFlags &= ~SCAN_CHECK_ONLY;
8270        }
8271
8272        // Scan the parent
8273        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8274                scanFlags, currentTime, user);
8275
8276        // Scan the children
8277        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8278        for (int i = 0; i < childCount; i++) {
8279            PackageParser.Package childPackage = pkg.childPackages.get(i);
8280            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8281                    currentTime, user);
8282        }
8283
8284
8285        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8286            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8287        }
8288
8289        return scannedPkg;
8290    }
8291
8292    /**
8293     *  Scans a package and returns the newly parsed package.
8294     *  @throws PackageManagerException on a parse error.
8295     */
8296    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8297            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8298            throws PackageManagerException {
8299        PackageSetting ps = null;
8300        PackageSetting updatedPkg;
8301        // reader
8302        synchronized (mPackages) {
8303            // Look to see if we already know about this package.
8304            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8305            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8306                // This package has been renamed to its original name.  Let's
8307                // use that.
8308                ps = mSettings.getPackageLPr(oldName);
8309            }
8310            // If there was no original package, see one for the real package name.
8311            if (ps == null) {
8312                ps = mSettings.getPackageLPr(pkg.packageName);
8313            }
8314            // Check to see if this package could be hiding/updating a system
8315            // package.  Must look for it either under the original or real
8316            // package name depending on our state.
8317            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8318            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8319
8320            // If this is a package we don't know about on the system partition, we
8321            // may need to remove disabled child packages on the system partition
8322            // or may need to not add child packages if the parent apk is updated
8323            // on the data partition and no longer defines this child package.
8324            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8325                // If this is a parent package for an updated system app and this system
8326                // app got an OTA update which no longer defines some of the child packages
8327                // we have to prune them from the disabled system packages.
8328                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8329                if (disabledPs != null) {
8330                    final int scannedChildCount = (pkg.childPackages != null)
8331                            ? pkg.childPackages.size() : 0;
8332                    final int disabledChildCount = disabledPs.childPackageNames != null
8333                            ? disabledPs.childPackageNames.size() : 0;
8334                    for (int i = 0; i < disabledChildCount; i++) {
8335                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8336                        boolean disabledPackageAvailable = false;
8337                        for (int j = 0; j < scannedChildCount; j++) {
8338                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8339                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8340                                disabledPackageAvailable = true;
8341                                break;
8342                            }
8343                         }
8344                         if (!disabledPackageAvailable) {
8345                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8346                         }
8347                    }
8348                }
8349            }
8350        }
8351
8352        final boolean isUpdatedPkg = updatedPkg != null;
8353        final boolean isUpdatedSystemPkg = isUpdatedPkg
8354                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8355        boolean isUpdatedPkgBetter = false;
8356        // First check if this is a system package that may involve an update
8357        if (isUpdatedSystemPkg) {
8358            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8359            // it needs to drop FLAG_PRIVILEGED.
8360            if (locationIsPrivileged(scanFile)) {
8361                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8362            } else {
8363                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8364            }
8365            // If new package is not located in "/oem" (e.g. due to an OTA),
8366            // it needs to drop FLAG_OEM.
8367            if (locationIsOem(scanFile)) {
8368                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8369            } else {
8370                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8371            }
8372
8373            if (ps != null && !ps.codePath.equals(scanFile)) {
8374                // The path has changed from what was last scanned...  check the
8375                // version of the new path against what we have stored to determine
8376                // what to do.
8377                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8378                if (pkg.mVersionCode <= ps.versionCode) {
8379                    // The system package has been updated and the code path does not match
8380                    // Ignore entry. Skip it.
8381                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8382                            + " ignored: updated version " + ps.versionCode
8383                            + " better than this " + pkg.mVersionCode);
8384                    if (!updatedPkg.codePath.equals(scanFile)) {
8385                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8386                                + ps.name + " changing from " + updatedPkg.codePathString
8387                                + " to " + scanFile);
8388                        updatedPkg.codePath = scanFile;
8389                        updatedPkg.codePathString = scanFile.toString();
8390                        updatedPkg.resourcePath = scanFile;
8391                        updatedPkg.resourcePathString = scanFile.toString();
8392                    }
8393                    updatedPkg.pkg = pkg;
8394                    updatedPkg.versionCode = pkg.mVersionCode;
8395
8396                    // Update the disabled system child packages to point to the package too.
8397                    final int childCount = updatedPkg.childPackageNames != null
8398                            ? updatedPkg.childPackageNames.size() : 0;
8399                    for (int i = 0; i < childCount; i++) {
8400                        String childPackageName = updatedPkg.childPackageNames.get(i);
8401                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8402                                childPackageName);
8403                        if (updatedChildPkg != null) {
8404                            updatedChildPkg.pkg = pkg;
8405                            updatedChildPkg.versionCode = pkg.mVersionCode;
8406                        }
8407                    }
8408                } else {
8409                    // The current app on the system partition is better than
8410                    // what we have updated to on the data partition; switch
8411                    // back to the system partition version.
8412                    // At this point, its safely assumed that package installation for
8413                    // apps in system partition will go through. If not there won't be a working
8414                    // version of the app
8415                    // writer
8416                    synchronized (mPackages) {
8417                        // Just remove the loaded entries from package lists.
8418                        mPackages.remove(ps.name);
8419                    }
8420
8421                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8422                            + " reverting from " + ps.codePathString
8423                            + ": new version " + pkg.mVersionCode
8424                            + " better than installed " + ps.versionCode);
8425
8426                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8427                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8428                    synchronized (mInstallLock) {
8429                        args.cleanUpResourcesLI();
8430                    }
8431                    synchronized (mPackages) {
8432                        mSettings.enableSystemPackageLPw(ps.name);
8433                    }
8434                    isUpdatedPkgBetter = true;
8435                }
8436            }
8437        }
8438
8439        String resourcePath = null;
8440        String baseResourcePath = null;
8441        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8442            if (ps != null && ps.resourcePathString != null) {
8443                resourcePath = ps.resourcePathString;
8444                baseResourcePath = ps.resourcePathString;
8445            } else {
8446                // Should not happen at all. Just log an error.
8447                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8448            }
8449        } else {
8450            resourcePath = pkg.codePath;
8451            baseResourcePath = pkg.baseCodePath;
8452        }
8453
8454        // Set application objects path explicitly.
8455        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8456        pkg.setApplicationInfoCodePath(pkg.codePath);
8457        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8458        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8459        pkg.setApplicationInfoResourcePath(resourcePath);
8460        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8461        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8462
8463        // throw an exception if we have an update to a system application, but, it's not more
8464        // recent than the package we've already scanned
8465        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8466            // Set CPU Abis to application info.
8467            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8468                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8469                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8470            } else {
8471                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8472                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8473            }
8474
8475            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8476                    + scanFile + " ignored: updated version " + ps.versionCode
8477                    + " better than this " + pkg.mVersionCode);
8478        }
8479
8480        if (isUpdatedPkg) {
8481            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8482            // initially
8483            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8484
8485            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8486            // flag set initially
8487            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8488                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8489            }
8490
8491            // An updated OEM app will not have the PARSE_IS_OEM
8492            // flag set initially
8493            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8494                policyFlags |= PackageParser.PARSE_IS_OEM;
8495            }
8496        }
8497
8498        // Verify certificates against what was last scanned
8499        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8500
8501        /*
8502         * A new system app appeared, but we already had a non-system one of the
8503         * same name installed earlier.
8504         */
8505        boolean shouldHideSystemApp = false;
8506        if (!isUpdatedPkg && ps != null
8507                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8508            /*
8509             * Check to make sure the signatures match first. If they don't,
8510             * wipe the installed application and its data.
8511             */
8512            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8513                    != PackageManager.SIGNATURE_MATCH) {
8514                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8515                        + " signatures don't match existing userdata copy; removing");
8516                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8517                        "scanPackageInternalLI")) {
8518                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8519                }
8520                ps = null;
8521            } else {
8522                /*
8523                 * If the newly-added system app is an older version than the
8524                 * already installed version, hide it. It will be scanned later
8525                 * and re-added like an update.
8526                 */
8527                if (pkg.mVersionCode <= ps.versionCode) {
8528                    shouldHideSystemApp = true;
8529                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8530                            + " but new version " + pkg.mVersionCode + " better than installed "
8531                            + ps.versionCode + "; hiding system");
8532                } else {
8533                    /*
8534                     * The newly found system app is a newer version that the
8535                     * one previously installed. Simply remove the
8536                     * already-installed application and replace it with our own
8537                     * while keeping the application data.
8538                     */
8539                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8540                            + " reverting from " + ps.codePathString + ": new version "
8541                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8542                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8543                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8544                    synchronized (mInstallLock) {
8545                        args.cleanUpResourcesLI();
8546                    }
8547                }
8548            }
8549        }
8550
8551        // The apk is forward locked (not public) if its code and resources
8552        // are kept in different files. (except for app in either system or
8553        // vendor path).
8554        // TODO grab this value from PackageSettings
8555        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8556            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8557                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8558            }
8559        }
8560
8561        final int userId = ((user == null) ? 0 : user.getIdentifier());
8562        if (ps != null && ps.getInstantApp(userId)) {
8563            scanFlags |= SCAN_AS_INSTANT_APP;
8564        }
8565        if (ps != null && ps.getVirtulalPreload(userId)) {
8566            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8567        }
8568
8569        // Note that we invoke the following method only if we are about to unpack an application
8570        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8571                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8572
8573        /*
8574         * If the system app should be overridden by a previously installed
8575         * data, hide the system app now and let the /data/app scan pick it up
8576         * again.
8577         */
8578        if (shouldHideSystemApp) {
8579            synchronized (mPackages) {
8580                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8581            }
8582        }
8583
8584        return scannedPkg;
8585    }
8586
8587    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8588        // Derive the new package synthetic package name
8589        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8590                + pkg.staticSharedLibVersion);
8591    }
8592
8593    private static String fixProcessName(String defProcessName,
8594            String processName) {
8595        if (processName == null) {
8596            return defProcessName;
8597        }
8598        return processName;
8599    }
8600
8601    /**
8602     * Enforces that only the system UID or root's UID can call a method exposed
8603     * via Binder.
8604     *
8605     * @param message used as message if SecurityException is thrown
8606     * @throws SecurityException if the caller is not system or root
8607     */
8608    private static final void enforceSystemOrRoot(String message) {
8609        final int uid = Binder.getCallingUid();
8610        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8611            throw new SecurityException(message);
8612        }
8613    }
8614
8615    @Override
8616    public void performFstrimIfNeeded() {
8617        enforceSystemOrRoot("Only the system can request fstrim");
8618
8619        // Before everything else, see whether we need to fstrim.
8620        try {
8621            IStorageManager sm = PackageHelper.getStorageManager();
8622            if (sm != null) {
8623                boolean doTrim = false;
8624                final long interval = android.provider.Settings.Global.getLong(
8625                        mContext.getContentResolver(),
8626                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8627                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8628                if (interval > 0) {
8629                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8630                    if (timeSinceLast > interval) {
8631                        doTrim = true;
8632                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8633                                + "; running immediately");
8634                    }
8635                }
8636                if (doTrim) {
8637                    final boolean dexOptDialogShown;
8638                    synchronized (mPackages) {
8639                        dexOptDialogShown = mDexOptDialogShown;
8640                    }
8641                    if (!isFirstBoot() && dexOptDialogShown) {
8642                        try {
8643                            ActivityManager.getService().showBootMessage(
8644                                    mContext.getResources().getString(
8645                                            R.string.android_upgrading_fstrim), true);
8646                        } catch (RemoteException e) {
8647                        }
8648                    }
8649                    sm.runMaintenance();
8650                }
8651            } else {
8652                Slog.e(TAG, "storageManager service unavailable!");
8653            }
8654        } catch (RemoteException e) {
8655            // Can't happen; StorageManagerService is local
8656        }
8657    }
8658
8659    @Override
8660    public void updatePackagesIfNeeded() {
8661        enforceSystemOrRoot("Only the system can request package update");
8662
8663        // We need to re-extract after an OTA.
8664        boolean causeUpgrade = isUpgrade();
8665
8666        // First boot or factory reset.
8667        // Note: we also handle devices that are upgrading to N right now as if it is their
8668        //       first boot, as they do not have profile data.
8669        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8670
8671        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8672        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8673
8674        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8675            return;
8676        }
8677
8678        List<PackageParser.Package> pkgs;
8679        synchronized (mPackages) {
8680            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8681        }
8682
8683        final long startTime = System.nanoTime();
8684        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8685                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8686                    false /* bootComplete */);
8687
8688        final int elapsedTimeSeconds =
8689                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8690
8691        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8692        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8693        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8694        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8695        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8696    }
8697
8698    /*
8699     * Return the prebuilt profile path given a package base code path.
8700     */
8701    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8702        return pkg.baseCodePath + ".prof";
8703    }
8704
8705    /**
8706     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8707     * containing statistics about the invocation. The array consists of three elements,
8708     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8709     * and {@code numberOfPackagesFailed}.
8710     */
8711    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8712            final String compilerFilter, boolean bootComplete) {
8713
8714        int numberOfPackagesVisited = 0;
8715        int numberOfPackagesOptimized = 0;
8716        int numberOfPackagesSkipped = 0;
8717        int numberOfPackagesFailed = 0;
8718        final int numberOfPackagesToDexopt = pkgs.size();
8719
8720        for (PackageParser.Package pkg : pkgs) {
8721            numberOfPackagesVisited++;
8722
8723            boolean useProfileForDexopt = false;
8724
8725            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8726                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8727                // that are already compiled.
8728                File profileFile = new File(getPrebuildProfilePath(pkg));
8729                // Copy profile if it exists.
8730                if (profileFile.exists()) {
8731                    try {
8732                        // We could also do this lazily before calling dexopt in
8733                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8734                        // is that we don't have a good way to say "do this only once".
8735                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8736                                pkg.applicationInfo.uid, pkg.packageName)) {
8737                            Log.e(TAG, "Installer failed to copy system profile!");
8738                        } else {
8739                            // Disabled as this causes speed-profile compilation during first boot
8740                            // even if things are already compiled.
8741                            // useProfileForDexopt = true;
8742                        }
8743                    } catch (Exception e) {
8744                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8745                                e);
8746                    }
8747                } else {
8748                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8749                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8750                    // minimize the number off apps being speed-profile compiled during first boot.
8751                    // The other paths will not change the filter.
8752                    if (disabledPs != null && disabledPs.pkg.isStub) {
8753                        // The package is the stub one, remove the stub suffix to get the normal
8754                        // package and APK names.
8755                        String systemProfilePath =
8756                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8757                        profileFile = new File(systemProfilePath);
8758                        // If we have a profile for a compressed APK, copy it to the reference
8759                        // location.
8760                        // Note that copying the profile here will cause it to override the
8761                        // reference profile every OTA even though the existing reference profile
8762                        // may have more data. We can't copy during decompression since the
8763                        // directories are not set up at that point.
8764                        if (profileFile.exists()) {
8765                            try {
8766                                // We could also do this lazily before calling dexopt in
8767                                // PackageDexOptimizer to prevent this happening on first boot. The
8768                                // issue is that we don't have a good way to say "do this only
8769                                // once".
8770                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8771                                        pkg.applicationInfo.uid, pkg.packageName)) {
8772                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8773                                } else {
8774                                    useProfileForDexopt = true;
8775                                }
8776                            } catch (Exception e) {
8777                                Log.e(TAG, "Failed to copy profile " +
8778                                        profileFile.getAbsolutePath() + " ", e);
8779                            }
8780                        }
8781                    }
8782                }
8783            }
8784
8785            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8786                if (DEBUG_DEXOPT) {
8787                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8788                }
8789                numberOfPackagesSkipped++;
8790                continue;
8791            }
8792
8793            if (DEBUG_DEXOPT) {
8794                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8795                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8796            }
8797
8798            if (showDialog) {
8799                try {
8800                    ActivityManager.getService().showBootMessage(
8801                            mContext.getResources().getString(R.string.android_upgrading_apk,
8802                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8803                } catch (RemoteException e) {
8804                }
8805                synchronized (mPackages) {
8806                    mDexOptDialogShown = true;
8807                }
8808            }
8809
8810            String pkgCompilerFilter = compilerFilter;
8811            if (useProfileForDexopt) {
8812                // Use background dexopt mode to try and use the profile. Note that this does not
8813                // guarantee usage of the profile.
8814                pkgCompilerFilter =
8815                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8816                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8817            }
8818
8819            // checkProfiles is false to avoid merging profiles during boot which
8820            // might interfere with background compilation (b/28612421).
8821            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8822            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8823            // trade-off worth doing to save boot time work.
8824            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8825            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8826                    pkg.packageName,
8827                    pkgCompilerFilter,
8828                    dexoptFlags));
8829
8830            switch (primaryDexOptStaus) {
8831                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8832                    numberOfPackagesOptimized++;
8833                    break;
8834                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8835                    numberOfPackagesSkipped++;
8836                    break;
8837                case PackageDexOptimizer.DEX_OPT_FAILED:
8838                    numberOfPackagesFailed++;
8839                    break;
8840                default:
8841                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8842                    break;
8843            }
8844        }
8845
8846        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8847                numberOfPackagesFailed };
8848    }
8849
8850    @Override
8851    public void notifyPackageUse(String packageName, int reason) {
8852        synchronized (mPackages) {
8853            final int callingUid = Binder.getCallingUid();
8854            final int callingUserId = UserHandle.getUserId(callingUid);
8855            if (getInstantAppPackageName(callingUid) != null) {
8856                if (!isCallerSameApp(packageName, callingUid)) {
8857                    return;
8858                }
8859            } else {
8860                if (isInstantApp(packageName, callingUserId)) {
8861                    return;
8862                }
8863            }
8864            notifyPackageUseLocked(packageName, reason);
8865        }
8866    }
8867
8868    private void notifyPackageUseLocked(String packageName, int reason) {
8869        final PackageParser.Package p = mPackages.get(packageName);
8870        if (p == null) {
8871            return;
8872        }
8873        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8874    }
8875
8876    @Override
8877    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
8878            List<String> classPaths, String loaderIsa) {
8879        int userId = UserHandle.getCallingUserId();
8880        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8881        if (ai == null) {
8882            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8883                + loadingPackageName + ", user=" + userId);
8884            return;
8885        }
8886        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
8887    }
8888
8889    @Override
8890    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
8891            IDexModuleRegisterCallback callback) {
8892        int userId = UserHandle.getCallingUserId();
8893        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
8894        DexManager.RegisterDexModuleResult result;
8895        if (ai == null) {
8896            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
8897                     " calling user. package=" + packageName + ", user=" + userId);
8898            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
8899        } else {
8900            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
8901        }
8902
8903        if (callback != null) {
8904            mHandler.post(() -> {
8905                try {
8906                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
8907                } catch (RemoteException e) {
8908                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
8909                }
8910            });
8911        }
8912    }
8913
8914    /**
8915     * Ask the package manager to perform a dex-opt with the given compiler filter.
8916     *
8917     * Note: exposed only for the shell command to allow moving packages explicitly to a
8918     *       definite state.
8919     */
8920    @Override
8921    public boolean performDexOptMode(String packageName,
8922            boolean checkProfiles, String targetCompilerFilter, boolean force,
8923            boolean bootComplete, String splitName) {
8924        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
8925                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
8926                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
8927        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
8928                splitName, flags));
8929    }
8930
8931    /**
8932     * Ask the package manager to perform a dex-opt with the given compiler filter on the
8933     * secondary dex files belonging to the given package.
8934     *
8935     * Note: exposed only for the shell command to allow moving packages explicitly to a
8936     *       definite state.
8937     */
8938    @Override
8939    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8940            boolean force) {
8941        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
8942                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
8943                DexoptOptions.DEXOPT_BOOT_COMPLETE |
8944                (force ? DexoptOptions.DEXOPT_FORCE : 0);
8945        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
8946    }
8947
8948    /*package*/ boolean performDexOpt(DexoptOptions options) {
8949        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8950            return false;
8951        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
8952            return false;
8953        }
8954
8955        if (options.isDexoptOnlySecondaryDex()) {
8956            return mDexManager.dexoptSecondaryDex(options);
8957        } else {
8958            int dexoptStatus = performDexOptWithStatus(options);
8959            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8960        }
8961    }
8962
8963    /**
8964     * Perform dexopt on the given package and return one of following result:
8965     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
8966     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
8967     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
8968     */
8969    /* package */ int performDexOptWithStatus(DexoptOptions options) {
8970        return performDexOptTraced(options);
8971    }
8972
8973    private int performDexOptTraced(DexoptOptions options) {
8974        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8975        try {
8976            return performDexOptInternal(options);
8977        } finally {
8978            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8979        }
8980    }
8981
8982    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8983    // if the package can now be considered up to date for the given filter.
8984    private int performDexOptInternal(DexoptOptions options) {
8985        PackageParser.Package p;
8986        synchronized (mPackages) {
8987            p = mPackages.get(options.getPackageName());
8988            if (p == null) {
8989                // Package could not be found. Report failure.
8990                return PackageDexOptimizer.DEX_OPT_FAILED;
8991            }
8992            mPackageUsage.maybeWriteAsync(mPackages);
8993            mCompilerStats.maybeWriteAsync();
8994        }
8995        long callingId = Binder.clearCallingIdentity();
8996        try {
8997            synchronized (mInstallLock) {
8998                return performDexOptInternalWithDependenciesLI(p, options);
8999            }
9000        } finally {
9001            Binder.restoreCallingIdentity(callingId);
9002        }
9003    }
9004
9005    public ArraySet<String> getOptimizablePackages() {
9006        ArraySet<String> pkgs = new ArraySet<String>();
9007        synchronized (mPackages) {
9008            for (PackageParser.Package p : mPackages.values()) {
9009                if (PackageDexOptimizer.canOptimizePackage(p)) {
9010                    pkgs.add(p.packageName);
9011                }
9012            }
9013        }
9014        return pkgs;
9015    }
9016
9017    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9018            DexoptOptions options) {
9019        // Select the dex optimizer based on the force parameter.
9020        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9021        //       allocate an object here.
9022        PackageDexOptimizer pdo = options.isForce()
9023                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9024                : mPackageDexOptimizer;
9025
9026        // Dexopt all dependencies first. Note: we ignore the return value and march on
9027        // on errors.
9028        // Note that we are going to call performDexOpt on those libraries as many times as
9029        // they are referenced in packages. When we do a batch of performDexOpt (for example
9030        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9031        // and the first package that uses the library will dexopt it. The
9032        // others will see that the compiled code for the library is up to date.
9033        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9034        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9035        if (!deps.isEmpty()) {
9036            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9037                    options.getCompilerFilter(), options.getSplitName(),
9038                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9039            for (PackageParser.Package depPackage : deps) {
9040                // TODO: Analyze and investigate if we (should) profile libraries.
9041                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9042                        getOrCreateCompilerPackageStats(depPackage),
9043                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9044            }
9045        }
9046        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9047                getOrCreateCompilerPackageStats(p),
9048                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9049    }
9050
9051    /**
9052     * Reconcile the information we have about the secondary dex files belonging to
9053     * {@code packagName} and the actual dex files. For all dex files that were
9054     * deleted, update the internal records and delete the generated oat files.
9055     */
9056    @Override
9057    public void reconcileSecondaryDexFiles(String packageName) {
9058        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9059            return;
9060        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9061            return;
9062        }
9063        mDexManager.reconcileSecondaryDexFiles(packageName);
9064    }
9065
9066    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9067    // a reference there.
9068    /*package*/ DexManager getDexManager() {
9069        return mDexManager;
9070    }
9071
9072    /**
9073     * Execute the background dexopt job immediately.
9074     */
9075    @Override
9076    public boolean runBackgroundDexoptJob() {
9077        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9078            return false;
9079        }
9080        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9081    }
9082
9083    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9084        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9085                || p.usesStaticLibraries != null) {
9086            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9087            Set<String> collectedNames = new HashSet<>();
9088            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9089
9090            retValue.remove(p);
9091
9092            return retValue;
9093        } else {
9094            return Collections.emptyList();
9095        }
9096    }
9097
9098    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9099            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9100        if (!collectedNames.contains(p.packageName)) {
9101            collectedNames.add(p.packageName);
9102            collected.add(p);
9103
9104            if (p.usesLibraries != null) {
9105                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9106                        null, collected, collectedNames);
9107            }
9108            if (p.usesOptionalLibraries != null) {
9109                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9110                        null, collected, collectedNames);
9111            }
9112            if (p.usesStaticLibraries != null) {
9113                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9114                        p.usesStaticLibrariesVersions, collected, collectedNames);
9115            }
9116        }
9117    }
9118
9119    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9120            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9121        final int libNameCount = libs.size();
9122        for (int i = 0; i < libNameCount; i++) {
9123            String libName = libs.get(i);
9124            int version = (versions != null && versions.length == libNameCount)
9125                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9126            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9127            if (libPkg != null) {
9128                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9129            }
9130        }
9131    }
9132
9133    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9134        synchronized (mPackages) {
9135            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9136            if (libEntry != null) {
9137                return mPackages.get(libEntry.apk);
9138            }
9139            return null;
9140        }
9141    }
9142
9143    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9144        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9145        if (versionedLib == null) {
9146            return null;
9147        }
9148        return versionedLib.get(version);
9149    }
9150
9151    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9152        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9153                pkg.staticSharedLibName);
9154        if (versionedLib == null) {
9155            return null;
9156        }
9157        int previousLibVersion = -1;
9158        final int versionCount = versionedLib.size();
9159        for (int i = 0; i < versionCount; i++) {
9160            final int libVersion = versionedLib.keyAt(i);
9161            if (libVersion < pkg.staticSharedLibVersion) {
9162                previousLibVersion = Math.max(previousLibVersion, libVersion);
9163            }
9164        }
9165        if (previousLibVersion >= 0) {
9166            return versionedLib.get(previousLibVersion);
9167        }
9168        return null;
9169    }
9170
9171    public void shutdown() {
9172        mPackageUsage.writeNow(mPackages);
9173        mCompilerStats.writeNow();
9174        mDexManager.writePackageDexUsageNow();
9175    }
9176
9177    @Override
9178    public void dumpProfiles(String packageName) {
9179        PackageParser.Package pkg;
9180        synchronized (mPackages) {
9181            pkg = mPackages.get(packageName);
9182            if (pkg == null) {
9183                throw new IllegalArgumentException("Unknown package: " + packageName);
9184            }
9185        }
9186        /* Only the shell, root, or the app user should be able to dump profiles. */
9187        int callingUid = Binder.getCallingUid();
9188        if (callingUid != Process.SHELL_UID &&
9189            callingUid != Process.ROOT_UID &&
9190            callingUid != pkg.applicationInfo.uid) {
9191            throw new SecurityException("dumpProfiles");
9192        }
9193
9194        synchronized (mInstallLock) {
9195            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9196            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9197            try {
9198                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9199                String codePaths = TextUtils.join(";", allCodePaths);
9200                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9201            } catch (InstallerException e) {
9202                Slog.w(TAG, "Failed to dump profiles", e);
9203            }
9204            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9205        }
9206    }
9207
9208    @Override
9209    public void forceDexOpt(String packageName) {
9210        enforceSystemOrRoot("forceDexOpt");
9211
9212        PackageParser.Package pkg;
9213        synchronized (mPackages) {
9214            pkg = mPackages.get(packageName);
9215            if (pkg == null) {
9216                throw new IllegalArgumentException("Unknown package: " + packageName);
9217            }
9218        }
9219
9220        synchronized (mInstallLock) {
9221            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9222
9223            // Whoever is calling forceDexOpt wants a compiled package.
9224            // Don't use profiles since that may cause compilation to be skipped.
9225            final int res = performDexOptInternalWithDependenciesLI(
9226                    pkg,
9227                    new DexoptOptions(packageName,
9228                            getDefaultCompilerFilter(),
9229                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9230
9231            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9232            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9233                throw new IllegalStateException("Failed to dexopt: " + res);
9234            }
9235        }
9236    }
9237
9238    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9239        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9240            Slog.w(TAG, "Unable to update from " + oldPkg.name
9241                    + " to " + newPkg.packageName
9242                    + ": old package not in system partition");
9243            return false;
9244        } else if (mPackages.get(oldPkg.name) != null) {
9245            Slog.w(TAG, "Unable to update from " + oldPkg.name
9246                    + " to " + newPkg.packageName
9247                    + ": old package still exists");
9248            return false;
9249        }
9250        return true;
9251    }
9252
9253    void removeCodePathLI(File codePath) {
9254        if (codePath.isDirectory()) {
9255            try {
9256                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9257            } catch (InstallerException e) {
9258                Slog.w(TAG, "Failed to remove code path", e);
9259            }
9260        } else {
9261            codePath.delete();
9262        }
9263    }
9264
9265    private int[] resolveUserIds(int userId) {
9266        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9267    }
9268
9269    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9270        if (pkg == null) {
9271            Slog.wtf(TAG, "Package was null!", new Throwable());
9272            return;
9273        }
9274        clearAppDataLeafLIF(pkg, userId, flags);
9275        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9276        for (int i = 0; i < childCount; i++) {
9277            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9278        }
9279    }
9280
9281    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9282        final PackageSetting ps;
9283        synchronized (mPackages) {
9284            ps = mSettings.mPackages.get(pkg.packageName);
9285        }
9286        for (int realUserId : resolveUserIds(userId)) {
9287            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9288            try {
9289                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9290                        ceDataInode);
9291            } catch (InstallerException e) {
9292                Slog.w(TAG, String.valueOf(e));
9293            }
9294        }
9295    }
9296
9297    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9298        if (pkg == null) {
9299            Slog.wtf(TAG, "Package was null!", new Throwable());
9300            return;
9301        }
9302        destroyAppDataLeafLIF(pkg, userId, flags);
9303        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9304        for (int i = 0; i < childCount; i++) {
9305            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9306        }
9307    }
9308
9309    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9310        final PackageSetting ps;
9311        synchronized (mPackages) {
9312            ps = mSettings.mPackages.get(pkg.packageName);
9313        }
9314        for (int realUserId : resolveUserIds(userId)) {
9315            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9316            try {
9317                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9318                        ceDataInode);
9319            } catch (InstallerException e) {
9320                Slog.w(TAG, String.valueOf(e));
9321            }
9322            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9323        }
9324    }
9325
9326    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9327        if (pkg == null) {
9328            Slog.wtf(TAG, "Package was null!", new Throwable());
9329            return;
9330        }
9331        destroyAppProfilesLeafLIF(pkg);
9332        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9333        for (int i = 0; i < childCount; i++) {
9334            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9335        }
9336    }
9337
9338    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9339        try {
9340            mInstaller.destroyAppProfiles(pkg.packageName);
9341        } catch (InstallerException e) {
9342            Slog.w(TAG, String.valueOf(e));
9343        }
9344    }
9345
9346    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9347        if (pkg == null) {
9348            Slog.wtf(TAG, "Package was null!", new Throwable());
9349            return;
9350        }
9351        clearAppProfilesLeafLIF(pkg);
9352        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9353        for (int i = 0; i < childCount; i++) {
9354            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9355        }
9356    }
9357
9358    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9359        try {
9360            mInstaller.clearAppProfiles(pkg.packageName);
9361        } catch (InstallerException e) {
9362            Slog.w(TAG, String.valueOf(e));
9363        }
9364    }
9365
9366    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9367            long lastUpdateTime) {
9368        // Set parent install/update time
9369        PackageSetting ps = (PackageSetting) pkg.mExtras;
9370        if (ps != null) {
9371            ps.firstInstallTime = firstInstallTime;
9372            ps.lastUpdateTime = lastUpdateTime;
9373        }
9374        // Set children install/update time
9375        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9376        for (int i = 0; i < childCount; i++) {
9377            PackageParser.Package childPkg = pkg.childPackages.get(i);
9378            ps = (PackageSetting) childPkg.mExtras;
9379            if (ps != null) {
9380                ps.firstInstallTime = firstInstallTime;
9381                ps.lastUpdateTime = lastUpdateTime;
9382            }
9383        }
9384    }
9385
9386    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9387            SharedLibraryEntry file,
9388            PackageParser.Package changingLib) {
9389        if (file.path != null) {
9390            usesLibraryFiles.add(file.path);
9391            return;
9392        }
9393        PackageParser.Package p = mPackages.get(file.apk);
9394        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9395            // If we are doing this while in the middle of updating a library apk,
9396            // then we need to make sure to use that new apk for determining the
9397            // dependencies here.  (We haven't yet finished committing the new apk
9398            // to the package manager state.)
9399            if (p == null || p.packageName.equals(changingLib.packageName)) {
9400                p = changingLib;
9401            }
9402        }
9403        if (p != null) {
9404            usesLibraryFiles.addAll(p.getAllCodePaths());
9405            if (p.usesLibraryFiles != null) {
9406                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9407            }
9408        }
9409    }
9410
9411    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9412            PackageParser.Package changingLib) throws PackageManagerException {
9413        if (pkg == null) {
9414            return;
9415        }
9416        // The collection used here must maintain the order of addition (so
9417        // that libraries are searched in the correct order) and must have no
9418        // duplicates.
9419        Set<String> usesLibraryFiles = null;
9420        if (pkg.usesLibraries != null) {
9421            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9422                    null, null, pkg.packageName, changingLib, true,
9423                    pkg.applicationInfo.targetSdkVersion, null);
9424        }
9425        if (pkg.usesStaticLibraries != null) {
9426            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9427                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9428                    pkg.packageName, changingLib, true,
9429                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9430        }
9431        if (pkg.usesOptionalLibraries != null) {
9432            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9433                    null, null, pkg.packageName, changingLib, false,
9434                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9435        }
9436        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9437            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9438        } else {
9439            pkg.usesLibraryFiles = null;
9440        }
9441    }
9442
9443    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9444            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9445            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9446            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9447            throws PackageManagerException {
9448        final int libCount = requestedLibraries.size();
9449        for (int i = 0; i < libCount; i++) {
9450            final String libName = requestedLibraries.get(i);
9451            final int libVersion = requiredVersions != null ? requiredVersions[i]
9452                    : SharedLibraryInfo.VERSION_UNDEFINED;
9453            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9454            if (libEntry == null) {
9455                if (required) {
9456                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9457                            "Package " + packageName + " requires unavailable shared library "
9458                                    + libName + "; failing!");
9459                } else if (DEBUG_SHARED_LIBRARIES) {
9460                    Slog.i(TAG, "Package " + packageName
9461                            + " desires unavailable shared library "
9462                            + libName + "; ignoring!");
9463                }
9464            } else {
9465                if (requiredVersions != null && requiredCertDigests != null) {
9466                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9467                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9468                            "Package " + packageName + " requires unavailable static shared"
9469                                    + " library " + libName + " version "
9470                                    + libEntry.info.getVersion() + "; failing!");
9471                    }
9472
9473                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9474                    if (libPkg == null) {
9475                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9476                                "Package " + packageName + " requires unavailable static shared"
9477                                        + " library; failing!");
9478                    }
9479
9480                    final String[] expectedCertDigests = requiredCertDigests[i];
9481                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9482                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9483                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9484                            : PackageUtils.computeSignaturesSha256Digests(
9485                                    new Signature[]{libPkg.mSignatures[0]});
9486
9487                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9488                    // target O we don't parse the "additional-certificate" tags similarly
9489                    // how we only consider all certs only for apps targeting O (see above).
9490                    // Therefore, the size check is safe to make.
9491                    if (expectedCertDigests.length != libCertDigests.length) {
9492                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9493                                "Package " + packageName + " requires differently signed" +
9494                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9495                    }
9496
9497                    // Use a predictable order as signature order may vary
9498                    Arrays.sort(libCertDigests);
9499                    Arrays.sort(expectedCertDigests);
9500
9501                    final int certCount = libCertDigests.length;
9502                    for (int j = 0; j < certCount; j++) {
9503                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9504                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9505                                    "Package " + packageName + " requires differently signed" +
9506                                            " static shared library; failing!");
9507                        }
9508                    }
9509                }
9510
9511                if (outUsedLibraries == null) {
9512                    // Use LinkedHashSet to preserve the order of files added to
9513                    // usesLibraryFiles while eliminating duplicates.
9514                    outUsedLibraries = new LinkedHashSet<>();
9515                }
9516                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9517            }
9518        }
9519        return outUsedLibraries;
9520    }
9521
9522    private static boolean hasString(List<String> list, List<String> which) {
9523        if (list == null) {
9524            return false;
9525        }
9526        for (int i=list.size()-1; i>=0; i--) {
9527            for (int j=which.size()-1; j>=0; j--) {
9528                if (which.get(j).equals(list.get(i))) {
9529                    return true;
9530                }
9531            }
9532        }
9533        return false;
9534    }
9535
9536    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9537            PackageParser.Package changingPkg) {
9538        ArrayList<PackageParser.Package> res = null;
9539        for (PackageParser.Package pkg : mPackages.values()) {
9540            if (changingPkg != null
9541                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9542                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9543                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9544                            changingPkg.staticSharedLibName)) {
9545                return null;
9546            }
9547            if (res == null) {
9548                res = new ArrayList<>();
9549            }
9550            res.add(pkg);
9551            try {
9552                updateSharedLibrariesLPr(pkg, changingPkg);
9553            } catch (PackageManagerException e) {
9554                // If a system app update or an app and a required lib missing we
9555                // delete the package and for updated system apps keep the data as
9556                // it is better for the user to reinstall than to be in an limbo
9557                // state. Also libs disappearing under an app should never happen
9558                // - just in case.
9559                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9560                    final int flags = pkg.isUpdatedSystemApp()
9561                            ? PackageManager.DELETE_KEEP_DATA : 0;
9562                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9563                            flags , null, true, null);
9564                }
9565                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9566            }
9567        }
9568        return res;
9569    }
9570
9571    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9572            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9573                    throws PackageManagerException {
9574        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9575        // If the package has children and this is the first dive in the function
9576        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9577        // whether all packages (parent and children) would be successfully scanned
9578        // before the actual scan since scanning mutates internal state and we want
9579        // to atomically install the package and its children.
9580        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9581            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9582                scanFlags |= SCAN_CHECK_ONLY;
9583            }
9584        } else {
9585            scanFlags &= ~SCAN_CHECK_ONLY;
9586        }
9587
9588        final PackageParser.Package scannedPkg;
9589        try {
9590            // Scan the parent
9591            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9592            // Scan the children
9593            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9594            for (int i = 0; i < childCount; i++) {
9595                PackageParser.Package childPkg = pkg.childPackages.get(i);
9596                scanPackageLI(childPkg, policyFlags,
9597                        scanFlags, currentTime, user);
9598            }
9599        } finally {
9600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9601        }
9602
9603        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9604            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9605        }
9606
9607        return scannedPkg;
9608    }
9609
9610    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9611            int scanFlags, long currentTime, @Nullable UserHandle user)
9612                    throws PackageManagerException {
9613        boolean success = false;
9614        try {
9615            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9616                    currentTime, user);
9617            success = true;
9618            return res;
9619        } finally {
9620            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9621                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9622                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9623                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9624                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9625            }
9626        }
9627    }
9628
9629    /**
9630     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9631     */
9632    private static boolean apkHasCode(String fileName) {
9633        StrictJarFile jarFile = null;
9634        try {
9635            jarFile = new StrictJarFile(fileName,
9636                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9637            return jarFile.findEntry("classes.dex") != null;
9638        } catch (IOException ignore) {
9639        } finally {
9640            try {
9641                if (jarFile != null) {
9642                    jarFile.close();
9643                }
9644            } catch (IOException ignore) {}
9645        }
9646        return false;
9647    }
9648
9649    /**
9650     * Enforces code policy for the package. This ensures that if an APK has
9651     * declared hasCode="true" in its manifest that the APK actually contains
9652     * code.
9653     *
9654     * @throws PackageManagerException If bytecode could not be found when it should exist
9655     */
9656    private static void assertCodePolicy(PackageParser.Package pkg)
9657            throws PackageManagerException {
9658        final boolean shouldHaveCode =
9659                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9660        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9661            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9662                    "Package " + pkg.baseCodePath + " code is missing");
9663        }
9664
9665        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9666            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9667                final boolean splitShouldHaveCode =
9668                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9669                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9670                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9671                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9672                }
9673            }
9674        }
9675    }
9676
9677    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9678            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9679                    throws PackageManagerException {
9680        if (DEBUG_PACKAGE_SCANNING) {
9681            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9682                Log.d(TAG, "Scanning package " + pkg.packageName);
9683        }
9684
9685        applyPolicy(pkg, policyFlags);
9686
9687        assertPackageIsValid(pkg, policyFlags, scanFlags);
9688
9689        if (Build.IS_DEBUGGABLE &&
9690                pkg.isPrivileged() &&
9691                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
9692            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
9693        }
9694
9695        // Initialize package source and resource directories
9696        final File scanFile = new File(pkg.codePath);
9697        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9698        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9699
9700        SharedUserSetting suid = null;
9701        PackageSetting pkgSetting = null;
9702
9703        // Getting the package setting may have a side-effect, so if we
9704        // are only checking if scan would succeed, stash a copy of the
9705        // old setting to restore at the end.
9706        PackageSetting nonMutatedPs = null;
9707
9708        // We keep references to the derived CPU Abis from settings in oder to reuse
9709        // them in the case where we're not upgrading or booting for the first time.
9710        String primaryCpuAbiFromSettings = null;
9711        String secondaryCpuAbiFromSettings = null;
9712
9713        // writer
9714        synchronized (mPackages) {
9715            if (pkg.mSharedUserId != null) {
9716                // SIDE EFFECTS; may potentially allocate a new shared user
9717                suid = mSettings.getSharedUserLPw(
9718                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9719                if (DEBUG_PACKAGE_SCANNING) {
9720                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9721                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9722                                + "): packages=" + suid.packages);
9723                }
9724            }
9725
9726            // Check if we are renaming from an original package name.
9727            PackageSetting origPackage = null;
9728            String realName = null;
9729            if (pkg.mOriginalPackages != null) {
9730                // This package may need to be renamed to a previously
9731                // installed name.  Let's check on that...
9732                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9733                if (pkg.mOriginalPackages.contains(renamed)) {
9734                    // This package had originally been installed as the
9735                    // original name, and we have already taken care of
9736                    // transitioning to the new one.  Just update the new
9737                    // one to continue using the old name.
9738                    realName = pkg.mRealPackage;
9739                    if (!pkg.packageName.equals(renamed)) {
9740                        // Callers into this function may have already taken
9741                        // care of renaming the package; only do it here if
9742                        // it is not already done.
9743                        pkg.setPackageName(renamed);
9744                    }
9745                } else {
9746                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9747                        if ((origPackage = mSettings.getPackageLPr(
9748                                pkg.mOriginalPackages.get(i))) != null) {
9749                            // We do have the package already installed under its
9750                            // original name...  should we use it?
9751                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9752                                // New package is not compatible with original.
9753                                origPackage = null;
9754                                continue;
9755                            } else if (origPackage.sharedUser != null) {
9756                                // Make sure uid is compatible between packages.
9757                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9758                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9759                                            + " to " + pkg.packageName + ": old uid "
9760                                            + origPackage.sharedUser.name
9761                                            + " differs from " + pkg.mSharedUserId);
9762                                    origPackage = null;
9763                                    continue;
9764                                }
9765                                // TODO: Add case when shared user id is added [b/28144775]
9766                            } else {
9767                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9768                                        + pkg.packageName + " to old name " + origPackage.name);
9769                            }
9770                            break;
9771                        }
9772                    }
9773                }
9774            }
9775
9776            if (mTransferedPackages.contains(pkg.packageName)) {
9777                Slog.w(TAG, "Package " + pkg.packageName
9778                        + " was transferred to another, but its .apk remains");
9779            }
9780
9781            // See comments in nonMutatedPs declaration
9782            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9783                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9784                if (foundPs != null) {
9785                    nonMutatedPs = new PackageSetting(foundPs);
9786                }
9787            }
9788
9789            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9790                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9791                if (foundPs != null) {
9792                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9793                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9794                }
9795            }
9796
9797            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9798            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9799                PackageManagerService.reportSettingsProblem(Log.WARN,
9800                        "Package " + pkg.packageName + " shared user changed from "
9801                                + (pkgSetting.sharedUser != null
9802                                        ? pkgSetting.sharedUser.name : "<nothing>")
9803                                + " to "
9804                                + (suid != null ? suid.name : "<nothing>")
9805                                + "; replacing with new");
9806                pkgSetting = null;
9807            }
9808            final PackageSetting oldPkgSetting =
9809                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9810            final PackageSetting disabledPkgSetting =
9811                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9812
9813            String[] usesStaticLibraries = null;
9814            if (pkg.usesStaticLibraries != null) {
9815                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9816                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9817            }
9818
9819            if (pkgSetting == null) {
9820                final String parentPackageName = (pkg.parentPackage != null)
9821                        ? pkg.parentPackage.packageName : null;
9822                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9823                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
9824                // REMOVE SharedUserSetting from method; update in a separate call
9825                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9826                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9827                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9828                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9829                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9830                        true /*allowInstall*/, instantApp, virtualPreload,
9831                        parentPackageName, pkg.getChildPackageNames(),
9832                        UserManagerService.getInstance(), usesStaticLibraries,
9833                        pkg.usesStaticLibrariesVersions);
9834                // SIDE EFFECTS; updates system state; move elsewhere
9835                if (origPackage != null) {
9836                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9837                }
9838                mSettings.addUserToSettingLPw(pkgSetting);
9839            } else {
9840                // REMOVE SharedUserSetting from method; update in a separate call.
9841                //
9842                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9843                // secondaryCpuAbi are not known at this point so we always update them
9844                // to null here, only to reset them at a later point.
9845                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9846                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9847                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9848                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9849                        UserManagerService.getInstance(), usesStaticLibraries,
9850                        pkg.usesStaticLibrariesVersions);
9851            }
9852            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9853            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9854
9855            // SIDE EFFECTS; modifies system state; move elsewhere
9856            if (pkgSetting.origPackage != null) {
9857                // If we are first transitioning from an original package,
9858                // fix up the new package's name now.  We need to do this after
9859                // looking up the package under its new name, so getPackageLP
9860                // can take care of fiddling things correctly.
9861                pkg.setPackageName(origPackage.name);
9862
9863                // File a report about this.
9864                String msg = "New package " + pkgSetting.realName
9865                        + " renamed to replace old package " + pkgSetting.name;
9866                reportSettingsProblem(Log.WARN, msg);
9867
9868                // Make a note of it.
9869                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9870                    mTransferedPackages.add(origPackage.name);
9871                }
9872
9873                // No longer need to retain this.
9874                pkgSetting.origPackage = null;
9875            }
9876
9877            // SIDE EFFECTS; modifies system state; move elsewhere
9878            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9879                // Make a note of it.
9880                mTransferedPackages.add(pkg.packageName);
9881            }
9882
9883            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9884                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9885            }
9886
9887            if ((scanFlags & SCAN_BOOTING) == 0
9888                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9889                // Check all shared libraries and map to their actual file path.
9890                // We only do this here for apps not on a system dir, because those
9891                // are the only ones that can fail an install due to this.  We
9892                // will take care of the system apps by updating all of their
9893                // library paths after the scan is done. Also during the initial
9894                // scan don't update any libs as we do this wholesale after all
9895                // apps are scanned to avoid dependency based scanning.
9896                updateSharedLibrariesLPr(pkg, null);
9897            }
9898
9899            if (mFoundPolicyFile) {
9900                SELinuxMMAC.assignSeInfoValue(pkg);
9901            }
9902            pkg.applicationInfo.uid = pkgSetting.appId;
9903            pkg.mExtras = pkgSetting;
9904
9905
9906            // Static shared libs have same package with different versions where
9907            // we internally use a synthetic package name to allow multiple versions
9908            // of the same package, therefore we need to compare signatures against
9909            // the package setting for the latest library version.
9910            PackageSetting signatureCheckPs = pkgSetting;
9911            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9912                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9913                if (libraryEntry != null) {
9914                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9915                }
9916            }
9917
9918            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9919            if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9920                if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9921                    // We just determined the app is signed correctly, so bring
9922                    // over the latest parsed certs.
9923                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9924                } else {
9925                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9926                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9927                                "Package " + pkg.packageName + " upgrade keys do not match the "
9928                                + "previously installed version");
9929                    } else {
9930                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9931                        String msg = "System package " + pkg.packageName
9932                                + " signature changed; retaining data.";
9933                        reportSettingsProblem(Log.WARN, msg);
9934                    }
9935                }
9936            } else {
9937                try {
9938                    final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9939                    final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9940                    final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures,
9941                            compareCompat, compareRecover);
9942                    // The new KeySets will be re-added later in the scanning process.
9943                    if (compatMatch) {
9944                        synchronized (mPackages) {
9945                            ksms.removeAppKeySetDataLPw(pkg.packageName);
9946                        }
9947                    }
9948                    // We just determined the app is signed correctly, so bring
9949                    // over the latest parsed certs.
9950                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9951                } catch (PackageManagerException e) {
9952                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9953                        throw e;
9954                    }
9955                    // The signature has changed, but this package is in the system
9956                    // image...  let's recover!
9957                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9958                    // However...  if this package is part of a shared user, but it
9959                    // doesn't match the signature of the shared user, let's fail.
9960                    // What this means is that you can't change the signatures
9961                    // associated with an overall shared user, which doesn't seem all
9962                    // that unreasonable.
9963                    if (signatureCheckPs.sharedUser != null) {
9964                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9965                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9966                            throw new PackageManagerException(
9967                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9968                                    "Signature mismatch for shared user: "
9969                                            + pkgSetting.sharedUser);
9970                        }
9971                    }
9972                    // File a report about this.
9973                    String msg = "System package " + pkg.packageName
9974                            + " signature changed; retaining data.";
9975                    reportSettingsProblem(Log.WARN, msg);
9976                }
9977            }
9978
9979            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9980                // This package wants to adopt ownership of permissions from
9981                // another package.
9982                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9983                    final String origName = pkg.mAdoptPermissions.get(i);
9984                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9985                    if (orig != null) {
9986                        if (verifyPackageUpdateLPr(orig, pkg)) {
9987                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9988                                    + pkg.packageName);
9989                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9990                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9991                        }
9992                    }
9993                }
9994            }
9995        }
9996
9997        pkg.applicationInfo.processName = fixProcessName(
9998                pkg.applicationInfo.packageName,
9999                pkg.applicationInfo.processName);
10000
10001        if (pkg != mPlatformPackage) {
10002            // Get all of our default paths setup
10003            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10004        }
10005
10006        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10007
10008        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10009            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10010                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10011                final boolean extractNativeLibs = !pkg.isLibrary();
10012                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10013                        mAppLib32InstallDir);
10014                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10015
10016                // Some system apps still use directory structure for native libraries
10017                // in which case we might end up not detecting abi solely based on apk
10018                // structure. Try to detect abi based on directory structure.
10019                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10020                        pkg.applicationInfo.primaryCpuAbi == null) {
10021                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10022                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10023                }
10024            } else {
10025                // This is not a first boot or an upgrade, don't bother deriving the
10026                // ABI during the scan. Instead, trust the value that was stored in the
10027                // package setting.
10028                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10029                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10030
10031                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10032
10033                if (DEBUG_ABI_SELECTION) {
10034                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10035                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10036                        pkg.applicationInfo.secondaryCpuAbi);
10037                }
10038            }
10039        } else {
10040            if ((scanFlags & SCAN_MOVE) != 0) {
10041                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10042                // but we already have this packages package info in the PackageSetting. We just
10043                // use that and derive the native library path based on the new codepath.
10044                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10045                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10046            }
10047
10048            // Set native library paths again. For moves, the path will be updated based on the
10049            // ABIs we've determined above. For non-moves, the path will be updated based on the
10050            // ABIs we determined during compilation, but the path will depend on the final
10051            // package path (after the rename away from the stage path).
10052            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10053        }
10054
10055        // This is a special case for the "system" package, where the ABI is
10056        // dictated by the zygote configuration (and init.rc). We should keep track
10057        // of this ABI so that we can deal with "normal" applications that run under
10058        // the same UID correctly.
10059        if (mPlatformPackage == pkg) {
10060            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10061                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10062        }
10063
10064        // If there's a mismatch between the abi-override in the package setting
10065        // and the abiOverride specified for the install. Warn about this because we
10066        // would've already compiled the app without taking the package setting into
10067        // account.
10068        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10069            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10070                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10071                        " for package " + pkg.packageName);
10072            }
10073        }
10074
10075        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10076        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10077        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10078
10079        // Copy the derived override back to the parsed package, so that we can
10080        // update the package settings accordingly.
10081        pkg.cpuAbiOverride = cpuAbiOverride;
10082
10083        if (DEBUG_ABI_SELECTION) {
10084            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10085                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10086                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10087        }
10088
10089        // Push the derived path down into PackageSettings so we know what to
10090        // clean up at uninstall time.
10091        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10092
10093        if (DEBUG_ABI_SELECTION) {
10094            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10095                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10096                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10097        }
10098
10099        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10100        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10101            // We don't do this here during boot because we can do it all
10102            // at once after scanning all existing packages.
10103            //
10104            // We also do this *before* we perform dexopt on this package, so that
10105            // we can avoid redundant dexopts, and also to make sure we've got the
10106            // code and package path correct.
10107            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10108        }
10109
10110        if (mFactoryTest && pkg.requestedPermissions.contains(
10111                android.Manifest.permission.FACTORY_TEST)) {
10112            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10113        }
10114
10115        if (isSystemApp(pkg)) {
10116            pkgSetting.isOrphaned = true;
10117        }
10118
10119        // Take care of first install / last update times.
10120        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10121        if (currentTime != 0) {
10122            if (pkgSetting.firstInstallTime == 0) {
10123                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10124            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10125                pkgSetting.lastUpdateTime = currentTime;
10126            }
10127        } else if (pkgSetting.firstInstallTime == 0) {
10128            // We need *something*.  Take time time stamp of the file.
10129            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10130        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10131            if (scanFileTime != pkgSetting.timeStamp) {
10132                // A package on the system image has changed; consider this
10133                // to be an update.
10134                pkgSetting.lastUpdateTime = scanFileTime;
10135            }
10136        }
10137        pkgSetting.setTimeStamp(scanFileTime);
10138
10139        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10140            if (nonMutatedPs != null) {
10141                synchronized (mPackages) {
10142                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10143                }
10144            }
10145        } else {
10146            final int userId = user == null ? 0 : user.getIdentifier();
10147            // Modify state for the given package setting
10148            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10149                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10150            if (pkgSetting.getInstantApp(userId)) {
10151                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10152            }
10153        }
10154        return pkg;
10155    }
10156
10157    /**
10158     * Applies policy to the parsed package based upon the given policy flags.
10159     * Ensures the package is in a good state.
10160     * <p>
10161     * Implementation detail: This method must NOT have any side effect. It would
10162     * ideally be static, but, it requires locks to read system state.
10163     */
10164    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10165        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10166            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10167            if (pkg.applicationInfo.isDirectBootAware()) {
10168                // we're direct boot aware; set for all components
10169                for (PackageParser.Service s : pkg.services) {
10170                    s.info.encryptionAware = s.info.directBootAware = true;
10171                }
10172                for (PackageParser.Provider p : pkg.providers) {
10173                    p.info.encryptionAware = p.info.directBootAware = true;
10174                }
10175                for (PackageParser.Activity a : pkg.activities) {
10176                    a.info.encryptionAware = a.info.directBootAware = true;
10177                }
10178                for (PackageParser.Activity r : pkg.receivers) {
10179                    r.info.encryptionAware = r.info.directBootAware = true;
10180                }
10181            }
10182            if (compressedFileExists(pkg.codePath)) {
10183                pkg.isStub = true;
10184            }
10185        } else {
10186            // Only allow system apps to be flagged as core apps.
10187            pkg.coreApp = false;
10188            // clear flags not applicable to regular apps
10189            pkg.applicationInfo.privateFlags &=
10190                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10191            pkg.applicationInfo.privateFlags &=
10192                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10193        }
10194        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10195
10196        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10197            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10198        }
10199
10200        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
10201            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10202        }
10203
10204        if (!isSystemApp(pkg)) {
10205            // Only system apps can use these features.
10206            pkg.mOriginalPackages = null;
10207            pkg.mRealPackage = null;
10208            pkg.mAdoptPermissions = null;
10209        }
10210    }
10211
10212    /**
10213     * Asserts the parsed package is valid according to the given policy. If the
10214     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10215     * <p>
10216     * Implementation detail: This method must NOT have any side effects. It would
10217     * ideally be static, but, it requires locks to read system state.
10218     *
10219     * @throws PackageManagerException If the package fails any of the validation checks
10220     */
10221    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10222            throws PackageManagerException {
10223        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10224            assertCodePolicy(pkg);
10225        }
10226
10227        if (pkg.applicationInfo.getCodePath() == null ||
10228                pkg.applicationInfo.getResourcePath() == null) {
10229            // Bail out. The resource and code paths haven't been set.
10230            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10231                    "Code and resource paths haven't been set correctly");
10232        }
10233
10234        // Make sure we're not adding any bogus keyset info
10235        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10236        ksms.assertScannedPackageValid(pkg);
10237
10238        synchronized (mPackages) {
10239            // The special "android" package can only be defined once
10240            if (pkg.packageName.equals("android")) {
10241                if (mAndroidApplication != null) {
10242                    Slog.w(TAG, "*************************************************");
10243                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10244                    Slog.w(TAG, " codePath=" + pkg.codePath);
10245                    Slog.w(TAG, "*************************************************");
10246                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10247                            "Core android package being redefined.  Skipping.");
10248                }
10249            }
10250
10251            // A package name must be unique; don't allow duplicates
10252            if (mPackages.containsKey(pkg.packageName)) {
10253                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10254                        "Application package " + pkg.packageName
10255                        + " already installed.  Skipping duplicate.");
10256            }
10257
10258            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10259                // Static libs have a synthetic package name containing the version
10260                // but we still want the base name to be unique.
10261                if (mPackages.containsKey(pkg.manifestPackageName)) {
10262                    throw new PackageManagerException(
10263                            "Duplicate static shared lib provider package");
10264                }
10265
10266                // Static shared libraries should have at least O target SDK
10267                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10268                    throw new PackageManagerException(
10269                            "Packages declaring static-shared libs must target O SDK or higher");
10270                }
10271
10272                // Package declaring static a shared lib cannot be instant apps
10273                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10274                    throw new PackageManagerException(
10275                            "Packages declaring static-shared libs cannot be instant apps");
10276                }
10277
10278                // Package declaring static a shared lib cannot be renamed since the package
10279                // name is synthetic and apps can't code around package manager internals.
10280                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10281                    throw new PackageManagerException(
10282                            "Packages declaring static-shared libs cannot be renamed");
10283                }
10284
10285                // Package declaring static a shared lib cannot declare child packages
10286                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10287                    throw new PackageManagerException(
10288                            "Packages declaring static-shared libs cannot have child packages");
10289                }
10290
10291                // Package declaring static a shared lib cannot declare dynamic libs
10292                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10293                    throw new PackageManagerException(
10294                            "Packages declaring static-shared libs cannot declare dynamic libs");
10295                }
10296
10297                // Package declaring static a shared lib cannot declare shared users
10298                if (pkg.mSharedUserId != null) {
10299                    throw new PackageManagerException(
10300                            "Packages declaring static-shared libs cannot declare shared users");
10301                }
10302
10303                // Static shared libs cannot declare activities
10304                if (!pkg.activities.isEmpty()) {
10305                    throw new PackageManagerException(
10306                            "Static shared libs cannot declare activities");
10307                }
10308
10309                // Static shared libs cannot declare services
10310                if (!pkg.services.isEmpty()) {
10311                    throw new PackageManagerException(
10312                            "Static shared libs cannot declare services");
10313                }
10314
10315                // Static shared libs cannot declare providers
10316                if (!pkg.providers.isEmpty()) {
10317                    throw new PackageManagerException(
10318                            "Static shared libs cannot declare content providers");
10319                }
10320
10321                // Static shared libs cannot declare receivers
10322                if (!pkg.receivers.isEmpty()) {
10323                    throw new PackageManagerException(
10324                            "Static shared libs cannot declare broadcast receivers");
10325                }
10326
10327                // Static shared libs cannot declare permission groups
10328                if (!pkg.permissionGroups.isEmpty()) {
10329                    throw new PackageManagerException(
10330                            "Static shared libs cannot declare permission groups");
10331                }
10332
10333                // Static shared libs cannot declare permissions
10334                if (!pkg.permissions.isEmpty()) {
10335                    throw new PackageManagerException(
10336                            "Static shared libs cannot declare permissions");
10337                }
10338
10339                // Static shared libs cannot declare protected broadcasts
10340                if (pkg.protectedBroadcasts != null) {
10341                    throw new PackageManagerException(
10342                            "Static shared libs cannot declare protected broadcasts");
10343                }
10344
10345                // Static shared libs cannot be overlay targets
10346                if (pkg.mOverlayTarget != null) {
10347                    throw new PackageManagerException(
10348                            "Static shared libs cannot be overlay targets");
10349                }
10350
10351                // The version codes must be ordered as lib versions
10352                int minVersionCode = Integer.MIN_VALUE;
10353                int maxVersionCode = Integer.MAX_VALUE;
10354
10355                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10356                        pkg.staticSharedLibName);
10357                if (versionedLib != null) {
10358                    final int versionCount = versionedLib.size();
10359                    for (int i = 0; i < versionCount; i++) {
10360                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10361                        final int libVersionCode = libInfo.getDeclaringPackage()
10362                                .getVersionCode();
10363                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10364                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10365                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10366                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10367                        } else {
10368                            minVersionCode = maxVersionCode = libVersionCode;
10369                            break;
10370                        }
10371                    }
10372                }
10373                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10374                    throw new PackageManagerException("Static shared"
10375                            + " lib version codes must be ordered as lib versions");
10376                }
10377            }
10378
10379            // Only privileged apps and updated privileged apps can add child packages.
10380            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10381                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10382                    throw new PackageManagerException("Only privileged apps can add child "
10383                            + "packages. Ignoring package " + pkg.packageName);
10384                }
10385                final int childCount = pkg.childPackages.size();
10386                for (int i = 0; i < childCount; i++) {
10387                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10388                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10389                            childPkg.packageName)) {
10390                        throw new PackageManagerException("Can't override child of "
10391                                + "another disabled app. Ignoring package " + pkg.packageName);
10392                    }
10393                }
10394            }
10395
10396            // If we're only installing presumed-existing packages, require that the
10397            // scanned APK is both already known and at the path previously established
10398            // for it.  Previously unknown packages we pick up normally, but if we have an
10399            // a priori expectation about this package's install presence, enforce it.
10400            // With a singular exception for new system packages. When an OTA contains
10401            // a new system package, we allow the codepath to change from a system location
10402            // to the user-installed location. If we don't allow this change, any newer,
10403            // user-installed version of the application will be ignored.
10404            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10405                if (mExpectingBetter.containsKey(pkg.packageName)) {
10406                    logCriticalInfo(Log.WARN,
10407                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10408                } else {
10409                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10410                    if (known != null) {
10411                        if (DEBUG_PACKAGE_SCANNING) {
10412                            Log.d(TAG, "Examining " + pkg.codePath
10413                                    + " and requiring known paths " + known.codePathString
10414                                    + " & " + known.resourcePathString);
10415                        }
10416                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10417                                || !pkg.applicationInfo.getResourcePath().equals(
10418                                        known.resourcePathString)) {
10419                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10420                                    "Application package " + pkg.packageName
10421                                    + " found at " + pkg.applicationInfo.getCodePath()
10422                                    + " but expected at " + known.codePathString
10423                                    + "; ignoring.");
10424                        }
10425                    } else {
10426                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10427                                "Application package " + pkg.packageName
10428                                + " not found; ignoring.");
10429                    }
10430                }
10431            }
10432
10433            // Verify that this new package doesn't have any content providers
10434            // that conflict with existing packages.  Only do this if the
10435            // package isn't already installed, since we don't want to break
10436            // things that are installed.
10437            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10438                final int N = pkg.providers.size();
10439                int i;
10440                for (i=0; i<N; i++) {
10441                    PackageParser.Provider p = pkg.providers.get(i);
10442                    if (p.info.authority != null) {
10443                        String names[] = p.info.authority.split(";");
10444                        for (int j = 0; j < names.length; j++) {
10445                            if (mProvidersByAuthority.containsKey(names[j])) {
10446                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10447                                final String otherPackageName =
10448                                        ((other != null && other.getComponentName() != null) ?
10449                                                other.getComponentName().getPackageName() : "?");
10450                                throw new PackageManagerException(
10451                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10452                                        "Can't install because provider name " + names[j]
10453                                                + " (in package " + pkg.applicationInfo.packageName
10454                                                + ") is already used by " + otherPackageName);
10455                            }
10456                        }
10457                    }
10458                }
10459            }
10460        }
10461    }
10462
10463    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10464            int type, String declaringPackageName, int declaringVersionCode) {
10465        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10466        if (versionedLib == null) {
10467            versionedLib = new SparseArray<>();
10468            mSharedLibraries.put(name, versionedLib);
10469            if (type == SharedLibraryInfo.TYPE_STATIC) {
10470                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10471            }
10472        } else if (versionedLib.indexOfKey(version) >= 0) {
10473            return false;
10474        }
10475        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10476                version, type, declaringPackageName, declaringVersionCode);
10477        versionedLib.put(version, libEntry);
10478        return true;
10479    }
10480
10481    private boolean removeSharedLibraryLPw(String name, int version) {
10482        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10483        if (versionedLib == null) {
10484            return false;
10485        }
10486        final int libIdx = versionedLib.indexOfKey(version);
10487        if (libIdx < 0) {
10488            return false;
10489        }
10490        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10491        versionedLib.remove(version);
10492        if (versionedLib.size() <= 0) {
10493            mSharedLibraries.remove(name);
10494            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10495                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10496                        .getPackageName());
10497            }
10498        }
10499        return true;
10500    }
10501
10502    /**
10503     * Adds a scanned package to the system. When this method is finished, the package will
10504     * be available for query, resolution, etc...
10505     */
10506    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10507            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10508        final String pkgName = pkg.packageName;
10509        if (mCustomResolverComponentName != null &&
10510                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10511            setUpCustomResolverActivity(pkg);
10512        }
10513
10514        if (pkg.packageName.equals("android")) {
10515            synchronized (mPackages) {
10516                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10517                    // Set up information for our fall-back user intent resolution activity.
10518                    mPlatformPackage = pkg;
10519                    pkg.mVersionCode = mSdkVersion;
10520                    mAndroidApplication = pkg.applicationInfo;
10521                    if (!mResolverReplaced) {
10522                        mResolveActivity.applicationInfo = mAndroidApplication;
10523                        mResolveActivity.name = ResolverActivity.class.getName();
10524                        mResolveActivity.packageName = mAndroidApplication.packageName;
10525                        mResolveActivity.processName = "system:ui";
10526                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10527                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10528                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10529                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10530                        mResolveActivity.exported = true;
10531                        mResolveActivity.enabled = true;
10532                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10533                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10534                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10535                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10536                                | ActivityInfo.CONFIG_ORIENTATION
10537                                | ActivityInfo.CONFIG_KEYBOARD
10538                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10539                        mResolveInfo.activityInfo = mResolveActivity;
10540                        mResolveInfo.priority = 0;
10541                        mResolveInfo.preferredOrder = 0;
10542                        mResolveInfo.match = 0;
10543                        mResolveComponentName = new ComponentName(
10544                                mAndroidApplication.packageName, mResolveActivity.name);
10545                    }
10546                }
10547            }
10548        }
10549
10550        ArrayList<PackageParser.Package> clientLibPkgs = null;
10551        // writer
10552        synchronized (mPackages) {
10553            boolean hasStaticSharedLibs = false;
10554
10555            // Any app can add new static shared libraries
10556            if (pkg.staticSharedLibName != null) {
10557                // Static shared libs don't allow renaming as they have synthetic package
10558                // names to allow install of multiple versions, so use name from manifest.
10559                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10560                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10561                        pkg.manifestPackageName, pkg.mVersionCode)) {
10562                    hasStaticSharedLibs = true;
10563                } else {
10564                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10565                                + pkg.staticSharedLibName + " already exists; skipping");
10566                }
10567                // Static shared libs cannot be updated once installed since they
10568                // use synthetic package name which includes the version code, so
10569                // not need to update other packages's shared lib dependencies.
10570            }
10571
10572            if (!hasStaticSharedLibs
10573                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10574                // Only system apps can add new dynamic shared libraries.
10575                if (pkg.libraryNames != null) {
10576                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10577                        String name = pkg.libraryNames.get(i);
10578                        boolean allowed = false;
10579                        if (pkg.isUpdatedSystemApp()) {
10580                            // New library entries can only be added through the
10581                            // system image.  This is important to get rid of a lot
10582                            // of nasty edge cases: for example if we allowed a non-
10583                            // system update of the app to add a library, then uninstalling
10584                            // the update would make the library go away, and assumptions
10585                            // we made such as through app install filtering would now
10586                            // have allowed apps on the device which aren't compatible
10587                            // with it.  Better to just have the restriction here, be
10588                            // conservative, and create many fewer cases that can negatively
10589                            // impact the user experience.
10590                            final PackageSetting sysPs = mSettings
10591                                    .getDisabledSystemPkgLPr(pkg.packageName);
10592                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10593                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10594                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10595                                        allowed = true;
10596                                        break;
10597                                    }
10598                                }
10599                            }
10600                        } else {
10601                            allowed = true;
10602                        }
10603                        if (allowed) {
10604                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10605                                    SharedLibraryInfo.VERSION_UNDEFINED,
10606                                    SharedLibraryInfo.TYPE_DYNAMIC,
10607                                    pkg.packageName, pkg.mVersionCode)) {
10608                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10609                                        + name + " already exists; skipping");
10610                            }
10611                        } else {
10612                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10613                                    + name + " that is not declared on system image; skipping");
10614                        }
10615                    }
10616
10617                    if ((scanFlags & SCAN_BOOTING) == 0) {
10618                        // If we are not booting, we need to update any applications
10619                        // that are clients of our shared library.  If we are booting,
10620                        // this will all be done once the scan is complete.
10621                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10622                    }
10623                }
10624            }
10625        }
10626
10627        if ((scanFlags & SCAN_BOOTING) != 0) {
10628            // No apps can run during boot scan, so they don't need to be frozen
10629        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10630            // Caller asked to not kill app, so it's probably not frozen
10631        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10632            // Caller asked us to ignore frozen check for some reason; they
10633            // probably didn't know the package name
10634        } else {
10635            // We're doing major surgery on this package, so it better be frozen
10636            // right now to keep it from launching
10637            checkPackageFrozen(pkgName);
10638        }
10639
10640        // Also need to kill any apps that are dependent on the library.
10641        if (clientLibPkgs != null) {
10642            for (int i=0; i<clientLibPkgs.size(); i++) {
10643                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10644                killApplication(clientPkg.applicationInfo.packageName,
10645                        clientPkg.applicationInfo.uid, "update lib");
10646            }
10647        }
10648
10649        // writer
10650        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10651
10652        synchronized (mPackages) {
10653            // We don't expect installation to fail beyond this point
10654
10655            // Add the new setting to mSettings
10656            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10657            // Add the new setting to mPackages
10658            mPackages.put(pkg.applicationInfo.packageName, pkg);
10659            // Make sure we don't accidentally delete its data.
10660            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10661            while (iter.hasNext()) {
10662                PackageCleanItem item = iter.next();
10663                if (pkgName.equals(item.packageName)) {
10664                    iter.remove();
10665                }
10666            }
10667
10668            // Add the package's KeySets to the global KeySetManagerService
10669            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10670            ksms.addScannedPackageLPw(pkg);
10671
10672            int N = pkg.providers.size();
10673            StringBuilder r = null;
10674            int i;
10675            for (i=0; i<N; i++) {
10676                PackageParser.Provider p = pkg.providers.get(i);
10677                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10678                        p.info.processName);
10679                mProviders.addProvider(p);
10680                p.syncable = p.info.isSyncable;
10681                if (p.info.authority != null) {
10682                    String names[] = p.info.authority.split(";");
10683                    p.info.authority = null;
10684                    for (int j = 0; j < names.length; j++) {
10685                        if (j == 1 && p.syncable) {
10686                            // We only want the first authority for a provider to possibly be
10687                            // syncable, so if we already added this provider using a different
10688                            // authority clear the syncable flag. We copy the provider before
10689                            // changing it because the mProviders object contains a reference
10690                            // to a provider that we don't want to change.
10691                            // Only do this for the second authority since the resulting provider
10692                            // object can be the same for all future authorities for this provider.
10693                            p = new PackageParser.Provider(p);
10694                            p.syncable = false;
10695                        }
10696                        if (!mProvidersByAuthority.containsKey(names[j])) {
10697                            mProvidersByAuthority.put(names[j], p);
10698                            if (p.info.authority == null) {
10699                                p.info.authority = names[j];
10700                            } else {
10701                                p.info.authority = p.info.authority + ";" + names[j];
10702                            }
10703                            if (DEBUG_PACKAGE_SCANNING) {
10704                                if (chatty)
10705                                    Log.d(TAG, "Registered content provider: " + names[j]
10706                                            + ", className = " + p.info.name + ", isSyncable = "
10707                                            + p.info.isSyncable);
10708                            }
10709                        } else {
10710                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10711                            Slog.w(TAG, "Skipping provider name " + names[j] +
10712                                    " (in package " + pkg.applicationInfo.packageName +
10713                                    "): name already used by "
10714                                    + ((other != null && other.getComponentName() != null)
10715                                            ? other.getComponentName().getPackageName() : "?"));
10716                        }
10717                    }
10718                }
10719                if (chatty) {
10720                    if (r == null) {
10721                        r = new StringBuilder(256);
10722                    } else {
10723                        r.append(' ');
10724                    }
10725                    r.append(p.info.name);
10726                }
10727            }
10728            if (r != null) {
10729                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10730            }
10731
10732            N = pkg.services.size();
10733            r = null;
10734            for (i=0; i<N; i++) {
10735                PackageParser.Service s = pkg.services.get(i);
10736                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10737                        s.info.processName);
10738                mServices.addService(s);
10739                if (chatty) {
10740                    if (r == null) {
10741                        r = new StringBuilder(256);
10742                    } else {
10743                        r.append(' ');
10744                    }
10745                    r.append(s.info.name);
10746                }
10747            }
10748            if (r != null) {
10749                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10750            }
10751
10752            N = pkg.receivers.size();
10753            r = null;
10754            for (i=0; i<N; i++) {
10755                PackageParser.Activity a = pkg.receivers.get(i);
10756                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10757                        a.info.processName);
10758                mReceivers.addActivity(a, "receiver");
10759                if (chatty) {
10760                    if (r == null) {
10761                        r = new StringBuilder(256);
10762                    } else {
10763                        r.append(' ');
10764                    }
10765                    r.append(a.info.name);
10766                }
10767            }
10768            if (r != null) {
10769                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10770            }
10771
10772            N = pkg.activities.size();
10773            r = null;
10774            for (i=0; i<N; i++) {
10775                PackageParser.Activity a = pkg.activities.get(i);
10776                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10777                        a.info.processName);
10778                mActivities.addActivity(a, "activity");
10779                if (chatty) {
10780                    if (r == null) {
10781                        r = new StringBuilder(256);
10782                    } else {
10783                        r.append(' ');
10784                    }
10785                    r.append(a.info.name);
10786                }
10787            }
10788            if (r != null) {
10789                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10790            }
10791
10792            // Don't allow ephemeral applications to define new permissions groups.
10793            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10794                Slog.w(TAG, "Permission groups from package " + pkg.packageName
10795                        + " ignored: instant apps cannot define new permission groups.");
10796            } else {
10797                mPermissionManager.addAllPermissionGroups(pkg, chatty);
10798            }
10799
10800            // Don't allow ephemeral applications to define new permissions.
10801            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10802                Slog.w(TAG, "Permissions from package " + pkg.packageName
10803                        + " ignored: instant apps cannot define new permissions.");
10804            } else {
10805                mPermissionManager.addAllPermissions(pkg, chatty);
10806            }
10807
10808            N = pkg.instrumentation.size();
10809            r = null;
10810            for (i=0; i<N; i++) {
10811                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10812                a.info.packageName = pkg.applicationInfo.packageName;
10813                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10814                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10815                a.info.splitNames = pkg.splitNames;
10816                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10817                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10818                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10819                a.info.dataDir = pkg.applicationInfo.dataDir;
10820                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10821                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10822                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10823                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10824                mInstrumentation.put(a.getComponentName(), a);
10825                if (chatty) {
10826                    if (r == null) {
10827                        r = new StringBuilder(256);
10828                    } else {
10829                        r.append(' ');
10830                    }
10831                    r.append(a.info.name);
10832                }
10833            }
10834            if (r != null) {
10835                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10836            }
10837
10838            if (pkg.protectedBroadcasts != null) {
10839                N = pkg.protectedBroadcasts.size();
10840                synchronized (mProtectedBroadcasts) {
10841                    for (i = 0; i < N; i++) {
10842                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10843                    }
10844                }
10845            }
10846        }
10847
10848        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10849    }
10850
10851    /**
10852     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10853     * is derived purely on the basis of the contents of {@code scanFile} and
10854     * {@code cpuAbiOverride}.
10855     *
10856     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10857     */
10858    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10859                                 String cpuAbiOverride, boolean extractLibs,
10860                                 File appLib32InstallDir)
10861            throws PackageManagerException {
10862        // Give ourselves some initial paths; we'll come back for another
10863        // pass once we've determined ABI below.
10864        setNativeLibraryPaths(pkg, appLib32InstallDir);
10865
10866        // We would never need to extract libs for forward-locked and external packages,
10867        // since the container service will do it for us. We shouldn't attempt to
10868        // extract libs from system app when it was not updated.
10869        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10870                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10871            extractLibs = false;
10872        }
10873
10874        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10875        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10876
10877        NativeLibraryHelper.Handle handle = null;
10878        try {
10879            handle = NativeLibraryHelper.Handle.create(pkg);
10880            // TODO(multiArch): This can be null for apps that didn't go through the
10881            // usual installation process. We can calculate it again, like we
10882            // do during install time.
10883            //
10884            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10885            // unnecessary.
10886            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10887
10888            // Null out the abis so that they can be recalculated.
10889            pkg.applicationInfo.primaryCpuAbi = null;
10890            pkg.applicationInfo.secondaryCpuAbi = null;
10891            if (isMultiArch(pkg.applicationInfo)) {
10892                // Warn if we've set an abiOverride for multi-lib packages..
10893                // By definition, we need to copy both 32 and 64 bit libraries for
10894                // such packages.
10895                if (pkg.cpuAbiOverride != null
10896                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10897                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10898                }
10899
10900                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10901                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10902                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10903                    if (extractLibs) {
10904                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10905                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10906                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10907                                useIsaSpecificSubdirs);
10908                    } else {
10909                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10910                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10911                    }
10912                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10913                }
10914
10915                // Shared library native code should be in the APK zip aligned
10916                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
10917                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10918                            "Shared library native lib extraction not supported");
10919                }
10920
10921                maybeThrowExceptionForMultiArchCopy(
10922                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10923
10924                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10925                    if (extractLibs) {
10926                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10927                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10928                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10929                                useIsaSpecificSubdirs);
10930                    } else {
10931                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10932                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10933                    }
10934                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10935                }
10936
10937                maybeThrowExceptionForMultiArchCopy(
10938                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10939
10940                if (abi64 >= 0) {
10941                    // Shared library native libs should be in the APK zip aligned
10942                    if (extractLibs && pkg.isLibrary()) {
10943                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10944                                "Shared library native lib extraction not supported");
10945                    }
10946                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10947                }
10948
10949                if (abi32 >= 0) {
10950                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10951                    if (abi64 >= 0) {
10952                        if (pkg.use32bitAbi) {
10953                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10954                            pkg.applicationInfo.primaryCpuAbi = abi;
10955                        } else {
10956                            pkg.applicationInfo.secondaryCpuAbi = abi;
10957                        }
10958                    } else {
10959                        pkg.applicationInfo.primaryCpuAbi = abi;
10960                    }
10961                }
10962            } else {
10963                String[] abiList = (cpuAbiOverride != null) ?
10964                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10965
10966                // Enable gross and lame hacks for apps that are built with old
10967                // SDK tools. We must scan their APKs for renderscript bitcode and
10968                // not launch them if it's present. Don't bother checking on devices
10969                // that don't have 64 bit support.
10970                boolean needsRenderScriptOverride = false;
10971                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10972                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10973                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10974                    needsRenderScriptOverride = true;
10975                }
10976
10977                final int copyRet;
10978                if (extractLibs) {
10979                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10980                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10981                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10982                } else {
10983                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10984                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10985                }
10986                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10987
10988                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10989                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10990                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10991                }
10992
10993                if (copyRet >= 0) {
10994                    // Shared libraries that have native libs must be multi-architecture
10995                    if (pkg.isLibrary()) {
10996                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10997                                "Shared library with native libs must be multiarch");
10998                    }
10999                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11000                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11001                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11002                } else if (needsRenderScriptOverride) {
11003                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11004                }
11005            }
11006        } catch (IOException ioe) {
11007            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11008        } finally {
11009            IoUtils.closeQuietly(handle);
11010        }
11011
11012        // Now that we've calculated the ABIs and determined if it's an internal app,
11013        // we will go ahead and populate the nativeLibraryPath.
11014        setNativeLibraryPaths(pkg, appLib32InstallDir);
11015    }
11016
11017    /**
11018     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11019     * i.e, so that all packages can be run inside a single process if required.
11020     *
11021     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11022     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11023     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11024     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11025     * updating a package that belongs to a shared user.
11026     *
11027     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11028     * adds unnecessary complexity.
11029     */
11030    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11031            PackageParser.Package scannedPackage) {
11032        String requiredInstructionSet = null;
11033        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11034            requiredInstructionSet = VMRuntime.getInstructionSet(
11035                     scannedPackage.applicationInfo.primaryCpuAbi);
11036        }
11037
11038        PackageSetting requirer = null;
11039        for (PackageSetting ps : packagesForUser) {
11040            // If packagesForUser contains scannedPackage, we skip it. This will happen
11041            // when scannedPackage is an update of an existing package. Without this check,
11042            // we will never be able to change the ABI of any package belonging to a shared
11043            // user, even if it's compatible with other packages.
11044            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11045                if (ps.primaryCpuAbiString == null) {
11046                    continue;
11047                }
11048
11049                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11050                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11051                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11052                    // this but there's not much we can do.
11053                    String errorMessage = "Instruction set mismatch, "
11054                            + ((requirer == null) ? "[caller]" : requirer)
11055                            + " requires " + requiredInstructionSet + " whereas " + ps
11056                            + " requires " + instructionSet;
11057                    Slog.w(TAG, errorMessage);
11058                }
11059
11060                if (requiredInstructionSet == null) {
11061                    requiredInstructionSet = instructionSet;
11062                    requirer = ps;
11063                }
11064            }
11065        }
11066
11067        if (requiredInstructionSet != null) {
11068            String adjustedAbi;
11069            if (requirer != null) {
11070                // requirer != null implies that either scannedPackage was null or that scannedPackage
11071                // did not require an ABI, in which case we have to adjust scannedPackage to match
11072                // the ABI of the set (which is the same as requirer's ABI)
11073                adjustedAbi = requirer.primaryCpuAbiString;
11074                if (scannedPackage != null) {
11075                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11076                }
11077            } else {
11078                // requirer == null implies that we're updating all ABIs in the set to
11079                // match scannedPackage.
11080                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11081            }
11082
11083            for (PackageSetting ps : packagesForUser) {
11084                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11085                    if (ps.primaryCpuAbiString != null) {
11086                        continue;
11087                    }
11088
11089                    ps.primaryCpuAbiString = adjustedAbi;
11090                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11091                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11092                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11093                        if (DEBUG_ABI_SELECTION) {
11094                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11095                                    + " (requirer="
11096                                    + (requirer != null ? requirer.pkg : "null")
11097                                    + ", scannedPackage="
11098                                    + (scannedPackage != null ? scannedPackage : "null")
11099                                    + ")");
11100                        }
11101                        try {
11102                            mInstaller.rmdex(ps.codePathString,
11103                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11104                        } catch (InstallerException ignored) {
11105                        }
11106                    }
11107                }
11108            }
11109        }
11110    }
11111
11112    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11113        synchronized (mPackages) {
11114            mResolverReplaced = true;
11115            // Set up information for custom user intent resolution activity.
11116            mResolveActivity.applicationInfo = pkg.applicationInfo;
11117            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11118            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11119            mResolveActivity.processName = pkg.applicationInfo.packageName;
11120            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11121            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11122                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11123            mResolveActivity.theme = 0;
11124            mResolveActivity.exported = true;
11125            mResolveActivity.enabled = true;
11126            mResolveInfo.activityInfo = mResolveActivity;
11127            mResolveInfo.priority = 0;
11128            mResolveInfo.preferredOrder = 0;
11129            mResolveInfo.match = 0;
11130            mResolveComponentName = mCustomResolverComponentName;
11131            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11132                    mResolveComponentName);
11133        }
11134    }
11135
11136    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11137        if (installerActivity == null) {
11138            if (DEBUG_EPHEMERAL) {
11139                Slog.d(TAG, "Clear ephemeral installer activity");
11140            }
11141            mInstantAppInstallerActivity = null;
11142            return;
11143        }
11144
11145        if (DEBUG_EPHEMERAL) {
11146            Slog.d(TAG, "Set ephemeral installer activity: "
11147                    + installerActivity.getComponentName());
11148        }
11149        // Set up information for ephemeral installer activity
11150        mInstantAppInstallerActivity = installerActivity;
11151        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11152                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11153        mInstantAppInstallerActivity.exported = true;
11154        mInstantAppInstallerActivity.enabled = true;
11155        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11156        mInstantAppInstallerInfo.priority = 0;
11157        mInstantAppInstallerInfo.preferredOrder = 1;
11158        mInstantAppInstallerInfo.isDefault = true;
11159        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11160                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11161    }
11162
11163    private static String calculateBundledApkRoot(final String codePathString) {
11164        final File codePath = new File(codePathString);
11165        final File codeRoot;
11166        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11167            codeRoot = Environment.getRootDirectory();
11168        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11169            codeRoot = Environment.getOemDirectory();
11170        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11171            codeRoot = Environment.getVendorDirectory();
11172        } else {
11173            // Unrecognized code path; take its top real segment as the apk root:
11174            // e.g. /something/app/blah.apk => /something
11175            try {
11176                File f = codePath.getCanonicalFile();
11177                File parent = f.getParentFile();    // non-null because codePath is a file
11178                File tmp;
11179                while ((tmp = parent.getParentFile()) != null) {
11180                    f = parent;
11181                    parent = tmp;
11182                }
11183                codeRoot = f;
11184                Slog.w(TAG, "Unrecognized code path "
11185                        + codePath + " - using " + codeRoot);
11186            } catch (IOException e) {
11187                // Can't canonicalize the code path -- shenanigans?
11188                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11189                return Environment.getRootDirectory().getPath();
11190            }
11191        }
11192        return codeRoot.getPath();
11193    }
11194
11195    /**
11196     * Derive and set the location of native libraries for the given package,
11197     * which varies depending on where and how the package was installed.
11198     */
11199    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11200        final ApplicationInfo info = pkg.applicationInfo;
11201        final String codePath = pkg.codePath;
11202        final File codeFile = new File(codePath);
11203        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11204        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11205
11206        info.nativeLibraryRootDir = null;
11207        info.nativeLibraryRootRequiresIsa = false;
11208        info.nativeLibraryDir = null;
11209        info.secondaryNativeLibraryDir = null;
11210
11211        if (isApkFile(codeFile)) {
11212            // Monolithic install
11213            if (bundledApp) {
11214                // If "/system/lib64/apkname" exists, assume that is the per-package
11215                // native library directory to use; otherwise use "/system/lib/apkname".
11216                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11217                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11218                        getPrimaryInstructionSet(info));
11219
11220                // This is a bundled system app so choose the path based on the ABI.
11221                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11222                // is just the default path.
11223                final String apkName = deriveCodePathName(codePath);
11224                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11225                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11226                        apkName).getAbsolutePath();
11227
11228                if (info.secondaryCpuAbi != null) {
11229                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11230                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11231                            secondaryLibDir, apkName).getAbsolutePath();
11232                }
11233            } else if (asecApp) {
11234                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11235                        .getAbsolutePath();
11236            } else {
11237                final String apkName = deriveCodePathName(codePath);
11238                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11239                        .getAbsolutePath();
11240            }
11241
11242            info.nativeLibraryRootRequiresIsa = false;
11243            info.nativeLibraryDir = info.nativeLibraryRootDir;
11244        } else {
11245            // Cluster install
11246            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11247            info.nativeLibraryRootRequiresIsa = true;
11248
11249            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11250                    getPrimaryInstructionSet(info)).getAbsolutePath();
11251
11252            if (info.secondaryCpuAbi != null) {
11253                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11254                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11255            }
11256        }
11257    }
11258
11259    /**
11260     * Calculate the abis and roots for a bundled app. These can uniquely
11261     * be determined from the contents of the system partition, i.e whether
11262     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11263     * of this information, and instead assume that the system was built
11264     * sensibly.
11265     */
11266    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11267                                           PackageSetting pkgSetting) {
11268        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11269
11270        // If "/system/lib64/apkname" exists, assume that is the per-package
11271        // native library directory to use; otherwise use "/system/lib/apkname".
11272        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11273        setBundledAppAbi(pkg, apkRoot, apkName);
11274        // pkgSetting might be null during rescan following uninstall of updates
11275        // to a bundled app, so accommodate that possibility.  The settings in
11276        // that case will be established later from the parsed package.
11277        //
11278        // If the settings aren't null, sync them up with what we've just derived.
11279        // note that apkRoot isn't stored in the package settings.
11280        if (pkgSetting != null) {
11281            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11282            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11283        }
11284    }
11285
11286    /**
11287     * Deduces the ABI of a bundled app and sets the relevant fields on the
11288     * parsed pkg object.
11289     *
11290     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11291     *        under which system libraries are installed.
11292     * @param apkName the name of the installed package.
11293     */
11294    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11295        final File codeFile = new File(pkg.codePath);
11296
11297        final boolean has64BitLibs;
11298        final boolean has32BitLibs;
11299        if (isApkFile(codeFile)) {
11300            // Monolithic install
11301            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11302            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11303        } else {
11304            // Cluster install
11305            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11306            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11307                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11308                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11309                has64BitLibs = (new File(rootDir, isa)).exists();
11310            } else {
11311                has64BitLibs = false;
11312            }
11313            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11314                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11315                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11316                has32BitLibs = (new File(rootDir, isa)).exists();
11317            } else {
11318                has32BitLibs = false;
11319            }
11320        }
11321
11322        if (has64BitLibs && !has32BitLibs) {
11323            // The package has 64 bit libs, but not 32 bit libs. Its primary
11324            // ABI should be 64 bit. We can safely assume here that the bundled
11325            // native libraries correspond to the most preferred ABI in the list.
11326
11327            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11328            pkg.applicationInfo.secondaryCpuAbi = null;
11329        } else if (has32BitLibs && !has64BitLibs) {
11330            // The package has 32 bit libs but not 64 bit libs. Its primary
11331            // ABI should be 32 bit.
11332
11333            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11334            pkg.applicationInfo.secondaryCpuAbi = null;
11335        } else if (has32BitLibs && has64BitLibs) {
11336            // The application has both 64 and 32 bit bundled libraries. We check
11337            // here that the app declares multiArch support, and warn if it doesn't.
11338            //
11339            // We will be lenient here and record both ABIs. The primary will be the
11340            // ABI that's higher on the list, i.e, a device that's configured to prefer
11341            // 64 bit apps will see a 64 bit primary ABI,
11342
11343            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11344                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11345            }
11346
11347            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11348                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11349                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11350            } else {
11351                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11352                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11353            }
11354        } else {
11355            pkg.applicationInfo.primaryCpuAbi = null;
11356            pkg.applicationInfo.secondaryCpuAbi = null;
11357        }
11358    }
11359
11360    private void killApplication(String pkgName, int appId, String reason) {
11361        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11362    }
11363
11364    private void killApplication(String pkgName, int appId, int userId, String reason) {
11365        // Request the ActivityManager to kill the process(only for existing packages)
11366        // so that we do not end up in a confused state while the user is still using the older
11367        // version of the application while the new one gets installed.
11368        final long token = Binder.clearCallingIdentity();
11369        try {
11370            IActivityManager am = ActivityManager.getService();
11371            if (am != null) {
11372                try {
11373                    am.killApplication(pkgName, appId, userId, reason);
11374                } catch (RemoteException e) {
11375                }
11376            }
11377        } finally {
11378            Binder.restoreCallingIdentity(token);
11379        }
11380    }
11381
11382    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11383        // Remove the parent package setting
11384        PackageSetting ps = (PackageSetting) pkg.mExtras;
11385        if (ps != null) {
11386            removePackageLI(ps, chatty);
11387        }
11388        // Remove the child package setting
11389        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11390        for (int i = 0; i < childCount; i++) {
11391            PackageParser.Package childPkg = pkg.childPackages.get(i);
11392            ps = (PackageSetting) childPkg.mExtras;
11393            if (ps != null) {
11394                removePackageLI(ps, chatty);
11395            }
11396        }
11397    }
11398
11399    void removePackageLI(PackageSetting ps, boolean chatty) {
11400        if (DEBUG_INSTALL) {
11401            if (chatty)
11402                Log.d(TAG, "Removing package " + ps.name);
11403        }
11404
11405        // writer
11406        synchronized (mPackages) {
11407            mPackages.remove(ps.name);
11408            final PackageParser.Package pkg = ps.pkg;
11409            if (pkg != null) {
11410                cleanPackageDataStructuresLILPw(pkg, chatty);
11411            }
11412        }
11413    }
11414
11415    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11416        if (DEBUG_INSTALL) {
11417            if (chatty)
11418                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11419        }
11420
11421        // writer
11422        synchronized (mPackages) {
11423            // Remove the parent package
11424            mPackages.remove(pkg.applicationInfo.packageName);
11425            cleanPackageDataStructuresLILPw(pkg, chatty);
11426
11427            // Remove the child packages
11428            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11429            for (int i = 0; i < childCount; i++) {
11430                PackageParser.Package childPkg = pkg.childPackages.get(i);
11431                mPackages.remove(childPkg.applicationInfo.packageName);
11432                cleanPackageDataStructuresLILPw(childPkg, chatty);
11433            }
11434        }
11435    }
11436
11437    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11438        int N = pkg.providers.size();
11439        StringBuilder r = null;
11440        int i;
11441        for (i=0; i<N; i++) {
11442            PackageParser.Provider p = pkg.providers.get(i);
11443            mProviders.removeProvider(p);
11444            if (p.info.authority == null) {
11445
11446                /* There was another ContentProvider with this authority when
11447                 * this app was installed so this authority is null,
11448                 * Ignore it as we don't have to unregister the provider.
11449                 */
11450                continue;
11451            }
11452            String names[] = p.info.authority.split(";");
11453            for (int j = 0; j < names.length; j++) {
11454                if (mProvidersByAuthority.get(names[j]) == p) {
11455                    mProvidersByAuthority.remove(names[j]);
11456                    if (DEBUG_REMOVE) {
11457                        if (chatty)
11458                            Log.d(TAG, "Unregistered content provider: " + names[j]
11459                                    + ", className = " + p.info.name + ", isSyncable = "
11460                                    + p.info.isSyncable);
11461                    }
11462                }
11463            }
11464            if (DEBUG_REMOVE && chatty) {
11465                if (r == null) {
11466                    r = new StringBuilder(256);
11467                } else {
11468                    r.append(' ');
11469                }
11470                r.append(p.info.name);
11471            }
11472        }
11473        if (r != null) {
11474            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11475        }
11476
11477        N = pkg.services.size();
11478        r = null;
11479        for (i=0; i<N; i++) {
11480            PackageParser.Service s = pkg.services.get(i);
11481            mServices.removeService(s);
11482            if (chatty) {
11483                if (r == null) {
11484                    r = new StringBuilder(256);
11485                } else {
11486                    r.append(' ');
11487                }
11488                r.append(s.info.name);
11489            }
11490        }
11491        if (r != null) {
11492            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11493        }
11494
11495        N = pkg.receivers.size();
11496        r = null;
11497        for (i=0; i<N; i++) {
11498            PackageParser.Activity a = pkg.receivers.get(i);
11499            mReceivers.removeActivity(a, "receiver");
11500            if (DEBUG_REMOVE && chatty) {
11501                if (r == null) {
11502                    r = new StringBuilder(256);
11503                } else {
11504                    r.append(' ');
11505                }
11506                r.append(a.info.name);
11507            }
11508        }
11509        if (r != null) {
11510            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11511        }
11512
11513        N = pkg.activities.size();
11514        r = null;
11515        for (i=0; i<N; i++) {
11516            PackageParser.Activity a = pkg.activities.get(i);
11517            mActivities.removeActivity(a, "activity");
11518            if (DEBUG_REMOVE && chatty) {
11519                if (r == null) {
11520                    r = new StringBuilder(256);
11521                } else {
11522                    r.append(' ');
11523                }
11524                r.append(a.info.name);
11525            }
11526        }
11527        if (r != null) {
11528            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11529        }
11530
11531        mPermissionManager.removeAllPermissions(pkg, chatty);
11532
11533        N = pkg.instrumentation.size();
11534        r = null;
11535        for (i=0; i<N; i++) {
11536            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11537            mInstrumentation.remove(a.getComponentName());
11538            if (DEBUG_REMOVE && chatty) {
11539                if (r == null) {
11540                    r = new StringBuilder(256);
11541                } else {
11542                    r.append(' ');
11543                }
11544                r.append(a.info.name);
11545            }
11546        }
11547        if (r != null) {
11548            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11549        }
11550
11551        r = null;
11552        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11553            // Only system apps can hold shared libraries.
11554            if (pkg.libraryNames != null) {
11555                for (i = 0; i < pkg.libraryNames.size(); i++) {
11556                    String name = pkg.libraryNames.get(i);
11557                    if (removeSharedLibraryLPw(name, 0)) {
11558                        if (DEBUG_REMOVE && chatty) {
11559                            if (r == null) {
11560                                r = new StringBuilder(256);
11561                            } else {
11562                                r.append(' ');
11563                            }
11564                            r.append(name);
11565                        }
11566                    }
11567                }
11568            }
11569        }
11570
11571        r = null;
11572
11573        // Any package can hold static shared libraries.
11574        if (pkg.staticSharedLibName != null) {
11575            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11576                if (DEBUG_REMOVE && chatty) {
11577                    if (r == null) {
11578                        r = new StringBuilder(256);
11579                    } else {
11580                        r.append(' ');
11581                    }
11582                    r.append(pkg.staticSharedLibName);
11583                }
11584            }
11585        }
11586
11587        if (r != null) {
11588            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11589        }
11590    }
11591
11592
11593    final class ActivityIntentResolver
11594            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11595        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11596                boolean defaultOnly, int userId) {
11597            if (!sUserManager.exists(userId)) return null;
11598            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11599            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11600        }
11601
11602        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11603                int userId) {
11604            if (!sUserManager.exists(userId)) return null;
11605            mFlags = flags;
11606            return super.queryIntent(intent, resolvedType,
11607                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11608                    userId);
11609        }
11610
11611        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11612                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11613            if (!sUserManager.exists(userId)) return null;
11614            if (packageActivities == null) {
11615                return null;
11616            }
11617            mFlags = flags;
11618            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11619            final int N = packageActivities.size();
11620            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11621                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11622
11623            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11624            for (int i = 0; i < N; ++i) {
11625                intentFilters = packageActivities.get(i).intents;
11626                if (intentFilters != null && intentFilters.size() > 0) {
11627                    PackageParser.ActivityIntentInfo[] array =
11628                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11629                    intentFilters.toArray(array);
11630                    listCut.add(array);
11631                }
11632            }
11633            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11634        }
11635
11636        /**
11637         * Finds a privileged activity that matches the specified activity names.
11638         */
11639        private PackageParser.Activity findMatchingActivity(
11640                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11641            for (PackageParser.Activity sysActivity : activityList) {
11642                if (sysActivity.info.name.equals(activityInfo.name)) {
11643                    return sysActivity;
11644                }
11645                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11646                    return sysActivity;
11647                }
11648                if (sysActivity.info.targetActivity != null) {
11649                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11650                        return sysActivity;
11651                    }
11652                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11653                        return sysActivity;
11654                    }
11655                }
11656            }
11657            return null;
11658        }
11659
11660        public class IterGenerator<E> {
11661            public Iterator<E> generate(ActivityIntentInfo info) {
11662                return null;
11663            }
11664        }
11665
11666        public class ActionIterGenerator extends IterGenerator<String> {
11667            @Override
11668            public Iterator<String> generate(ActivityIntentInfo info) {
11669                return info.actionsIterator();
11670            }
11671        }
11672
11673        public class CategoriesIterGenerator extends IterGenerator<String> {
11674            @Override
11675            public Iterator<String> generate(ActivityIntentInfo info) {
11676                return info.categoriesIterator();
11677            }
11678        }
11679
11680        public class SchemesIterGenerator extends IterGenerator<String> {
11681            @Override
11682            public Iterator<String> generate(ActivityIntentInfo info) {
11683                return info.schemesIterator();
11684            }
11685        }
11686
11687        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11688            @Override
11689            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11690                return info.authoritiesIterator();
11691            }
11692        }
11693
11694        /**
11695         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11696         * MODIFIED. Do not pass in a list that should not be changed.
11697         */
11698        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11699                IterGenerator<T> generator, Iterator<T> searchIterator) {
11700            // loop through the set of actions; every one must be found in the intent filter
11701            while (searchIterator.hasNext()) {
11702                // we must have at least one filter in the list to consider a match
11703                if (intentList.size() == 0) {
11704                    break;
11705                }
11706
11707                final T searchAction = searchIterator.next();
11708
11709                // loop through the set of intent filters
11710                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11711                while (intentIter.hasNext()) {
11712                    final ActivityIntentInfo intentInfo = intentIter.next();
11713                    boolean selectionFound = false;
11714
11715                    // loop through the intent filter's selection criteria; at least one
11716                    // of them must match the searched criteria
11717                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11718                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11719                        final T intentSelection = intentSelectionIter.next();
11720                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11721                            selectionFound = true;
11722                            break;
11723                        }
11724                    }
11725
11726                    // the selection criteria wasn't found in this filter's set; this filter
11727                    // is not a potential match
11728                    if (!selectionFound) {
11729                        intentIter.remove();
11730                    }
11731                }
11732            }
11733        }
11734
11735        private boolean isProtectedAction(ActivityIntentInfo filter) {
11736            final Iterator<String> actionsIter = filter.actionsIterator();
11737            while (actionsIter != null && actionsIter.hasNext()) {
11738                final String filterAction = actionsIter.next();
11739                if (PROTECTED_ACTIONS.contains(filterAction)) {
11740                    return true;
11741                }
11742            }
11743            return false;
11744        }
11745
11746        /**
11747         * Adjusts the priority of the given intent filter according to policy.
11748         * <p>
11749         * <ul>
11750         * <li>The priority for non privileged applications is capped to '0'</li>
11751         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11752         * <li>The priority for unbundled updates to privileged applications is capped to the
11753         *      priority defined on the system partition</li>
11754         * </ul>
11755         * <p>
11756         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11757         * allowed to obtain any priority on any action.
11758         */
11759        private void adjustPriority(
11760                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11761            // nothing to do; priority is fine as-is
11762            if (intent.getPriority() <= 0) {
11763                return;
11764            }
11765
11766            final ActivityInfo activityInfo = intent.activity.info;
11767            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11768
11769            final boolean privilegedApp =
11770                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11771            if (!privilegedApp) {
11772                // non-privileged applications can never define a priority >0
11773                if (DEBUG_FILTERS) {
11774                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
11775                            + " package: " + applicationInfo.packageName
11776                            + " activity: " + intent.activity.className
11777                            + " origPrio: " + intent.getPriority());
11778                }
11779                intent.setPriority(0);
11780                return;
11781            }
11782
11783            if (systemActivities == null) {
11784                // the system package is not disabled; we're parsing the system partition
11785                if (isProtectedAction(intent)) {
11786                    if (mDeferProtectedFilters) {
11787                        // We can't deal with these just yet. No component should ever obtain a
11788                        // >0 priority for a protected actions, with ONE exception -- the setup
11789                        // wizard. The setup wizard, however, cannot be known until we're able to
11790                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11791                        // until all intent filters have been processed. Chicken, meet egg.
11792                        // Let the filter temporarily have a high priority and rectify the
11793                        // priorities after all system packages have been scanned.
11794                        mProtectedFilters.add(intent);
11795                        if (DEBUG_FILTERS) {
11796                            Slog.i(TAG, "Protected action; save for later;"
11797                                    + " package: " + applicationInfo.packageName
11798                                    + " activity: " + intent.activity.className
11799                                    + " origPrio: " + intent.getPriority());
11800                        }
11801                        return;
11802                    } else {
11803                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11804                            Slog.i(TAG, "No setup wizard;"
11805                                + " All protected intents capped to priority 0");
11806                        }
11807                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11808                            if (DEBUG_FILTERS) {
11809                                Slog.i(TAG, "Found setup wizard;"
11810                                    + " allow priority " + intent.getPriority() + ";"
11811                                    + " package: " + intent.activity.info.packageName
11812                                    + " activity: " + intent.activity.className
11813                                    + " priority: " + intent.getPriority());
11814                            }
11815                            // setup wizard gets whatever it wants
11816                            return;
11817                        }
11818                        if (DEBUG_FILTERS) {
11819                            Slog.i(TAG, "Protected action; cap priority to 0;"
11820                                    + " package: " + intent.activity.info.packageName
11821                                    + " activity: " + intent.activity.className
11822                                    + " origPrio: " + intent.getPriority());
11823                        }
11824                        intent.setPriority(0);
11825                        return;
11826                    }
11827                }
11828                // privileged apps on the system image get whatever priority they request
11829                return;
11830            }
11831
11832            // privileged app unbundled update ... try to find the same activity
11833            final PackageParser.Activity foundActivity =
11834                    findMatchingActivity(systemActivities, activityInfo);
11835            if (foundActivity == null) {
11836                // this is a new activity; it cannot obtain >0 priority
11837                if (DEBUG_FILTERS) {
11838                    Slog.i(TAG, "New activity; cap priority to 0;"
11839                            + " package: " + applicationInfo.packageName
11840                            + " activity: " + intent.activity.className
11841                            + " origPrio: " + intent.getPriority());
11842                }
11843                intent.setPriority(0);
11844                return;
11845            }
11846
11847            // found activity, now check for filter equivalence
11848
11849            // a shallow copy is enough; we modify the list, not its contents
11850            final List<ActivityIntentInfo> intentListCopy =
11851                    new ArrayList<>(foundActivity.intents);
11852            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11853
11854            // find matching action subsets
11855            final Iterator<String> actionsIterator = intent.actionsIterator();
11856            if (actionsIterator != null) {
11857                getIntentListSubset(
11858                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11859                if (intentListCopy.size() == 0) {
11860                    // no more intents to match; we're not equivalent
11861                    if (DEBUG_FILTERS) {
11862                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11863                                + " package: " + applicationInfo.packageName
11864                                + " activity: " + intent.activity.className
11865                                + " origPrio: " + intent.getPriority());
11866                    }
11867                    intent.setPriority(0);
11868                    return;
11869                }
11870            }
11871
11872            // find matching category subsets
11873            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11874            if (categoriesIterator != null) {
11875                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11876                        categoriesIterator);
11877                if (intentListCopy.size() == 0) {
11878                    // no more intents to match; we're not equivalent
11879                    if (DEBUG_FILTERS) {
11880                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11881                                + " package: " + applicationInfo.packageName
11882                                + " activity: " + intent.activity.className
11883                                + " origPrio: " + intent.getPriority());
11884                    }
11885                    intent.setPriority(0);
11886                    return;
11887                }
11888            }
11889
11890            // find matching schemes subsets
11891            final Iterator<String> schemesIterator = intent.schemesIterator();
11892            if (schemesIterator != null) {
11893                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11894                        schemesIterator);
11895                if (intentListCopy.size() == 0) {
11896                    // no more intents to match; we're not equivalent
11897                    if (DEBUG_FILTERS) {
11898                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11899                                + " package: " + applicationInfo.packageName
11900                                + " activity: " + intent.activity.className
11901                                + " origPrio: " + intent.getPriority());
11902                    }
11903                    intent.setPriority(0);
11904                    return;
11905                }
11906            }
11907
11908            // find matching authorities subsets
11909            final Iterator<IntentFilter.AuthorityEntry>
11910                    authoritiesIterator = intent.authoritiesIterator();
11911            if (authoritiesIterator != null) {
11912                getIntentListSubset(intentListCopy,
11913                        new AuthoritiesIterGenerator(),
11914                        authoritiesIterator);
11915                if (intentListCopy.size() == 0) {
11916                    // no more intents to match; we're not equivalent
11917                    if (DEBUG_FILTERS) {
11918                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11919                                + " package: " + applicationInfo.packageName
11920                                + " activity: " + intent.activity.className
11921                                + " origPrio: " + intent.getPriority());
11922                    }
11923                    intent.setPriority(0);
11924                    return;
11925                }
11926            }
11927
11928            // we found matching filter(s); app gets the max priority of all intents
11929            int cappedPriority = 0;
11930            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11931                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11932            }
11933            if (intent.getPriority() > cappedPriority) {
11934                if (DEBUG_FILTERS) {
11935                    Slog.i(TAG, "Found matching filter(s);"
11936                            + " cap priority to " + cappedPriority + ";"
11937                            + " package: " + applicationInfo.packageName
11938                            + " activity: " + intent.activity.className
11939                            + " origPrio: " + intent.getPriority());
11940                }
11941                intent.setPriority(cappedPriority);
11942                return;
11943            }
11944            // all this for nothing; the requested priority was <= what was on the system
11945        }
11946
11947        public final void addActivity(PackageParser.Activity a, String type) {
11948            mActivities.put(a.getComponentName(), a);
11949            if (DEBUG_SHOW_INFO)
11950                Log.v(
11951                TAG, "  " + type + " " +
11952                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11953            if (DEBUG_SHOW_INFO)
11954                Log.v(TAG, "    Class=" + a.info.name);
11955            final int NI = a.intents.size();
11956            for (int j=0; j<NI; j++) {
11957                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11958                if ("activity".equals(type)) {
11959                    final PackageSetting ps =
11960                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11961                    final List<PackageParser.Activity> systemActivities =
11962                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11963                    adjustPriority(systemActivities, intent);
11964                }
11965                if (DEBUG_SHOW_INFO) {
11966                    Log.v(TAG, "    IntentFilter:");
11967                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11968                }
11969                if (!intent.debugCheck()) {
11970                    Log.w(TAG, "==> For Activity " + a.info.name);
11971                }
11972                addFilter(intent);
11973            }
11974        }
11975
11976        public final void removeActivity(PackageParser.Activity a, String type) {
11977            mActivities.remove(a.getComponentName());
11978            if (DEBUG_SHOW_INFO) {
11979                Log.v(TAG, "  " + type + " "
11980                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11981                                : a.info.name) + ":");
11982                Log.v(TAG, "    Class=" + a.info.name);
11983            }
11984            final int NI = a.intents.size();
11985            for (int j=0; j<NI; j++) {
11986                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11987                if (DEBUG_SHOW_INFO) {
11988                    Log.v(TAG, "    IntentFilter:");
11989                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11990                }
11991                removeFilter(intent);
11992            }
11993        }
11994
11995        @Override
11996        protected boolean allowFilterResult(
11997                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11998            ActivityInfo filterAi = filter.activity.info;
11999            for (int i=dest.size()-1; i>=0; i--) {
12000                ActivityInfo destAi = dest.get(i).activityInfo;
12001                if (destAi.name == filterAi.name
12002                        && destAi.packageName == filterAi.packageName) {
12003                    return false;
12004                }
12005            }
12006            return true;
12007        }
12008
12009        @Override
12010        protected ActivityIntentInfo[] newArray(int size) {
12011            return new ActivityIntentInfo[size];
12012        }
12013
12014        @Override
12015        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12016            if (!sUserManager.exists(userId)) return true;
12017            PackageParser.Package p = filter.activity.owner;
12018            if (p != null) {
12019                PackageSetting ps = (PackageSetting)p.mExtras;
12020                if (ps != null) {
12021                    // System apps are never considered stopped for purposes of
12022                    // filtering, because there may be no way for the user to
12023                    // actually re-launch them.
12024                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12025                            && ps.getStopped(userId);
12026                }
12027            }
12028            return false;
12029        }
12030
12031        @Override
12032        protected boolean isPackageForFilter(String packageName,
12033                PackageParser.ActivityIntentInfo info) {
12034            return packageName.equals(info.activity.owner.packageName);
12035        }
12036
12037        @Override
12038        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12039                int match, int userId) {
12040            if (!sUserManager.exists(userId)) return null;
12041            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12042                return null;
12043            }
12044            final PackageParser.Activity activity = info.activity;
12045            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12046            if (ps == null) {
12047                return null;
12048            }
12049            final PackageUserState userState = ps.readUserState(userId);
12050            ActivityInfo ai =
12051                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12052            if (ai == null) {
12053                return null;
12054            }
12055            final boolean matchExplicitlyVisibleOnly =
12056                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12057            final boolean matchVisibleToInstantApp =
12058                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12059            final boolean componentVisible =
12060                    matchVisibleToInstantApp
12061                    && info.isVisibleToInstantApp()
12062                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12063            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12064            // throw out filters that aren't visible to ephemeral apps
12065            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12066                return null;
12067            }
12068            // throw out instant app filters if we're not explicitly requesting them
12069            if (!matchInstantApp && userState.instantApp) {
12070                return null;
12071            }
12072            // throw out instant app filters if updates are available; will trigger
12073            // instant app resolution
12074            if (userState.instantApp && ps.isUpdateAvailable()) {
12075                return null;
12076            }
12077            final ResolveInfo res = new ResolveInfo();
12078            res.activityInfo = ai;
12079            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12080                res.filter = info;
12081            }
12082            if (info != null) {
12083                res.handleAllWebDataURI = info.handleAllWebDataURI();
12084            }
12085            res.priority = info.getPriority();
12086            res.preferredOrder = activity.owner.mPreferredOrder;
12087            //System.out.println("Result: " + res.activityInfo.className +
12088            //                   " = " + res.priority);
12089            res.match = match;
12090            res.isDefault = info.hasDefault;
12091            res.labelRes = info.labelRes;
12092            res.nonLocalizedLabel = info.nonLocalizedLabel;
12093            if (userNeedsBadging(userId)) {
12094                res.noResourceId = true;
12095            } else {
12096                res.icon = info.icon;
12097            }
12098            res.iconResourceId = info.icon;
12099            res.system = res.activityInfo.applicationInfo.isSystemApp();
12100            res.isInstantAppAvailable = userState.instantApp;
12101            return res;
12102        }
12103
12104        @Override
12105        protected void sortResults(List<ResolveInfo> results) {
12106            Collections.sort(results, mResolvePrioritySorter);
12107        }
12108
12109        @Override
12110        protected void dumpFilter(PrintWriter out, String prefix,
12111                PackageParser.ActivityIntentInfo filter) {
12112            out.print(prefix); out.print(
12113                    Integer.toHexString(System.identityHashCode(filter.activity)));
12114                    out.print(' ');
12115                    filter.activity.printComponentShortName(out);
12116                    out.print(" filter ");
12117                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12118        }
12119
12120        @Override
12121        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12122            return filter.activity;
12123        }
12124
12125        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12126            PackageParser.Activity activity = (PackageParser.Activity)label;
12127            out.print(prefix); out.print(
12128                    Integer.toHexString(System.identityHashCode(activity)));
12129                    out.print(' ');
12130                    activity.printComponentShortName(out);
12131            if (count > 1) {
12132                out.print(" ("); out.print(count); out.print(" filters)");
12133            }
12134            out.println();
12135        }
12136
12137        // Keys are String (activity class name), values are Activity.
12138        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12139                = new ArrayMap<ComponentName, PackageParser.Activity>();
12140        private int mFlags;
12141    }
12142
12143    private final class ServiceIntentResolver
12144            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12145        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12146                boolean defaultOnly, int userId) {
12147            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12148            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12149        }
12150
12151        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12152                int userId) {
12153            if (!sUserManager.exists(userId)) return null;
12154            mFlags = flags;
12155            return super.queryIntent(intent, resolvedType,
12156                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12157                    userId);
12158        }
12159
12160        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12161                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12162            if (!sUserManager.exists(userId)) return null;
12163            if (packageServices == null) {
12164                return null;
12165            }
12166            mFlags = flags;
12167            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12168            final int N = packageServices.size();
12169            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12170                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12171
12172            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12173            for (int i = 0; i < N; ++i) {
12174                intentFilters = packageServices.get(i).intents;
12175                if (intentFilters != null && intentFilters.size() > 0) {
12176                    PackageParser.ServiceIntentInfo[] array =
12177                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12178                    intentFilters.toArray(array);
12179                    listCut.add(array);
12180                }
12181            }
12182            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12183        }
12184
12185        public final void addService(PackageParser.Service s) {
12186            mServices.put(s.getComponentName(), s);
12187            if (DEBUG_SHOW_INFO) {
12188                Log.v(TAG, "  "
12189                        + (s.info.nonLocalizedLabel != null
12190                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12191                Log.v(TAG, "    Class=" + s.info.name);
12192            }
12193            final int NI = s.intents.size();
12194            int j;
12195            for (j=0; j<NI; j++) {
12196                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12197                if (DEBUG_SHOW_INFO) {
12198                    Log.v(TAG, "    IntentFilter:");
12199                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12200                }
12201                if (!intent.debugCheck()) {
12202                    Log.w(TAG, "==> For Service " + s.info.name);
12203                }
12204                addFilter(intent);
12205            }
12206        }
12207
12208        public final void removeService(PackageParser.Service s) {
12209            mServices.remove(s.getComponentName());
12210            if (DEBUG_SHOW_INFO) {
12211                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12212                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12213                Log.v(TAG, "    Class=" + s.info.name);
12214            }
12215            final int NI = s.intents.size();
12216            int j;
12217            for (j=0; j<NI; j++) {
12218                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12219                if (DEBUG_SHOW_INFO) {
12220                    Log.v(TAG, "    IntentFilter:");
12221                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12222                }
12223                removeFilter(intent);
12224            }
12225        }
12226
12227        @Override
12228        protected boolean allowFilterResult(
12229                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12230            ServiceInfo filterSi = filter.service.info;
12231            for (int i=dest.size()-1; i>=0; i--) {
12232                ServiceInfo destAi = dest.get(i).serviceInfo;
12233                if (destAi.name == filterSi.name
12234                        && destAi.packageName == filterSi.packageName) {
12235                    return false;
12236                }
12237            }
12238            return true;
12239        }
12240
12241        @Override
12242        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12243            return new PackageParser.ServiceIntentInfo[size];
12244        }
12245
12246        @Override
12247        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12248            if (!sUserManager.exists(userId)) return true;
12249            PackageParser.Package p = filter.service.owner;
12250            if (p != null) {
12251                PackageSetting ps = (PackageSetting)p.mExtras;
12252                if (ps != null) {
12253                    // System apps are never considered stopped for purposes of
12254                    // filtering, because there may be no way for the user to
12255                    // actually re-launch them.
12256                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12257                            && ps.getStopped(userId);
12258                }
12259            }
12260            return false;
12261        }
12262
12263        @Override
12264        protected boolean isPackageForFilter(String packageName,
12265                PackageParser.ServiceIntentInfo info) {
12266            return packageName.equals(info.service.owner.packageName);
12267        }
12268
12269        @Override
12270        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12271                int match, int userId) {
12272            if (!sUserManager.exists(userId)) return null;
12273            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12274            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12275                return null;
12276            }
12277            final PackageParser.Service service = info.service;
12278            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12279            if (ps == null) {
12280                return null;
12281            }
12282            final PackageUserState userState = ps.readUserState(userId);
12283            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12284                    userState, userId);
12285            if (si == null) {
12286                return null;
12287            }
12288            final boolean matchVisibleToInstantApp =
12289                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12290            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12291            // throw out filters that aren't visible to ephemeral apps
12292            if (matchVisibleToInstantApp
12293                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12294                return null;
12295            }
12296            // throw out ephemeral filters if we're not explicitly requesting them
12297            if (!isInstantApp && userState.instantApp) {
12298                return null;
12299            }
12300            // throw out instant app filters if updates are available; will trigger
12301            // instant app resolution
12302            if (userState.instantApp && ps.isUpdateAvailable()) {
12303                return null;
12304            }
12305            final ResolveInfo res = new ResolveInfo();
12306            res.serviceInfo = si;
12307            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12308                res.filter = filter;
12309            }
12310            res.priority = info.getPriority();
12311            res.preferredOrder = service.owner.mPreferredOrder;
12312            res.match = match;
12313            res.isDefault = info.hasDefault;
12314            res.labelRes = info.labelRes;
12315            res.nonLocalizedLabel = info.nonLocalizedLabel;
12316            res.icon = info.icon;
12317            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12318            return res;
12319        }
12320
12321        @Override
12322        protected void sortResults(List<ResolveInfo> results) {
12323            Collections.sort(results, mResolvePrioritySorter);
12324        }
12325
12326        @Override
12327        protected void dumpFilter(PrintWriter out, String prefix,
12328                PackageParser.ServiceIntentInfo filter) {
12329            out.print(prefix); out.print(
12330                    Integer.toHexString(System.identityHashCode(filter.service)));
12331                    out.print(' ');
12332                    filter.service.printComponentShortName(out);
12333                    out.print(" filter ");
12334                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12335        }
12336
12337        @Override
12338        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12339            return filter.service;
12340        }
12341
12342        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12343            PackageParser.Service service = (PackageParser.Service)label;
12344            out.print(prefix); out.print(
12345                    Integer.toHexString(System.identityHashCode(service)));
12346                    out.print(' ');
12347                    service.printComponentShortName(out);
12348            if (count > 1) {
12349                out.print(" ("); out.print(count); out.print(" filters)");
12350            }
12351            out.println();
12352        }
12353
12354//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12355//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12356//            final List<ResolveInfo> retList = Lists.newArrayList();
12357//            while (i.hasNext()) {
12358//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12359//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12360//                    retList.add(resolveInfo);
12361//                }
12362//            }
12363//            return retList;
12364//        }
12365
12366        // Keys are String (activity class name), values are Activity.
12367        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12368                = new ArrayMap<ComponentName, PackageParser.Service>();
12369        private int mFlags;
12370    }
12371
12372    private final class ProviderIntentResolver
12373            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12374        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12375                boolean defaultOnly, int userId) {
12376            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12377            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12378        }
12379
12380        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12381                int userId) {
12382            if (!sUserManager.exists(userId))
12383                return null;
12384            mFlags = flags;
12385            return super.queryIntent(intent, resolvedType,
12386                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12387                    userId);
12388        }
12389
12390        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12391                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12392            if (!sUserManager.exists(userId))
12393                return null;
12394            if (packageProviders == null) {
12395                return null;
12396            }
12397            mFlags = flags;
12398            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12399            final int N = packageProviders.size();
12400            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12401                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12402
12403            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12404            for (int i = 0; i < N; ++i) {
12405                intentFilters = packageProviders.get(i).intents;
12406                if (intentFilters != null && intentFilters.size() > 0) {
12407                    PackageParser.ProviderIntentInfo[] array =
12408                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12409                    intentFilters.toArray(array);
12410                    listCut.add(array);
12411                }
12412            }
12413            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12414        }
12415
12416        public final void addProvider(PackageParser.Provider p) {
12417            if (mProviders.containsKey(p.getComponentName())) {
12418                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12419                return;
12420            }
12421
12422            mProviders.put(p.getComponentName(), p);
12423            if (DEBUG_SHOW_INFO) {
12424                Log.v(TAG, "  "
12425                        + (p.info.nonLocalizedLabel != null
12426                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12427                Log.v(TAG, "    Class=" + p.info.name);
12428            }
12429            final int NI = p.intents.size();
12430            int j;
12431            for (j = 0; j < NI; j++) {
12432                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12433                if (DEBUG_SHOW_INFO) {
12434                    Log.v(TAG, "    IntentFilter:");
12435                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12436                }
12437                if (!intent.debugCheck()) {
12438                    Log.w(TAG, "==> For Provider " + p.info.name);
12439                }
12440                addFilter(intent);
12441            }
12442        }
12443
12444        public final void removeProvider(PackageParser.Provider p) {
12445            mProviders.remove(p.getComponentName());
12446            if (DEBUG_SHOW_INFO) {
12447                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12448                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12449                Log.v(TAG, "    Class=" + p.info.name);
12450            }
12451            final int NI = p.intents.size();
12452            int j;
12453            for (j = 0; j < NI; j++) {
12454                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12455                if (DEBUG_SHOW_INFO) {
12456                    Log.v(TAG, "    IntentFilter:");
12457                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12458                }
12459                removeFilter(intent);
12460            }
12461        }
12462
12463        @Override
12464        protected boolean allowFilterResult(
12465                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12466            ProviderInfo filterPi = filter.provider.info;
12467            for (int i = dest.size() - 1; i >= 0; i--) {
12468                ProviderInfo destPi = dest.get(i).providerInfo;
12469                if (destPi.name == filterPi.name
12470                        && destPi.packageName == filterPi.packageName) {
12471                    return false;
12472                }
12473            }
12474            return true;
12475        }
12476
12477        @Override
12478        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12479            return new PackageParser.ProviderIntentInfo[size];
12480        }
12481
12482        @Override
12483        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12484            if (!sUserManager.exists(userId))
12485                return true;
12486            PackageParser.Package p = filter.provider.owner;
12487            if (p != null) {
12488                PackageSetting ps = (PackageSetting) p.mExtras;
12489                if (ps != null) {
12490                    // System apps are never considered stopped for purposes of
12491                    // filtering, because there may be no way for the user to
12492                    // actually re-launch them.
12493                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12494                            && ps.getStopped(userId);
12495                }
12496            }
12497            return false;
12498        }
12499
12500        @Override
12501        protected boolean isPackageForFilter(String packageName,
12502                PackageParser.ProviderIntentInfo info) {
12503            return packageName.equals(info.provider.owner.packageName);
12504        }
12505
12506        @Override
12507        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12508                int match, int userId) {
12509            if (!sUserManager.exists(userId))
12510                return null;
12511            final PackageParser.ProviderIntentInfo info = filter;
12512            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12513                return null;
12514            }
12515            final PackageParser.Provider provider = info.provider;
12516            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12517            if (ps == null) {
12518                return null;
12519            }
12520            final PackageUserState userState = ps.readUserState(userId);
12521            final boolean matchVisibleToInstantApp =
12522                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12523            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12524            // throw out filters that aren't visible to instant applications
12525            if (matchVisibleToInstantApp
12526                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12527                return null;
12528            }
12529            // throw out instant application filters if we're not explicitly requesting them
12530            if (!isInstantApp && userState.instantApp) {
12531                return null;
12532            }
12533            // throw out instant application filters if updates are available; will trigger
12534            // instant application resolution
12535            if (userState.instantApp && ps.isUpdateAvailable()) {
12536                return null;
12537            }
12538            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12539                    userState, userId);
12540            if (pi == null) {
12541                return null;
12542            }
12543            final ResolveInfo res = new ResolveInfo();
12544            res.providerInfo = pi;
12545            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12546                res.filter = filter;
12547            }
12548            res.priority = info.getPriority();
12549            res.preferredOrder = provider.owner.mPreferredOrder;
12550            res.match = match;
12551            res.isDefault = info.hasDefault;
12552            res.labelRes = info.labelRes;
12553            res.nonLocalizedLabel = info.nonLocalizedLabel;
12554            res.icon = info.icon;
12555            res.system = res.providerInfo.applicationInfo.isSystemApp();
12556            return res;
12557        }
12558
12559        @Override
12560        protected void sortResults(List<ResolveInfo> results) {
12561            Collections.sort(results, mResolvePrioritySorter);
12562        }
12563
12564        @Override
12565        protected void dumpFilter(PrintWriter out, String prefix,
12566                PackageParser.ProviderIntentInfo filter) {
12567            out.print(prefix);
12568            out.print(
12569                    Integer.toHexString(System.identityHashCode(filter.provider)));
12570            out.print(' ');
12571            filter.provider.printComponentShortName(out);
12572            out.print(" filter ");
12573            out.println(Integer.toHexString(System.identityHashCode(filter)));
12574        }
12575
12576        @Override
12577        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12578            return filter.provider;
12579        }
12580
12581        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12582            PackageParser.Provider provider = (PackageParser.Provider)label;
12583            out.print(prefix); out.print(
12584                    Integer.toHexString(System.identityHashCode(provider)));
12585                    out.print(' ');
12586                    provider.printComponentShortName(out);
12587            if (count > 1) {
12588                out.print(" ("); out.print(count); out.print(" filters)");
12589            }
12590            out.println();
12591        }
12592
12593        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12594                = new ArrayMap<ComponentName, PackageParser.Provider>();
12595        private int mFlags;
12596    }
12597
12598    static final class EphemeralIntentResolver
12599            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12600        /**
12601         * The result that has the highest defined order. Ordering applies on a
12602         * per-package basis. Mapping is from package name to Pair of order and
12603         * EphemeralResolveInfo.
12604         * <p>
12605         * NOTE: This is implemented as a field variable for convenience and efficiency.
12606         * By having a field variable, we're able to track filter ordering as soon as
12607         * a non-zero order is defined. Otherwise, multiple loops across the result set
12608         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12609         * this needs to be contained entirely within {@link #filterResults}.
12610         */
12611        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12612
12613        @Override
12614        protected AuxiliaryResolveInfo[] newArray(int size) {
12615            return new AuxiliaryResolveInfo[size];
12616        }
12617
12618        @Override
12619        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12620            return true;
12621        }
12622
12623        @Override
12624        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12625                int userId) {
12626            if (!sUserManager.exists(userId)) {
12627                return null;
12628            }
12629            final String packageName = responseObj.resolveInfo.getPackageName();
12630            final Integer order = responseObj.getOrder();
12631            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12632                    mOrderResult.get(packageName);
12633            // ordering is enabled and this item's order isn't high enough
12634            if (lastOrderResult != null && lastOrderResult.first >= order) {
12635                return null;
12636            }
12637            final InstantAppResolveInfo res = responseObj.resolveInfo;
12638            if (order > 0) {
12639                // non-zero order, enable ordering
12640                mOrderResult.put(packageName, new Pair<>(order, res));
12641            }
12642            return responseObj;
12643        }
12644
12645        @Override
12646        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12647            // only do work if ordering is enabled [most of the time it won't be]
12648            if (mOrderResult.size() == 0) {
12649                return;
12650            }
12651            int resultSize = results.size();
12652            for (int i = 0; i < resultSize; i++) {
12653                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12654                final String packageName = info.getPackageName();
12655                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12656                if (savedInfo == null) {
12657                    // package doesn't having ordering
12658                    continue;
12659                }
12660                if (savedInfo.second == info) {
12661                    // circled back to the highest ordered item; remove from order list
12662                    mOrderResult.remove(packageName);
12663                    if (mOrderResult.size() == 0) {
12664                        // no more ordered items
12665                        break;
12666                    }
12667                    continue;
12668                }
12669                // item has a worse order, remove it from the result list
12670                results.remove(i);
12671                resultSize--;
12672                i--;
12673            }
12674        }
12675    }
12676
12677    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12678            new Comparator<ResolveInfo>() {
12679        public int compare(ResolveInfo r1, ResolveInfo r2) {
12680            int v1 = r1.priority;
12681            int v2 = r2.priority;
12682            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12683            if (v1 != v2) {
12684                return (v1 > v2) ? -1 : 1;
12685            }
12686            v1 = r1.preferredOrder;
12687            v2 = r2.preferredOrder;
12688            if (v1 != v2) {
12689                return (v1 > v2) ? -1 : 1;
12690            }
12691            if (r1.isDefault != r2.isDefault) {
12692                return r1.isDefault ? -1 : 1;
12693            }
12694            v1 = r1.match;
12695            v2 = r2.match;
12696            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12697            if (v1 != v2) {
12698                return (v1 > v2) ? -1 : 1;
12699            }
12700            if (r1.system != r2.system) {
12701                return r1.system ? -1 : 1;
12702            }
12703            if (r1.activityInfo != null) {
12704                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12705            }
12706            if (r1.serviceInfo != null) {
12707                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12708            }
12709            if (r1.providerInfo != null) {
12710                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12711            }
12712            return 0;
12713        }
12714    };
12715
12716    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12717            new Comparator<ProviderInfo>() {
12718        public int compare(ProviderInfo p1, ProviderInfo p2) {
12719            final int v1 = p1.initOrder;
12720            final int v2 = p2.initOrder;
12721            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12722        }
12723    };
12724
12725    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12726            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12727            final int[] userIds) {
12728        mHandler.post(new Runnable() {
12729            @Override
12730            public void run() {
12731                try {
12732                    final IActivityManager am = ActivityManager.getService();
12733                    if (am == null) return;
12734                    final int[] resolvedUserIds;
12735                    if (userIds == null) {
12736                        resolvedUserIds = am.getRunningUserIds();
12737                    } else {
12738                        resolvedUserIds = userIds;
12739                    }
12740                    for (int id : resolvedUserIds) {
12741                        final Intent intent = new Intent(action,
12742                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12743                        if (extras != null) {
12744                            intent.putExtras(extras);
12745                        }
12746                        if (targetPkg != null) {
12747                            intent.setPackage(targetPkg);
12748                        }
12749                        // Modify the UID when posting to other users
12750                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12751                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12752                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12753                            intent.putExtra(Intent.EXTRA_UID, uid);
12754                        }
12755                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12756                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12757                        if (DEBUG_BROADCASTS) {
12758                            RuntimeException here = new RuntimeException("here");
12759                            here.fillInStackTrace();
12760                            Slog.d(TAG, "Sending to user " + id + ": "
12761                                    + intent.toShortString(false, true, false, false)
12762                                    + " " + intent.getExtras(), here);
12763                        }
12764                        am.broadcastIntent(null, intent, null, finishedReceiver,
12765                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12766                                null, finishedReceiver != null, false, id);
12767                    }
12768                } catch (RemoteException ex) {
12769                }
12770            }
12771        });
12772    }
12773
12774    /**
12775     * Check if the external storage media is available. This is true if there
12776     * is a mounted external storage medium or if the external storage is
12777     * emulated.
12778     */
12779    private boolean isExternalMediaAvailable() {
12780        return mMediaMounted || Environment.isExternalStorageEmulated();
12781    }
12782
12783    @Override
12784    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12785        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
12786            return null;
12787        }
12788        // writer
12789        synchronized (mPackages) {
12790            if (!isExternalMediaAvailable()) {
12791                // If the external storage is no longer mounted at this point,
12792                // the caller may not have been able to delete all of this
12793                // packages files and can not delete any more.  Bail.
12794                return null;
12795            }
12796            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12797            if (lastPackage != null) {
12798                pkgs.remove(lastPackage);
12799            }
12800            if (pkgs.size() > 0) {
12801                return pkgs.get(0);
12802            }
12803        }
12804        return null;
12805    }
12806
12807    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12808        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12809                userId, andCode ? 1 : 0, packageName);
12810        if (mSystemReady) {
12811            msg.sendToTarget();
12812        } else {
12813            if (mPostSystemReadyMessages == null) {
12814                mPostSystemReadyMessages = new ArrayList<>();
12815            }
12816            mPostSystemReadyMessages.add(msg);
12817        }
12818    }
12819
12820    void startCleaningPackages() {
12821        // reader
12822        if (!isExternalMediaAvailable()) {
12823            return;
12824        }
12825        synchronized (mPackages) {
12826            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12827                return;
12828            }
12829        }
12830        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12831        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12832        IActivityManager am = ActivityManager.getService();
12833        if (am != null) {
12834            int dcsUid = -1;
12835            synchronized (mPackages) {
12836                if (!mDefaultContainerWhitelisted) {
12837                    mDefaultContainerWhitelisted = true;
12838                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
12839                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
12840                }
12841            }
12842            try {
12843                if (dcsUid > 0) {
12844                    am.backgroundWhitelistUid(dcsUid);
12845                }
12846                am.startService(null, intent, null, false, mContext.getOpPackageName(),
12847                        UserHandle.USER_SYSTEM);
12848            } catch (RemoteException e) {
12849            }
12850        }
12851    }
12852
12853    @Override
12854    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12855            int installFlags, String installerPackageName, int userId) {
12856        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12857
12858        final int callingUid = Binder.getCallingUid();
12859        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
12860                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12861
12862        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12863            try {
12864                if (observer != null) {
12865                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12866                }
12867            } catch (RemoteException re) {
12868            }
12869            return;
12870        }
12871
12872        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12873            installFlags |= PackageManager.INSTALL_FROM_ADB;
12874
12875        } else {
12876            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12877            // about installerPackageName.
12878
12879            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12880            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12881        }
12882
12883        UserHandle user;
12884        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12885            user = UserHandle.ALL;
12886        } else {
12887            user = new UserHandle(userId);
12888        }
12889
12890        // Only system components can circumvent runtime permissions when installing.
12891        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12892                && mContext.checkCallingOrSelfPermission(Manifest.permission
12893                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12894            throw new SecurityException("You need the "
12895                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12896                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12897        }
12898
12899        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12900                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12901            throw new IllegalArgumentException(
12902                    "New installs into ASEC containers no longer supported");
12903        }
12904
12905        final File originFile = new File(originPath);
12906        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12907
12908        final Message msg = mHandler.obtainMessage(INIT_COPY);
12909        final VerificationInfo verificationInfo = new VerificationInfo(
12910                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12911        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12912                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12913                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12914                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12915        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12916        msg.obj = params;
12917
12918        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12919                System.identityHashCode(msg.obj));
12920        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12921                System.identityHashCode(msg.obj));
12922
12923        mHandler.sendMessage(msg);
12924    }
12925
12926
12927    /**
12928     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12929     * it is acting on behalf on an enterprise or the user).
12930     *
12931     * Note that the ordering of the conditionals in this method is important. The checks we perform
12932     * are as follows, in this order:
12933     *
12934     * 1) If the install is being performed by a system app, we can trust the app to have set the
12935     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12936     *    what it is.
12937     * 2) If the install is being performed by a device or profile owner app, the install reason
12938     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12939     *    set the install reason correctly. If the app targets an older SDK version where install
12940     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12941     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12942     * 3) In all other cases, the install is being performed by a regular app that is neither part
12943     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12944     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12945     *    set to enterprise policy and if so, change it to unknown instead.
12946     */
12947    private int fixUpInstallReason(String installerPackageName, int installerUid,
12948            int installReason) {
12949        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12950                == PERMISSION_GRANTED) {
12951            // If the install is being performed by a system app, we trust that app to have set the
12952            // install reason correctly.
12953            return installReason;
12954        }
12955
12956        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12957            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12958        if (dpm != null) {
12959            ComponentName owner = null;
12960            try {
12961                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12962                if (owner == null) {
12963                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12964                }
12965            } catch (RemoteException e) {
12966            }
12967            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12968                // If the install is being performed by a device or profile owner, the install
12969                // reason should be enterprise policy.
12970                return PackageManager.INSTALL_REASON_POLICY;
12971            }
12972        }
12973
12974        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12975            // If the install is being performed by a regular app (i.e. neither system app nor
12976            // device or profile owner), we have no reason to believe that the app is acting on
12977            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12978            // change it to unknown instead.
12979            return PackageManager.INSTALL_REASON_UNKNOWN;
12980        }
12981
12982        // If the install is being performed by a regular app and the install reason was set to any
12983        // value but enterprise policy, leave the install reason unchanged.
12984        return installReason;
12985    }
12986
12987    void installStage(String packageName, File stagedDir,
12988            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12989            String installerPackageName, int installerUid, UserHandle user,
12990            Certificate[][] certificates) {
12991        if (DEBUG_EPHEMERAL) {
12992            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
12993                Slog.d(TAG, "Ephemeral install of " + packageName);
12994            }
12995        }
12996        final VerificationInfo verificationInfo = new VerificationInfo(
12997                sessionParams.originatingUri, sessionParams.referrerUri,
12998                sessionParams.originatingUid, installerUid);
12999
13000        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13001
13002        final Message msg = mHandler.obtainMessage(INIT_COPY);
13003        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13004                sessionParams.installReason);
13005        final InstallParams params = new InstallParams(origin, null, observer,
13006                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13007                verificationInfo, user, sessionParams.abiOverride,
13008                sessionParams.grantedRuntimePermissions, certificates, installReason);
13009        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13010        msg.obj = params;
13011
13012        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13013                System.identityHashCode(msg.obj));
13014        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13015                System.identityHashCode(msg.obj));
13016
13017        mHandler.sendMessage(msg);
13018    }
13019
13020    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13021            int userId) {
13022        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13023        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13024                false /*startReceiver*/, pkgSetting.appId, userId);
13025
13026        // Send a session commit broadcast
13027        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13028        info.installReason = pkgSetting.getInstallReason(userId);
13029        info.appPackageName = packageName;
13030        sendSessionCommitBroadcast(info, userId);
13031    }
13032
13033    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13034            boolean includeStopped, int appId, int... userIds) {
13035        if (ArrayUtils.isEmpty(userIds)) {
13036            return;
13037        }
13038        Bundle extras = new Bundle(1);
13039        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13040        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13041
13042        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13043                packageName, extras, 0, null, null, userIds);
13044        if (sendBootCompleted) {
13045            mHandler.post(() -> {
13046                        for (int userId : userIds) {
13047                            sendBootCompletedBroadcastToSystemApp(
13048                                    packageName, includeStopped, userId);
13049                        }
13050                    }
13051            );
13052        }
13053    }
13054
13055    /**
13056     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13057     * automatically without needing an explicit launch.
13058     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13059     */
13060    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13061            int userId) {
13062        // If user is not running, the app didn't miss any broadcast
13063        if (!mUserManagerInternal.isUserRunning(userId)) {
13064            return;
13065        }
13066        final IActivityManager am = ActivityManager.getService();
13067        try {
13068            // Deliver LOCKED_BOOT_COMPLETED first
13069            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13070                    .setPackage(packageName);
13071            if (includeStopped) {
13072                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13073            }
13074            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13075            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13076                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13077
13078            // Deliver BOOT_COMPLETED only if user is unlocked
13079            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13080                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13081                if (includeStopped) {
13082                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13083                }
13084                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13085                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13086            }
13087        } catch (RemoteException e) {
13088            throw e.rethrowFromSystemServer();
13089        }
13090    }
13091
13092    @Override
13093    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13094            int userId) {
13095        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13096        PackageSetting pkgSetting;
13097        final int callingUid = Binder.getCallingUid();
13098        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13099                true /* requireFullPermission */, true /* checkShell */,
13100                "setApplicationHiddenSetting for user " + userId);
13101
13102        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13103            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13104            return false;
13105        }
13106
13107        long callingId = Binder.clearCallingIdentity();
13108        try {
13109            boolean sendAdded = false;
13110            boolean sendRemoved = false;
13111            // writer
13112            synchronized (mPackages) {
13113                pkgSetting = mSettings.mPackages.get(packageName);
13114                if (pkgSetting == null) {
13115                    return false;
13116                }
13117                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13118                    return false;
13119                }
13120                // Do not allow "android" is being disabled
13121                if ("android".equals(packageName)) {
13122                    Slog.w(TAG, "Cannot hide package: android");
13123                    return false;
13124                }
13125                // Cannot hide static shared libs as they are considered
13126                // a part of the using app (emulating static linking). Also
13127                // static libs are installed always on internal storage.
13128                PackageParser.Package pkg = mPackages.get(packageName);
13129                if (pkg != null && pkg.staticSharedLibName != null) {
13130                    Slog.w(TAG, "Cannot hide package: " + packageName
13131                            + " providing static shared library: "
13132                            + pkg.staticSharedLibName);
13133                    return false;
13134                }
13135                // Only allow protected packages to hide themselves.
13136                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13137                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13138                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13139                    return false;
13140                }
13141
13142                if (pkgSetting.getHidden(userId) != hidden) {
13143                    pkgSetting.setHidden(hidden, userId);
13144                    mSettings.writePackageRestrictionsLPr(userId);
13145                    if (hidden) {
13146                        sendRemoved = true;
13147                    } else {
13148                        sendAdded = true;
13149                    }
13150                }
13151            }
13152            if (sendAdded) {
13153                sendPackageAddedForUser(packageName, pkgSetting, userId);
13154                return true;
13155            }
13156            if (sendRemoved) {
13157                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13158                        "hiding pkg");
13159                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13160                return true;
13161            }
13162        } finally {
13163            Binder.restoreCallingIdentity(callingId);
13164        }
13165        return false;
13166    }
13167
13168    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13169            int userId) {
13170        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13171        info.removedPackage = packageName;
13172        info.installerPackageName = pkgSetting.installerPackageName;
13173        info.removedUsers = new int[] {userId};
13174        info.broadcastUsers = new int[] {userId};
13175        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13176        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13177    }
13178
13179    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13180        if (pkgList.length > 0) {
13181            Bundle extras = new Bundle(1);
13182            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13183
13184            sendPackageBroadcast(
13185                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13186                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13187                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13188                    new int[] {userId});
13189        }
13190    }
13191
13192    /**
13193     * Returns true if application is not found or there was an error. Otherwise it returns
13194     * the hidden state of the package for the given user.
13195     */
13196    @Override
13197    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13198        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13199        final int callingUid = Binder.getCallingUid();
13200        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13201                true /* requireFullPermission */, false /* checkShell */,
13202                "getApplicationHidden for user " + userId);
13203        PackageSetting ps;
13204        long callingId = Binder.clearCallingIdentity();
13205        try {
13206            // writer
13207            synchronized (mPackages) {
13208                ps = mSettings.mPackages.get(packageName);
13209                if (ps == null) {
13210                    return true;
13211                }
13212                if (filterAppAccessLPr(ps, callingUid, userId)) {
13213                    return true;
13214                }
13215                return ps.getHidden(userId);
13216            }
13217        } finally {
13218            Binder.restoreCallingIdentity(callingId);
13219        }
13220    }
13221
13222    /**
13223     * @hide
13224     */
13225    @Override
13226    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13227            int installReason) {
13228        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13229                null);
13230        PackageSetting pkgSetting;
13231        final int callingUid = Binder.getCallingUid();
13232        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13233                true /* requireFullPermission */, true /* checkShell */,
13234                "installExistingPackage for user " + userId);
13235        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13236            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13237        }
13238
13239        long callingId = Binder.clearCallingIdentity();
13240        try {
13241            boolean installed = false;
13242            final boolean instantApp =
13243                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13244            final boolean fullApp =
13245                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13246
13247            // writer
13248            synchronized (mPackages) {
13249                pkgSetting = mSettings.mPackages.get(packageName);
13250                if (pkgSetting == null) {
13251                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13252                }
13253                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13254                    // only allow the existing package to be used if it's installed as a full
13255                    // application for at least one user
13256                    boolean installAllowed = false;
13257                    for (int checkUserId : sUserManager.getUserIds()) {
13258                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13259                        if (installAllowed) {
13260                            break;
13261                        }
13262                    }
13263                    if (!installAllowed) {
13264                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13265                    }
13266                }
13267                if (!pkgSetting.getInstalled(userId)) {
13268                    pkgSetting.setInstalled(true, userId);
13269                    pkgSetting.setHidden(false, userId);
13270                    pkgSetting.setInstallReason(installReason, userId);
13271                    mSettings.writePackageRestrictionsLPr(userId);
13272                    mSettings.writeKernelMappingLPr(pkgSetting);
13273                    installed = true;
13274                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13275                    // upgrade app from instant to full; we don't allow app downgrade
13276                    installed = true;
13277                }
13278                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13279            }
13280
13281            if (installed) {
13282                if (pkgSetting.pkg != null) {
13283                    synchronized (mInstallLock) {
13284                        // We don't need to freeze for a brand new install
13285                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13286                    }
13287                }
13288                sendPackageAddedForUser(packageName, pkgSetting, userId);
13289                synchronized (mPackages) {
13290                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13291                }
13292            }
13293        } finally {
13294            Binder.restoreCallingIdentity(callingId);
13295        }
13296
13297        return PackageManager.INSTALL_SUCCEEDED;
13298    }
13299
13300    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13301            boolean instantApp, boolean fullApp) {
13302        // no state specified; do nothing
13303        if (!instantApp && !fullApp) {
13304            return;
13305        }
13306        if (userId != UserHandle.USER_ALL) {
13307            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13308                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13309            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13310                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13311            }
13312        } else {
13313            for (int currentUserId : sUserManager.getUserIds()) {
13314                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13315                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13316                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13317                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13318                }
13319            }
13320        }
13321    }
13322
13323    boolean isUserRestricted(int userId, String restrictionKey) {
13324        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13325        if (restrictions.getBoolean(restrictionKey, false)) {
13326            Log.w(TAG, "User is restricted: " + restrictionKey);
13327            return true;
13328        }
13329        return false;
13330    }
13331
13332    @Override
13333    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13334            int userId) {
13335        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13336        final int callingUid = Binder.getCallingUid();
13337        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13338                true /* requireFullPermission */, true /* checkShell */,
13339                "setPackagesSuspended for user " + userId);
13340
13341        if (ArrayUtils.isEmpty(packageNames)) {
13342            return packageNames;
13343        }
13344
13345        // List of package names for whom the suspended state has changed.
13346        List<String> changedPackages = new ArrayList<>(packageNames.length);
13347        // List of package names for whom the suspended state is not set as requested in this
13348        // method.
13349        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13350        long callingId = Binder.clearCallingIdentity();
13351        try {
13352            for (int i = 0; i < packageNames.length; i++) {
13353                String packageName = packageNames[i];
13354                boolean changed = false;
13355                final int appId;
13356                synchronized (mPackages) {
13357                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13358                    if (pkgSetting == null
13359                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13360                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13361                                + "\". Skipping suspending/un-suspending.");
13362                        unactionedPackages.add(packageName);
13363                        continue;
13364                    }
13365                    appId = pkgSetting.appId;
13366                    if (pkgSetting.getSuspended(userId) != suspended) {
13367                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13368                            unactionedPackages.add(packageName);
13369                            continue;
13370                        }
13371                        pkgSetting.setSuspended(suspended, userId);
13372                        mSettings.writePackageRestrictionsLPr(userId);
13373                        changed = true;
13374                        changedPackages.add(packageName);
13375                    }
13376                }
13377
13378                if (changed && suspended) {
13379                    killApplication(packageName, UserHandle.getUid(userId, appId),
13380                            "suspending package");
13381                }
13382            }
13383        } finally {
13384            Binder.restoreCallingIdentity(callingId);
13385        }
13386
13387        if (!changedPackages.isEmpty()) {
13388            sendPackagesSuspendedForUser(changedPackages.toArray(
13389                    new String[changedPackages.size()]), userId, suspended);
13390        }
13391
13392        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13393    }
13394
13395    @Override
13396    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13397        final int callingUid = Binder.getCallingUid();
13398        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13399                true /* requireFullPermission */, false /* checkShell */,
13400                "isPackageSuspendedForUser for user " + userId);
13401        synchronized (mPackages) {
13402            final PackageSetting ps = mSettings.mPackages.get(packageName);
13403            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13404                throw new IllegalArgumentException("Unknown target package: " + packageName);
13405            }
13406            return ps.getSuspended(userId);
13407        }
13408    }
13409
13410    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13411        if (isPackageDeviceAdmin(packageName, userId)) {
13412            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13413                    + "\": has an active device admin");
13414            return false;
13415        }
13416
13417        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13418        if (packageName.equals(activeLauncherPackageName)) {
13419            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13420                    + "\": contains the active launcher");
13421            return false;
13422        }
13423
13424        if (packageName.equals(mRequiredInstallerPackage)) {
13425            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13426                    + "\": required for package installation");
13427            return false;
13428        }
13429
13430        if (packageName.equals(mRequiredUninstallerPackage)) {
13431            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13432                    + "\": required for package uninstallation");
13433            return false;
13434        }
13435
13436        if (packageName.equals(mRequiredVerifierPackage)) {
13437            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13438                    + "\": required for package verification");
13439            return false;
13440        }
13441
13442        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13443            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13444                    + "\": is the default dialer");
13445            return false;
13446        }
13447
13448        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13449            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13450                    + "\": protected package");
13451            return false;
13452        }
13453
13454        // Cannot suspend static shared libs as they are considered
13455        // a part of the using app (emulating static linking). Also
13456        // static libs are installed always on internal storage.
13457        PackageParser.Package pkg = mPackages.get(packageName);
13458        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13459            Slog.w(TAG, "Cannot suspend package: " + packageName
13460                    + " providing static shared library: "
13461                    + pkg.staticSharedLibName);
13462            return false;
13463        }
13464
13465        return true;
13466    }
13467
13468    private String getActiveLauncherPackageName(int userId) {
13469        Intent intent = new Intent(Intent.ACTION_MAIN);
13470        intent.addCategory(Intent.CATEGORY_HOME);
13471        ResolveInfo resolveInfo = resolveIntent(
13472                intent,
13473                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13474                PackageManager.MATCH_DEFAULT_ONLY,
13475                userId);
13476
13477        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13478    }
13479
13480    private String getDefaultDialerPackageName(int userId) {
13481        synchronized (mPackages) {
13482            return mSettings.getDefaultDialerPackageNameLPw(userId);
13483        }
13484    }
13485
13486    @Override
13487    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13488        mContext.enforceCallingOrSelfPermission(
13489                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13490                "Only package verification agents can verify applications");
13491
13492        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13493        final PackageVerificationResponse response = new PackageVerificationResponse(
13494                verificationCode, Binder.getCallingUid());
13495        msg.arg1 = id;
13496        msg.obj = response;
13497        mHandler.sendMessage(msg);
13498    }
13499
13500    @Override
13501    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13502            long millisecondsToDelay) {
13503        mContext.enforceCallingOrSelfPermission(
13504                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13505                "Only package verification agents can extend verification timeouts");
13506
13507        final PackageVerificationState state = mPendingVerification.get(id);
13508        final PackageVerificationResponse response = new PackageVerificationResponse(
13509                verificationCodeAtTimeout, Binder.getCallingUid());
13510
13511        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13512            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13513        }
13514        if (millisecondsToDelay < 0) {
13515            millisecondsToDelay = 0;
13516        }
13517        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13518                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13519            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13520        }
13521
13522        if ((state != null) && !state.timeoutExtended()) {
13523            state.extendTimeout();
13524
13525            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13526            msg.arg1 = id;
13527            msg.obj = response;
13528            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13529        }
13530    }
13531
13532    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13533            int verificationCode, UserHandle user) {
13534        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13535        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13536        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13537        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13538        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13539
13540        mContext.sendBroadcastAsUser(intent, user,
13541                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13542    }
13543
13544    private ComponentName matchComponentForVerifier(String packageName,
13545            List<ResolveInfo> receivers) {
13546        ActivityInfo targetReceiver = null;
13547
13548        final int NR = receivers.size();
13549        for (int i = 0; i < NR; i++) {
13550            final ResolveInfo info = receivers.get(i);
13551            if (info.activityInfo == null) {
13552                continue;
13553            }
13554
13555            if (packageName.equals(info.activityInfo.packageName)) {
13556                targetReceiver = info.activityInfo;
13557                break;
13558            }
13559        }
13560
13561        if (targetReceiver == null) {
13562            return null;
13563        }
13564
13565        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13566    }
13567
13568    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13569            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13570        if (pkgInfo.verifiers.length == 0) {
13571            return null;
13572        }
13573
13574        final int N = pkgInfo.verifiers.length;
13575        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13576        for (int i = 0; i < N; i++) {
13577            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13578
13579            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13580                    receivers);
13581            if (comp == null) {
13582                continue;
13583            }
13584
13585            final int verifierUid = getUidForVerifier(verifierInfo);
13586            if (verifierUid == -1) {
13587                continue;
13588            }
13589
13590            if (DEBUG_VERIFY) {
13591                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13592                        + " with the correct signature");
13593            }
13594            sufficientVerifiers.add(comp);
13595            verificationState.addSufficientVerifier(verifierUid);
13596        }
13597
13598        return sufficientVerifiers;
13599    }
13600
13601    private int getUidForVerifier(VerifierInfo verifierInfo) {
13602        synchronized (mPackages) {
13603            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13604            if (pkg == null) {
13605                return -1;
13606            } else if (pkg.mSignatures.length != 1) {
13607                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13608                        + " has more than one signature; ignoring");
13609                return -1;
13610            }
13611
13612            /*
13613             * If the public key of the package's signature does not match
13614             * our expected public key, then this is a different package and
13615             * we should skip.
13616             */
13617
13618            final byte[] expectedPublicKey;
13619            try {
13620                final Signature verifierSig = pkg.mSignatures[0];
13621                final PublicKey publicKey = verifierSig.getPublicKey();
13622                expectedPublicKey = publicKey.getEncoded();
13623            } catch (CertificateException e) {
13624                return -1;
13625            }
13626
13627            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13628
13629            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13630                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13631                        + " does not have the expected public key; ignoring");
13632                return -1;
13633            }
13634
13635            return pkg.applicationInfo.uid;
13636        }
13637    }
13638
13639    @Override
13640    public void finishPackageInstall(int token, boolean didLaunch) {
13641        enforceSystemOrRoot("Only the system is allowed to finish installs");
13642
13643        if (DEBUG_INSTALL) {
13644            Slog.v(TAG, "BM finishing package install for " + token);
13645        }
13646        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13647
13648        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13649        mHandler.sendMessage(msg);
13650    }
13651
13652    /**
13653     * Get the verification agent timeout.  Used for both the APK verifier and the
13654     * intent filter verifier.
13655     *
13656     * @return verification timeout in milliseconds
13657     */
13658    private long getVerificationTimeout() {
13659        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13660                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13661                DEFAULT_VERIFICATION_TIMEOUT);
13662    }
13663
13664    /**
13665     * Get the default verification agent response code.
13666     *
13667     * @return default verification response code
13668     */
13669    private int getDefaultVerificationResponse(UserHandle user) {
13670        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13671            return PackageManager.VERIFICATION_REJECT;
13672        }
13673        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13674                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13675                DEFAULT_VERIFICATION_RESPONSE);
13676    }
13677
13678    /**
13679     * Check whether or not package verification has been enabled.
13680     *
13681     * @return true if verification should be performed
13682     */
13683    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13684        if (!DEFAULT_VERIFY_ENABLE) {
13685            return false;
13686        }
13687
13688        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13689
13690        // Check if installing from ADB
13691        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13692            // Do not run verification in a test harness environment
13693            if (ActivityManager.isRunningInTestHarness()) {
13694                return false;
13695            }
13696            if (ensureVerifyAppsEnabled) {
13697                return true;
13698            }
13699            // Check if the developer does not want package verification for ADB installs
13700            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13701                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13702                return false;
13703            }
13704        } else {
13705            // only when not installed from ADB, skip verification for instant apps when
13706            // the installer and verifier are the same.
13707            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13708                if (mInstantAppInstallerActivity != null
13709                        && mInstantAppInstallerActivity.packageName.equals(
13710                                mRequiredVerifierPackage)) {
13711                    try {
13712                        mContext.getSystemService(AppOpsManager.class)
13713                                .checkPackage(installerUid, mRequiredVerifierPackage);
13714                        if (DEBUG_VERIFY) {
13715                            Slog.i(TAG, "disable verification for instant app");
13716                        }
13717                        return false;
13718                    } catch (SecurityException ignore) { }
13719                }
13720            }
13721        }
13722
13723        if (ensureVerifyAppsEnabled) {
13724            return true;
13725        }
13726
13727        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13728                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13729    }
13730
13731    @Override
13732    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13733            throws RemoteException {
13734        mContext.enforceCallingOrSelfPermission(
13735                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13736                "Only intentfilter verification agents can verify applications");
13737
13738        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13739        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13740                Binder.getCallingUid(), verificationCode, failedDomains);
13741        msg.arg1 = id;
13742        msg.obj = response;
13743        mHandler.sendMessage(msg);
13744    }
13745
13746    @Override
13747    public int getIntentVerificationStatus(String packageName, int userId) {
13748        final int callingUid = Binder.getCallingUid();
13749        if (UserHandle.getUserId(callingUid) != userId) {
13750            mContext.enforceCallingOrSelfPermission(
13751                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13752                    "getIntentVerificationStatus" + userId);
13753        }
13754        if (getInstantAppPackageName(callingUid) != null) {
13755            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13756        }
13757        synchronized (mPackages) {
13758            final PackageSetting ps = mSettings.mPackages.get(packageName);
13759            if (ps == null
13760                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13761                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13762            }
13763            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13764        }
13765    }
13766
13767    @Override
13768    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13769        mContext.enforceCallingOrSelfPermission(
13770                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13771
13772        boolean result = false;
13773        synchronized (mPackages) {
13774            final PackageSetting ps = mSettings.mPackages.get(packageName);
13775            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13776                return false;
13777            }
13778            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13779        }
13780        if (result) {
13781            scheduleWritePackageRestrictionsLocked(userId);
13782        }
13783        return result;
13784    }
13785
13786    @Override
13787    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13788            String packageName) {
13789        final int callingUid = Binder.getCallingUid();
13790        if (getInstantAppPackageName(callingUid) != null) {
13791            return ParceledListSlice.emptyList();
13792        }
13793        synchronized (mPackages) {
13794            final PackageSetting ps = mSettings.mPackages.get(packageName);
13795            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13796                return ParceledListSlice.emptyList();
13797            }
13798            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13799        }
13800    }
13801
13802    @Override
13803    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13804        if (TextUtils.isEmpty(packageName)) {
13805            return ParceledListSlice.emptyList();
13806        }
13807        final int callingUid = Binder.getCallingUid();
13808        final int callingUserId = UserHandle.getUserId(callingUid);
13809        synchronized (mPackages) {
13810            PackageParser.Package pkg = mPackages.get(packageName);
13811            if (pkg == null || pkg.activities == null) {
13812                return ParceledListSlice.emptyList();
13813            }
13814            if (pkg.mExtras == null) {
13815                return ParceledListSlice.emptyList();
13816            }
13817            final PackageSetting ps = (PackageSetting) pkg.mExtras;
13818            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
13819                return ParceledListSlice.emptyList();
13820            }
13821            final int count = pkg.activities.size();
13822            ArrayList<IntentFilter> result = new ArrayList<>();
13823            for (int n=0; n<count; n++) {
13824                PackageParser.Activity activity = pkg.activities.get(n);
13825                if (activity.intents != null && activity.intents.size() > 0) {
13826                    result.addAll(activity.intents);
13827                }
13828            }
13829            return new ParceledListSlice<>(result);
13830        }
13831    }
13832
13833    @Override
13834    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13835        mContext.enforceCallingOrSelfPermission(
13836                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13837        if (UserHandle.getCallingUserId() != userId) {
13838            mContext.enforceCallingOrSelfPermission(
13839                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13840        }
13841
13842        synchronized (mPackages) {
13843            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13844            if (packageName != null) {
13845                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
13846                        packageName, userId);
13847            }
13848            return result;
13849        }
13850    }
13851
13852    @Override
13853    public String getDefaultBrowserPackageName(int userId) {
13854        if (UserHandle.getCallingUserId() != userId) {
13855            mContext.enforceCallingOrSelfPermission(
13856                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13857        }
13858        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13859            return null;
13860        }
13861        synchronized (mPackages) {
13862            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13863        }
13864    }
13865
13866    /**
13867     * Get the "allow unknown sources" setting.
13868     *
13869     * @return the current "allow unknown sources" setting
13870     */
13871    private int getUnknownSourcesSettings() {
13872        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13873                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13874                -1);
13875    }
13876
13877    @Override
13878    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13879        final int callingUid = Binder.getCallingUid();
13880        if (getInstantAppPackageName(callingUid) != null) {
13881            return;
13882        }
13883        // writer
13884        synchronized (mPackages) {
13885            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13886            if (targetPackageSetting == null
13887                    || filterAppAccessLPr(
13888                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
13889                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13890            }
13891
13892            PackageSetting installerPackageSetting;
13893            if (installerPackageName != null) {
13894                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13895                if (installerPackageSetting == null) {
13896                    throw new IllegalArgumentException("Unknown installer package: "
13897                            + installerPackageName);
13898                }
13899            } else {
13900                installerPackageSetting = null;
13901            }
13902
13903            Signature[] callerSignature;
13904            Object obj = mSettings.getUserIdLPr(callingUid);
13905            if (obj != null) {
13906                if (obj instanceof SharedUserSetting) {
13907                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13908                } else if (obj instanceof PackageSetting) {
13909                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13910                } else {
13911                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
13912                }
13913            } else {
13914                throw new SecurityException("Unknown calling UID: " + callingUid);
13915            }
13916
13917            // Verify: can't set installerPackageName to a package that is
13918            // not signed with the same cert as the caller.
13919            if (installerPackageSetting != null) {
13920                if (compareSignatures(callerSignature,
13921                        installerPackageSetting.signatures.mSignatures)
13922                        != PackageManager.SIGNATURE_MATCH) {
13923                    throw new SecurityException(
13924                            "Caller does not have same cert as new installer package "
13925                            + installerPackageName);
13926                }
13927            }
13928
13929            // Verify: if target already has an installer package, it must
13930            // be signed with the same cert as the caller.
13931            if (targetPackageSetting.installerPackageName != null) {
13932                PackageSetting setting = mSettings.mPackages.get(
13933                        targetPackageSetting.installerPackageName);
13934                // If the currently set package isn't valid, then it's always
13935                // okay to change it.
13936                if (setting != null) {
13937                    if (compareSignatures(callerSignature,
13938                            setting.signatures.mSignatures)
13939                            != PackageManager.SIGNATURE_MATCH) {
13940                        throw new SecurityException(
13941                                "Caller does not have same cert as old installer package "
13942                                + targetPackageSetting.installerPackageName);
13943                    }
13944                }
13945            }
13946
13947            // Okay!
13948            targetPackageSetting.installerPackageName = installerPackageName;
13949            if (installerPackageName != null) {
13950                mSettings.mInstallerPackages.add(installerPackageName);
13951            }
13952            scheduleWriteSettingsLocked();
13953        }
13954    }
13955
13956    @Override
13957    public void setApplicationCategoryHint(String packageName, int categoryHint,
13958            String callerPackageName) {
13959        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13960            throw new SecurityException("Instant applications don't have access to this method");
13961        }
13962        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13963                callerPackageName);
13964        synchronized (mPackages) {
13965            PackageSetting ps = mSettings.mPackages.get(packageName);
13966            if (ps == null) {
13967                throw new IllegalArgumentException("Unknown target package " + packageName);
13968            }
13969            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13970                throw new IllegalArgumentException("Unknown target package " + packageName);
13971            }
13972            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13973                throw new IllegalArgumentException("Calling package " + callerPackageName
13974                        + " is not installer for " + packageName);
13975            }
13976
13977            if (ps.categoryHint != categoryHint) {
13978                ps.categoryHint = categoryHint;
13979                scheduleWriteSettingsLocked();
13980            }
13981        }
13982    }
13983
13984    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13985        // Queue up an async operation since the package installation may take a little while.
13986        mHandler.post(new Runnable() {
13987            public void run() {
13988                mHandler.removeCallbacks(this);
13989                 // Result object to be returned
13990                PackageInstalledInfo res = new PackageInstalledInfo();
13991                res.setReturnCode(currentStatus);
13992                res.uid = -1;
13993                res.pkg = null;
13994                res.removedInfo = null;
13995                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13996                    args.doPreInstall(res.returnCode);
13997                    synchronized (mInstallLock) {
13998                        installPackageTracedLI(args, res);
13999                    }
14000                    args.doPostInstall(res.returnCode, res.uid);
14001                }
14002
14003                // A restore should be performed at this point if (a) the install
14004                // succeeded, (b) the operation is not an update, and (c) the new
14005                // package has not opted out of backup participation.
14006                final boolean update = res.removedInfo != null
14007                        && res.removedInfo.removedPackage != null;
14008                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14009                boolean doRestore = !update
14010                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14011
14012                // Set up the post-install work request bookkeeping.  This will be used
14013                // and cleaned up by the post-install event handling regardless of whether
14014                // there's a restore pass performed.  Token values are >= 1.
14015                int token;
14016                if (mNextInstallToken < 0) mNextInstallToken = 1;
14017                token = mNextInstallToken++;
14018
14019                PostInstallData data = new PostInstallData(args, res);
14020                mRunningInstalls.put(token, data);
14021                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14022
14023                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14024                    // Pass responsibility to the Backup Manager.  It will perform a
14025                    // restore if appropriate, then pass responsibility back to the
14026                    // Package Manager to run the post-install observer callbacks
14027                    // and broadcasts.
14028                    IBackupManager bm = IBackupManager.Stub.asInterface(
14029                            ServiceManager.getService(Context.BACKUP_SERVICE));
14030                    if (bm != null) {
14031                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14032                                + " to BM for possible restore");
14033                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14034                        try {
14035                            // TODO: http://b/22388012
14036                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14037                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14038                            } else {
14039                                doRestore = false;
14040                            }
14041                        } catch (RemoteException e) {
14042                            // can't happen; the backup manager is local
14043                        } catch (Exception e) {
14044                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14045                            doRestore = false;
14046                        }
14047                    } else {
14048                        Slog.e(TAG, "Backup Manager not found!");
14049                        doRestore = false;
14050                    }
14051                }
14052
14053                if (!doRestore) {
14054                    // No restore possible, or the Backup Manager was mysteriously not
14055                    // available -- just fire the post-install work request directly.
14056                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14057
14058                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14059
14060                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14061                    mHandler.sendMessage(msg);
14062                }
14063            }
14064        });
14065    }
14066
14067    /**
14068     * Callback from PackageSettings whenever an app is first transitioned out of the
14069     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14070     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14071     * here whether the app is the target of an ongoing install, and only send the
14072     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14073     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14074     * handling.
14075     */
14076    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14077        // Serialize this with the rest of the install-process message chain.  In the
14078        // restore-at-install case, this Runnable will necessarily run before the
14079        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14080        // are coherent.  In the non-restore case, the app has already completed install
14081        // and been launched through some other means, so it is not in a problematic
14082        // state for observers to see the FIRST_LAUNCH signal.
14083        mHandler.post(new Runnable() {
14084            @Override
14085            public void run() {
14086                for (int i = 0; i < mRunningInstalls.size(); i++) {
14087                    final PostInstallData data = mRunningInstalls.valueAt(i);
14088                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14089                        continue;
14090                    }
14091                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14092                        // right package; but is it for the right user?
14093                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14094                            if (userId == data.res.newUsers[uIndex]) {
14095                                if (DEBUG_BACKUP) {
14096                                    Slog.i(TAG, "Package " + pkgName
14097                                            + " being restored so deferring FIRST_LAUNCH");
14098                                }
14099                                return;
14100                            }
14101                        }
14102                    }
14103                }
14104                // didn't find it, so not being restored
14105                if (DEBUG_BACKUP) {
14106                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14107                }
14108                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14109            }
14110        });
14111    }
14112
14113    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14114        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14115                installerPkg, null, userIds);
14116    }
14117
14118    private abstract class HandlerParams {
14119        private static final int MAX_RETRIES = 4;
14120
14121        /**
14122         * Number of times startCopy() has been attempted and had a non-fatal
14123         * error.
14124         */
14125        private int mRetries = 0;
14126
14127        /** User handle for the user requesting the information or installation. */
14128        private final UserHandle mUser;
14129        String traceMethod;
14130        int traceCookie;
14131
14132        HandlerParams(UserHandle user) {
14133            mUser = user;
14134        }
14135
14136        UserHandle getUser() {
14137            return mUser;
14138        }
14139
14140        HandlerParams setTraceMethod(String traceMethod) {
14141            this.traceMethod = traceMethod;
14142            return this;
14143        }
14144
14145        HandlerParams setTraceCookie(int traceCookie) {
14146            this.traceCookie = traceCookie;
14147            return this;
14148        }
14149
14150        final boolean startCopy() {
14151            boolean res;
14152            try {
14153                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14154
14155                if (++mRetries > MAX_RETRIES) {
14156                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14157                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14158                    handleServiceError();
14159                    return false;
14160                } else {
14161                    handleStartCopy();
14162                    res = true;
14163                }
14164            } catch (RemoteException e) {
14165                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14166                mHandler.sendEmptyMessage(MCS_RECONNECT);
14167                res = false;
14168            }
14169            handleReturnCode();
14170            return res;
14171        }
14172
14173        final void serviceError() {
14174            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14175            handleServiceError();
14176            handleReturnCode();
14177        }
14178
14179        abstract void handleStartCopy() throws RemoteException;
14180        abstract void handleServiceError();
14181        abstract void handleReturnCode();
14182    }
14183
14184    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14185        for (File path : paths) {
14186            try {
14187                mcs.clearDirectory(path.getAbsolutePath());
14188            } catch (RemoteException e) {
14189            }
14190        }
14191    }
14192
14193    static class OriginInfo {
14194        /**
14195         * Location where install is coming from, before it has been
14196         * copied/renamed into place. This could be a single monolithic APK
14197         * file, or a cluster directory. This location may be untrusted.
14198         */
14199        final File file;
14200
14201        /**
14202         * Flag indicating that {@link #file} or {@link #cid} has already been
14203         * staged, meaning downstream users don't need to defensively copy the
14204         * contents.
14205         */
14206        final boolean staged;
14207
14208        /**
14209         * Flag indicating that {@link #file} or {@link #cid} is an already
14210         * installed app that is being moved.
14211         */
14212        final boolean existing;
14213
14214        final String resolvedPath;
14215        final File resolvedFile;
14216
14217        static OriginInfo fromNothing() {
14218            return new OriginInfo(null, false, false);
14219        }
14220
14221        static OriginInfo fromUntrustedFile(File file) {
14222            return new OriginInfo(file, false, false);
14223        }
14224
14225        static OriginInfo fromExistingFile(File file) {
14226            return new OriginInfo(file, false, true);
14227        }
14228
14229        static OriginInfo fromStagedFile(File file) {
14230            return new OriginInfo(file, true, false);
14231        }
14232
14233        private OriginInfo(File file, boolean staged, boolean existing) {
14234            this.file = file;
14235            this.staged = staged;
14236            this.existing = existing;
14237
14238            if (file != null) {
14239                resolvedPath = file.getAbsolutePath();
14240                resolvedFile = file;
14241            } else {
14242                resolvedPath = null;
14243                resolvedFile = null;
14244            }
14245        }
14246    }
14247
14248    static class MoveInfo {
14249        final int moveId;
14250        final String fromUuid;
14251        final String toUuid;
14252        final String packageName;
14253        final String dataAppName;
14254        final int appId;
14255        final String seinfo;
14256        final int targetSdkVersion;
14257
14258        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14259                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14260            this.moveId = moveId;
14261            this.fromUuid = fromUuid;
14262            this.toUuid = toUuid;
14263            this.packageName = packageName;
14264            this.dataAppName = dataAppName;
14265            this.appId = appId;
14266            this.seinfo = seinfo;
14267            this.targetSdkVersion = targetSdkVersion;
14268        }
14269    }
14270
14271    static class VerificationInfo {
14272        /** A constant used to indicate that a uid value is not present. */
14273        public static final int NO_UID = -1;
14274
14275        /** URI referencing where the package was downloaded from. */
14276        final Uri originatingUri;
14277
14278        /** HTTP referrer URI associated with the originatingURI. */
14279        final Uri referrer;
14280
14281        /** UID of the application that the install request originated from. */
14282        final int originatingUid;
14283
14284        /** UID of application requesting the install */
14285        final int installerUid;
14286
14287        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14288            this.originatingUri = originatingUri;
14289            this.referrer = referrer;
14290            this.originatingUid = originatingUid;
14291            this.installerUid = installerUid;
14292        }
14293    }
14294
14295    class InstallParams extends HandlerParams {
14296        final OriginInfo origin;
14297        final MoveInfo move;
14298        final IPackageInstallObserver2 observer;
14299        int installFlags;
14300        final String installerPackageName;
14301        final String volumeUuid;
14302        private InstallArgs mArgs;
14303        private int mRet;
14304        final String packageAbiOverride;
14305        final String[] grantedRuntimePermissions;
14306        final VerificationInfo verificationInfo;
14307        final Certificate[][] certificates;
14308        final int installReason;
14309
14310        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14311                int installFlags, String installerPackageName, String volumeUuid,
14312                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14313                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14314            super(user);
14315            this.origin = origin;
14316            this.move = move;
14317            this.observer = observer;
14318            this.installFlags = installFlags;
14319            this.installerPackageName = installerPackageName;
14320            this.volumeUuid = volumeUuid;
14321            this.verificationInfo = verificationInfo;
14322            this.packageAbiOverride = packageAbiOverride;
14323            this.grantedRuntimePermissions = grantedPermissions;
14324            this.certificates = certificates;
14325            this.installReason = installReason;
14326        }
14327
14328        @Override
14329        public String toString() {
14330            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14331                    + " file=" + origin.file + "}";
14332        }
14333
14334        private int installLocationPolicy(PackageInfoLite pkgLite) {
14335            String packageName = pkgLite.packageName;
14336            int installLocation = pkgLite.installLocation;
14337            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14338            // reader
14339            synchronized (mPackages) {
14340                // Currently installed package which the new package is attempting to replace or
14341                // null if no such package is installed.
14342                PackageParser.Package installedPkg = mPackages.get(packageName);
14343                // Package which currently owns the data which the new package will own if installed.
14344                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14345                // will be null whereas dataOwnerPkg will contain information about the package
14346                // which was uninstalled while keeping its data.
14347                PackageParser.Package dataOwnerPkg = installedPkg;
14348                if (dataOwnerPkg  == null) {
14349                    PackageSetting ps = mSettings.mPackages.get(packageName);
14350                    if (ps != null) {
14351                        dataOwnerPkg = ps.pkg;
14352                    }
14353                }
14354
14355                if (dataOwnerPkg != null) {
14356                    // If installed, the package will get access to data left on the device by its
14357                    // predecessor. As a security measure, this is permited only if this is not a
14358                    // version downgrade or if the predecessor package is marked as debuggable and
14359                    // a downgrade is explicitly requested.
14360                    //
14361                    // On debuggable platform builds, downgrades are permitted even for
14362                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14363                    // not offer security guarantees and thus it's OK to disable some security
14364                    // mechanisms to make debugging/testing easier on those builds. However, even on
14365                    // debuggable builds downgrades of packages are permitted only if requested via
14366                    // installFlags. This is because we aim to keep the behavior of debuggable
14367                    // platform builds as close as possible to the behavior of non-debuggable
14368                    // platform builds.
14369                    final boolean downgradeRequested =
14370                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14371                    final boolean packageDebuggable =
14372                                (dataOwnerPkg.applicationInfo.flags
14373                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14374                    final boolean downgradePermitted =
14375                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14376                    if (!downgradePermitted) {
14377                        try {
14378                            checkDowngrade(dataOwnerPkg, pkgLite);
14379                        } catch (PackageManagerException e) {
14380                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14381                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14382                        }
14383                    }
14384                }
14385
14386                if (installedPkg != null) {
14387                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14388                        // Check for updated system application.
14389                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14390                            if (onSd) {
14391                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14392                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14393                            }
14394                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14395                        } else {
14396                            if (onSd) {
14397                                // Install flag overrides everything.
14398                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14399                            }
14400                            // If current upgrade specifies particular preference
14401                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14402                                // Application explicitly specified internal.
14403                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14404                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14405                                // App explictly prefers external. Let policy decide
14406                            } else {
14407                                // Prefer previous location
14408                                if (isExternal(installedPkg)) {
14409                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14410                                }
14411                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14412                            }
14413                        }
14414                    } else {
14415                        // Invalid install. Return error code
14416                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14417                    }
14418                }
14419            }
14420            // All the special cases have been taken care of.
14421            // Return result based on recommended install location.
14422            if (onSd) {
14423                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14424            }
14425            return pkgLite.recommendedInstallLocation;
14426        }
14427
14428        /*
14429         * Invoke remote method to get package information and install
14430         * location values. Override install location based on default
14431         * policy if needed and then create install arguments based
14432         * on the install location.
14433         */
14434        public void handleStartCopy() throws RemoteException {
14435            int ret = PackageManager.INSTALL_SUCCEEDED;
14436
14437            // If we're already staged, we've firmly committed to an install location
14438            if (origin.staged) {
14439                if (origin.file != null) {
14440                    installFlags |= PackageManager.INSTALL_INTERNAL;
14441                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14442                } else {
14443                    throw new IllegalStateException("Invalid stage location");
14444                }
14445            }
14446
14447            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14448            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14449            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14450            PackageInfoLite pkgLite = null;
14451
14452            if (onInt && onSd) {
14453                // Check if both bits are set.
14454                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14455                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14456            } else if (onSd && ephemeral) {
14457                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14458                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14459            } else {
14460                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14461                        packageAbiOverride);
14462
14463                if (DEBUG_EPHEMERAL && ephemeral) {
14464                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14465                }
14466
14467                /*
14468                 * If we have too little free space, try to free cache
14469                 * before giving up.
14470                 */
14471                if (!origin.staged && pkgLite.recommendedInstallLocation
14472                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14473                    // TODO: focus freeing disk space on the target device
14474                    final StorageManager storage = StorageManager.from(mContext);
14475                    final long lowThreshold = storage.getStorageLowBytes(
14476                            Environment.getDataDirectory());
14477
14478                    final long sizeBytes = mContainerService.calculateInstalledSize(
14479                            origin.resolvedPath, packageAbiOverride);
14480
14481                    try {
14482                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14483                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14484                                installFlags, packageAbiOverride);
14485                    } catch (InstallerException e) {
14486                        Slog.w(TAG, "Failed to free cache", e);
14487                    }
14488
14489                    /*
14490                     * The cache free must have deleted the file we
14491                     * downloaded to install.
14492                     *
14493                     * TODO: fix the "freeCache" call to not delete
14494                     *       the file we care about.
14495                     */
14496                    if (pkgLite.recommendedInstallLocation
14497                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14498                        pkgLite.recommendedInstallLocation
14499                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14500                    }
14501                }
14502            }
14503
14504            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14505                int loc = pkgLite.recommendedInstallLocation;
14506                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14507                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14508                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14509                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14510                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14511                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14512                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14513                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14514                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14515                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14516                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14517                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14518                } else {
14519                    // Override with defaults if needed.
14520                    loc = installLocationPolicy(pkgLite);
14521                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14522                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14523                    } else if (!onSd && !onInt) {
14524                        // Override install location with flags
14525                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14526                            // Set the flag to install on external media.
14527                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14528                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14529                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14530                            if (DEBUG_EPHEMERAL) {
14531                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14532                            }
14533                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14534                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14535                                    |PackageManager.INSTALL_INTERNAL);
14536                        } else {
14537                            // Make sure the flag for installing on external
14538                            // media is unset
14539                            installFlags |= PackageManager.INSTALL_INTERNAL;
14540                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14541                        }
14542                    }
14543                }
14544            }
14545
14546            final InstallArgs args = createInstallArgs(this);
14547            mArgs = args;
14548
14549            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14550                // TODO: http://b/22976637
14551                // Apps installed for "all" users use the device owner to verify the app
14552                UserHandle verifierUser = getUser();
14553                if (verifierUser == UserHandle.ALL) {
14554                    verifierUser = UserHandle.SYSTEM;
14555                }
14556
14557                /*
14558                 * Determine if we have any installed package verifiers. If we
14559                 * do, then we'll defer to them to verify the packages.
14560                 */
14561                final int requiredUid = mRequiredVerifierPackage == null ? -1
14562                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14563                                verifierUser.getIdentifier());
14564                final int installerUid =
14565                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14566                if (!origin.existing && requiredUid != -1
14567                        && isVerificationEnabled(
14568                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14569                    final Intent verification = new Intent(
14570                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14571                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14572                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14573                            PACKAGE_MIME_TYPE);
14574                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14575
14576                    // Query all live verifiers based on current user state
14577                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14578                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14579                            false /*allowDynamicSplits*/);
14580
14581                    if (DEBUG_VERIFY) {
14582                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14583                                + verification.toString() + " with " + pkgLite.verifiers.length
14584                                + " optional verifiers");
14585                    }
14586
14587                    final int verificationId = mPendingVerificationToken++;
14588
14589                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14590
14591                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14592                            installerPackageName);
14593
14594                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14595                            installFlags);
14596
14597                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14598                            pkgLite.packageName);
14599
14600                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14601                            pkgLite.versionCode);
14602
14603                    if (verificationInfo != null) {
14604                        if (verificationInfo.originatingUri != null) {
14605                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14606                                    verificationInfo.originatingUri);
14607                        }
14608                        if (verificationInfo.referrer != null) {
14609                            verification.putExtra(Intent.EXTRA_REFERRER,
14610                                    verificationInfo.referrer);
14611                        }
14612                        if (verificationInfo.originatingUid >= 0) {
14613                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14614                                    verificationInfo.originatingUid);
14615                        }
14616                        if (verificationInfo.installerUid >= 0) {
14617                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14618                                    verificationInfo.installerUid);
14619                        }
14620                    }
14621
14622                    final PackageVerificationState verificationState = new PackageVerificationState(
14623                            requiredUid, args);
14624
14625                    mPendingVerification.append(verificationId, verificationState);
14626
14627                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14628                            receivers, verificationState);
14629
14630                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14631                    final long idleDuration = getVerificationTimeout();
14632
14633                    /*
14634                     * If any sufficient verifiers were listed in the package
14635                     * manifest, attempt to ask them.
14636                     */
14637                    if (sufficientVerifiers != null) {
14638                        final int N = sufficientVerifiers.size();
14639                        if (N == 0) {
14640                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14641                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14642                        } else {
14643                            for (int i = 0; i < N; i++) {
14644                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14645                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14646                                        verifierComponent.getPackageName(), idleDuration,
14647                                        verifierUser.getIdentifier(), false, "package verifier");
14648
14649                                final Intent sufficientIntent = new Intent(verification);
14650                                sufficientIntent.setComponent(verifierComponent);
14651                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14652                            }
14653                        }
14654                    }
14655
14656                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14657                            mRequiredVerifierPackage, receivers);
14658                    if (ret == PackageManager.INSTALL_SUCCEEDED
14659                            && mRequiredVerifierPackage != null) {
14660                        Trace.asyncTraceBegin(
14661                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14662                        /*
14663                         * Send the intent to the required verification agent,
14664                         * but only start the verification timeout after the
14665                         * target BroadcastReceivers have run.
14666                         */
14667                        verification.setComponent(requiredVerifierComponent);
14668                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14669                                mRequiredVerifierPackage, idleDuration,
14670                                verifierUser.getIdentifier(), false, "package verifier");
14671                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14672                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14673                                new BroadcastReceiver() {
14674                                    @Override
14675                                    public void onReceive(Context context, Intent intent) {
14676                                        final Message msg = mHandler
14677                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14678                                        msg.arg1 = verificationId;
14679                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14680                                    }
14681                                }, null, 0, null, null);
14682
14683                        /*
14684                         * We don't want the copy to proceed until verification
14685                         * succeeds, so null out this field.
14686                         */
14687                        mArgs = null;
14688                    }
14689                } else {
14690                    /*
14691                     * No package verification is enabled, so immediately start
14692                     * the remote call to initiate copy using temporary file.
14693                     */
14694                    ret = args.copyApk(mContainerService, true);
14695                }
14696            }
14697
14698            mRet = ret;
14699        }
14700
14701        @Override
14702        void handleReturnCode() {
14703            // If mArgs is null, then MCS couldn't be reached. When it
14704            // reconnects, it will try again to install. At that point, this
14705            // will succeed.
14706            if (mArgs != null) {
14707                processPendingInstall(mArgs, mRet);
14708            }
14709        }
14710
14711        @Override
14712        void handleServiceError() {
14713            mArgs = createInstallArgs(this);
14714            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14715        }
14716    }
14717
14718    private InstallArgs createInstallArgs(InstallParams params) {
14719        if (params.move != null) {
14720            return new MoveInstallArgs(params);
14721        } else {
14722            return new FileInstallArgs(params);
14723        }
14724    }
14725
14726    /**
14727     * Create args that describe an existing installed package. Typically used
14728     * when cleaning up old installs, or used as a move source.
14729     */
14730    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14731            String resourcePath, String[] instructionSets) {
14732        return new FileInstallArgs(codePath, resourcePath, instructionSets);
14733    }
14734
14735    static abstract class InstallArgs {
14736        /** @see InstallParams#origin */
14737        final OriginInfo origin;
14738        /** @see InstallParams#move */
14739        final MoveInfo move;
14740
14741        final IPackageInstallObserver2 observer;
14742        // Always refers to PackageManager flags only
14743        final int installFlags;
14744        final String installerPackageName;
14745        final String volumeUuid;
14746        final UserHandle user;
14747        final String abiOverride;
14748        final String[] installGrantPermissions;
14749        /** If non-null, drop an async trace when the install completes */
14750        final String traceMethod;
14751        final int traceCookie;
14752        final Certificate[][] certificates;
14753        final int installReason;
14754
14755        // The list of instruction sets supported by this app. This is currently
14756        // only used during the rmdex() phase to clean up resources. We can get rid of this
14757        // if we move dex files under the common app path.
14758        /* nullable */ String[] instructionSets;
14759
14760        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14761                int installFlags, String installerPackageName, String volumeUuid,
14762                UserHandle user, String[] instructionSets,
14763                String abiOverride, String[] installGrantPermissions,
14764                String traceMethod, int traceCookie, Certificate[][] certificates,
14765                int installReason) {
14766            this.origin = origin;
14767            this.move = move;
14768            this.installFlags = installFlags;
14769            this.observer = observer;
14770            this.installerPackageName = installerPackageName;
14771            this.volumeUuid = volumeUuid;
14772            this.user = user;
14773            this.instructionSets = instructionSets;
14774            this.abiOverride = abiOverride;
14775            this.installGrantPermissions = installGrantPermissions;
14776            this.traceMethod = traceMethod;
14777            this.traceCookie = traceCookie;
14778            this.certificates = certificates;
14779            this.installReason = installReason;
14780        }
14781
14782        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14783        abstract int doPreInstall(int status);
14784
14785        /**
14786         * Rename package into final resting place. All paths on the given
14787         * scanned package should be updated to reflect the rename.
14788         */
14789        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14790        abstract int doPostInstall(int status, int uid);
14791
14792        /** @see PackageSettingBase#codePathString */
14793        abstract String getCodePath();
14794        /** @see PackageSettingBase#resourcePathString */
14795        abstract String getResourcePath();
14796
14797        // Need installer lock especially for dex file removal.
14798        abstract void cleanUpResourcesLI();
14799        abstract boolean doPostDeleteLI(boolean delete);
14800
14801        /**
14802         * Called before the source arguments are copied. This is used mostly
14803         * for MoveParams when it needs to read the source file to put it in the
14804         * destination.
14805         */
14806        int doPreCopy() {
14807            return PackageManager.INSTALL_SUCCEEDED;
14808        }
14809
14810        /**
14811         * Called after the source arguments are copied. This is used mostly for
14812         * MoveParams when it needs to read the source file to put it in the
14813         * destination.
14814         */
14815        int doPostCopy(int uid) {
14816            return PackageManager.INSTALL_SUCCEEDED;
14817        }
14818
14819        protected boolean isFwdLocked() {
14820            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14821        }
14822
14823        protected boolean isExternalAsec() {
14824            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14825        }
14826
14827        protected boolean isEphemeral() {
14828            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14829        }
14830
14831        UserHandle getUser() {
14832            return user;
14833        }
14834    }
14835
14836    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14837        if (!allCodePaths.isEmpty()) {
14838            if (instructionSets == null) {
14839                throw new IllegalStateException("instructionSet == null");
14840            }
14841            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14842            for (String codePath : allCodePaths) {
14843                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14844                    try {
14845                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14846                    } catch (InstallerException ignored) {
14847                    }
14848                }
14849            }
14850        }
14851    }
14852
14853    /**
14854     * Logic to handle installation of non-ASEC applications, including copying
14855     * and renaming logic.
14856     */
14857    class FileInstallArgs extends InstallArgs {
14858        private File codeFile;
14859        private File resourceFile;
14860
14861        // Example topology:
14862        // /data/app/com.example/base.apk
14863        // /data/app/com.example/split_foo.apk
14864        // /data/app/com.example/lib/arm/libfoo.so
14865        // /data/app/com.example/lib/arm64/libfoo.so
14866        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14867
14868        /** New install */
14869        FileInstallArgs(InstallParams params) {
14870            super(params.origin, params.move, params.observer, params.installFlags,
14871                    params.installerPackageName, params.volumeUuid,
14872                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14873                    params.grantedRuntimePermissions,
14874                    params.traceMethod, params.traceCookie, params.certificates,
14875                    params.installReason);
14876            if (isFwdLocked()) {
14877                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14878            }
14879        }
14880
14881        /** Existing install */
14882        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14883            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14884                    null, null, null, 0, null /*certificates*/,
14885                    PackageManager.INSTALL_REASON_UNKNOWN);
14886            this.codeFile = (codePath != null) ? new File(codePath) : null;
14887            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14888        }
14889
14890        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14891            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14892            try {
14893                return doCopyApk(imcs, temp);
14894            } finally {
14895                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14896            }
14897        }
14898
14899        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14900            if (origin.staged) {
14901                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14902                codeFile = origin.file;
14903                resourceFile = origin.file;
14904                return PackageManager.INSTALL_SUCCEEDED;
14905            }
14906
14907            try {
14908                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14909                final File tempDir =
14910                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14911                codeFile = tempDir;
14912                resourceFile = tempDir;
14913            } catch (IOException e) {
14914                Slog.w(TAG, "Failed to create copy file: " + e);
14915                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14916            }
14917
14918            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14919                @Override
14920                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14921                    if (!FileUtils.isValidExtFilename(name)) {
14922                        throw new IllegalArgumentException("Invalid filename: " + name);
14923                    }
14924                    try {
14925                        final File file = new File(codeFile, name);
14926                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14927                                O_RDWR | O_CREAT, 0644);
14928                        Os.chmod(file.getAbsolutePath(), 0644);
14929                        return new ParcelFileDescriptor(fd);
14930                    } catch (ErrnoException e) {
14931                        throw new RemoteException("Failed to open: " + e.getMessage());
14932                    }
14933                }
14934            };
14935
14936            int ret = PackageManager.INSTALL_SUCCEEDED;
14937            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14938            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14939                Slog.e(TAG, "Failed to copy package");
14940                return ret;
14941            }
14942
14943            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14944            NativeLibraryHelper.Handle handle = null;
14945            try {
14946                handle = NativeLibraryHelper.Handle.create(codeFile);
14947                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14948                        abiOverride);
14949            } catch (IOException e) {
14950                Slog.e(TAG, "Copying native libraries failed", e);
14951                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14952            } finally {
14953                IoUtils.closeQuietly(handle);
14954            }
14955
14956            return ret;
14957        }
14958
14959        int doPreInstall(int status) {
14960            if (status != PackageManager.INSTALL_SUCCEEDED) {
14961                cleanUp();
14962            }
14963            return status;
14964        }
14965
14966        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14967            if (status != PackageManager.INSTALL_SUCCEEDED) {
14968                cleanUp();
14969                return false;
14970            }
14971
14972            final File targetDir = codeFile.getParentFile();
14973            final File beforeCodeFile = codeFile;
14974            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14975
14976            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14977            try {
14978                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14979            } catch (ErrnoException e) {
14980                Slog.w(TAG, "Failed to rename", e);
14981                return false;
14982            }
14983
14984            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14985                Slog.w(TAG, "Failed to restorecon");
14986                return false;
14987            }
14988
14989            // Reflect the rename internally
14990            codeFile = afterCodeFile;
14991            resourceFile = afterCodeFile;
14992
14993            // Reflect the rename in scanned details
14994            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14995            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14996                    afterCodeFile, pkg.baseCodePath));
14997            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14998                    afterCodeFile, pkg.splitCodePaths));
14999
15000            // Reflect the rename in app info
15001            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15002            pkg.setApplicationInfoCodePath(pkg.codePath);
15003            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15004            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15005            pkg.setApplicationInfoResourcePath(pkg.codePath);
15006            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15007            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15008
15009            return true;
15010        }
15011
15012        int doPostInstall(int status, int uid) {
15013            if (status != PackageManager.INSTALL_SUCCEEDED) {
15014                cleanUp();
15015            }
15016            return status;
15017        }
15018
15019        @Override
15020        String getCodePath() {
15021            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15022        }
15023
15024        @Override
15025        String getResourcePath() {
15026            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15027        }
15028
15029        private boolean cleanUp() {
15030            if (codeFile == null || !codeFile.exists()) {
15031                return false;
15032            }
15033
15034            removeCodePathLI(codeFile);
15035
15036            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15037                resourceFile.delete();
15038            }
15039
15040            return true;
15041        }
15042
15043        void cleanUpResourcesLI() {
15044            // Try enumerating all code paths before deleting
15045            List<String> allCodePaths = Collections.EMPTY_LIST;
15046            if (codeFile != null && codeFile.exists()) {
15047                try {
15048                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15049                    allCodePaths = pkg.getAllCodePaths();
15050                } catch (PackageParserException e) {
15051                    // Ignored; we tried our best
15052                }
15053            }
15054
15055            cleanUp();
15056            removeDexFiles(allCodePaths, instructionSets);
15057        }
15058
15059        boolean doPostDeleteLI(boolean delete) {
15060            // XXX err, shouldn't we respect the delete flag?
15061            cleanUpResourcesLI();
15062            return true;
15063        }
15064    }
15065
15066    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15067            PackageManagerException {
15068        if (copyRet < 0) {
15069            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15070                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15071                throw new PackageManagerException(copyRet, message);
15072            }
15073        }
15074    }
15075
15076    /**
15077     * Extract the StorageManagerService "container ID" from the full code path of an
15078     * .apk.
15079     */
15080    static String cidFromCodePath(String fullCodePath) {
15081        int eidx = fullCodePath.lastIndexOf("/");
15082        String subStr1 = fullCodePath.substring(0, eidx);
15083        int sidx = subStr1.lastIndexOf("/");
15084        return subStr1.substring(sidx+1, eidx);
15085    }
15086
15087    /**
15088     * Logic to handle movement of existing installed applications.
15089     */
15090    class MoveInstallArgs extends InstallArgs {
15091        private File codeFile;
15092        private File resourceFile;
15093
15094        /** New install */
15095        MoveInstallArgs(InstallParams params) {
15096            super(params.origin, params.move, params.observer, params.installFlags,
15097                    params.installerPackageName, params.volumeUuid,
15098                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15099                    params.grantedRuntimePermissions,
15100                    params.traceMethod, params.traceCookie, params.certificates,
15101                    params.installReason);
15102        }
15103
15104        int copyApk(IMediaContainerService imcs, boolean temp) {
15105            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15106                    + move.fromUuid + " to " + move.toUuid);
15107            synchronized (mInstaller) {
15108                try {
15109                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15110                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15111                } catch (InstallerException e) {
15112                    Slog.w(TAG, "Failed to move app", e);
15113                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15114                }
15115            }
15116
15117            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15118            resourceFile = codeFile;
15119            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15120
15121            return PackageManager.INSTALL_SUCCEEDED;
15122        }
15123
15124        int doPreInstall(int status) {
15125            if (status != PackageManager.INSTALL_SUCCEEDED) {
15126                cleanUp(move.toUuid);
15127            }
15128            return status;
15129        }
15130
15131        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15132            if (status != PackageManager.INSTALL_SUCCEEDED) {
15133                cleanUp(move.toUuid);
15134                return false;
15135            }
15136
15137            // Reflect the move in app info
15138            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15139            pkg.setApplicationInfoCodePath(pkg.codePath);
15140            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15141            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15142            pkg.setApplicationInfoResourcePath(pkg.codePath);
15143            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15144            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15145
15146            return true;
15147        }
15148
15149        int doPostInstall(int status, int uid) {
15150            if (status == PackageManager.INSTALL_SUCCEEDED) {
15151                cleanUp(move.fromUuid);
15152            } else {
15153                cleanUp(move.toUuid);
15154            }
15155            return status;
15156        }
15157
15158        @Override
15159        String getCodePath() {
15160            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15161        }
15162
15163        @Override
15164        String getResourcePath() {
15165            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15166        }
15167
15168        private boolean cleanUp(String volumeUuid) {
15169            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15170                    move.dataAppName);
15171            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15172            final int[] userIds = sUserManager.getUserIds();
15173            synchronized (mInstallLock) {
15174                // Clean up both app data and code
15175                // All package moves are frozen until finished
15176                for (int userId : userIds) {
15177                    try {
15178                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15179                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15180                    } catch (InstallerException e) {
15181                        Slog.w(TAG, String.valueOf(e));
15182                    }
15183                }
15184                removeCodePathLI(codeFile);
15185            }
15186            return true;
15187        }
15188
15189        void cleanUpResourcesLI() {
15190            throw new UnsupportedOperationException();
15191        }
15192
15193        boolean doPostDeleteLI(boolean delete) {
15194            throw new UnsupportedOperationException();
15195        }
15196    }
15197
15198    static String getAsecPackageName(String packageCid) {
15199        int idx = packageCid.lastIndexOf("-");
15200        if (idx == -1) {
15201            return packageCid;
15202        }
15203        return packageCid.substring(0, idx);
15204    }
15205
15206    // Utility method used to create code paths based on package name and available index.
15207    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15208        String idxStr = "";
15209        int idx = 1;
15210        // Fall back to default value of idx=1 if prefix is not
15211        // part of oldCodePath
15212        if (oldCodePath != null) {
15213            String subStr = oldCodePath;
15214            // Drop the suffix right away
15215            if (suffix != null && subStr.endsWith(suffix)) {
15216                subStr = subStr.substring(0, subStr.length() - suffix.length());
15217            }
15218            // If oldCodePath already contains prefix find out the
15219            // ending index to either increment or decrement.
15220            int sidx = subStr.lastIndexOf(prefix);
15221            if (sidx != -1) {
15222                subStr = subStr.substring(sidx + prefix.length());
15223                if (subStr != null) {
15224                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15225                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15226                    }
15227                    try {
15228                        idx = Integer.parseInt(subStr);
15229                        if (idx <= 1) {
15230                            idx++;
15231                        } else {
15232                            idx--;
15233                        }
15234                    } catch(NumberFormatException e) {
15235                    }
15236                }
15237            }
15238        }
15239        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15240        return prefix + idxStr;
15241    }
15242
15243    private File getNextCodePath(File targetDir, String packageName) {
15244        File result;
15245        SecureRandom random = new SecureRandom();
15246        byte[] bytes = new byte[16];
15247        do {
15248            random.nextBytes(bytes);
15249            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15250            result = new File(targetDir, packageName + "-" + suffix);
15251        } while (result.exists());
15252        return result;
15253    }
15254
15255    // Utility method that returns the relative package path with respect
15256    // to the installation directory. Like say for /data/data/com.test-1.apk
15257    // string com.test-1 is returned.
15258    static String deriveCodePathName(String codePath) {
15259        if (codePath == null) {
15260            return null;
15261        }
15262        final File codeFile = new File(codePath);
15263        final String name = codeFile.getName();
15264        if (codeFile.isDirectory()) {
15265            return name;
15266        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15267            final int lastDot = name.lastIndexOf('.');
15268            return name.substring(0, lastDot);
15269        } else {
15270            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15271            return null;
15272        }
15273    }
15274
15275    static class PackageInstalledInfo {
15276        String name;
15277        int uid;
15278        // The set of users that originally had this package installed.
15279        int[] origUsers;
15280        // The set of users that now have this package installed.
15281        int[] newUsers;
15282        PackageParser.Package pkg;
15283        int returnCode;
15284        String returnMsg;
15285        String installerPackageName;
15286        PackageRemovedInfo removedInfo;
15287        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15288
15289        public void setError(int code, String msg) {
15290            setReturnCode(code);
15291            setReturnMessage(msg);
15292            Slog.w(TAG, msg);
15293        }
15294
15295        public void setError(String msg, PackageParserException e) {
15296            setReturnCode(e.error);
15297            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15298            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15299            for (int i = 0; i < childCount; i++) {
15300                addedChildPackages.valueAt(i).setError(msg, e);
15301            }
15302            Slog.w(TAG, msg, e);
15303        }
15304
15305        public void setError(String msg, PackageManagerException e) {
15306            returnCode = e.error;
15307            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15308            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15309            for (int i = 0; i < childCount; i++) {
15310                addedChildPackages.valueAt(i).setError(msg, e);
15311            }
15312            Slog.w(TAG, msg, e);
15313        }
15314
15315        public void setReturnCode(int returnCode) {
15316            this.returnCode = returnCode;
15317            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15318            for (int i = 0; i < childCount; i++) {
15319                addedChildPackages.valueAt(i).returnCode = returnCode;
15320            }
15321        }
15322
15323        private void setReturnMessage(String returnMsg) {
15324            this.returnMsg = returnMsg;
15325            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15326            for (int i = 0; i < childCount; i++) {
15327                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15328            }
15329        }
15330
15331        // In some error cases we want to convey more info back to the observer
15332        String origPackage;
15333        String origPermission;
15334    }
15335
15336    /*
15337     * Install a non-existing package.
15338     */
15339    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15340            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15341            PackageInstalledInfo res, int installReason) {
15342        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15343
15344        // Remember this for later, in case we need to rollback this install
15345        String pkgName = pkg.packageName;
15346
15347        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15348
15349        synchronized(mPackages) {
15350            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15351            if (renamedPackage != null) {
15352                // A package with the same name is already installed, though
15353                // it has been renamed to an older name.  The package we
15354                // are trying to install should be installed as an update to
15355                // the existing one, but that has not been requested, so bail.
15356                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15357                        + " without first uninstalling package running as "
15358                        + renamedPackage);
15359                return;
15360            }
15361            if (mPackages.containsKey(pkgName)) {
15362                // Don't allow installation over an existing package with the same name.
15363                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15364                        + " without first uninstalling.");
15365                return;
15366            }
15367        }
15368
15369        try {
15370            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15371                    System.currentTimeMillis(), user);
15372
15373            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15374
15375            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15376                prepareAppDataAfterInstallLIF(newPackage);
15377
15378            } else {
15379                // Remove package from internal structures, but keep around any
15380                // data that might have already existed
15381                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15382                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15383            }
15384        } catch (PackageManagerException e) {
15385            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15386        }
15387
15388        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15389    }
15390
15391    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15392        try (DigestInputStream digestStream =
15393                new DigestInputStream(new FileInputStream(file), digest)) {
15394            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15395        }
15396    }
15397
15398    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15399            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15400            int installReason) {
15401        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15402
15403        final PackageParser.Package oldPackage;
15404        final PackageSetting ps;
15405        final String pkgName = pkg.packageName;
15406        final int[] allUsers;
15407        final int[] installedUsers;
15408
15409        synchronized(mPackages) {
15410            oldPackage = mPackages.get(pkgName);
15411            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15412
15413            // don't allow upgrade to target a release SDK from a pre-release SDK
15414            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15415                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15416            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15417                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15418            if (oldTargetsPreRelease
15419                    && !newTargetsPreRelease
15420                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15421                Slog.w(TAG, "Can't install package targeting released sdk");
15422                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15423                return;
15424            }
15425
15426            ps = mSettings.mPackages.get(pkgName);
15427
15428            // verify signatures are valid
15429            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15430            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15431                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15432                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15433                            "New package not signed by keys specified by upgrade-keysets: "
15434                                    + pkgName);
15435                    return;
15436                }
15437            } else {
15438                // default to original signature matching
15439                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15440                        != PackageManager.SIGNATURE_MATCH) {
15441                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15442                            "New package has a different signature: " + pkgName);
15443                    return;
15444                }
15445            }
15446
15447            // don't allow a system upgrade unless the upgrade hash matches
15448            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15449                byte[] digestBytes = null;
15450                try {
15451                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15452                    updateDigest(digest, new File(pkg.baseCodePath));
15453                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15454                        for (String path : pkg.splitCodePaths) {
15455                            updateDigest(digest, new File(path));
15456                        }
15457                    }
15458                    digestBytes = digest.digest();
15459                } catch (NoSuchAlgorithmException | IOException e) {
15460                    res.setError(INSTALL_FAILED_INVALID_APK,
15461                            "Could not compute hash: " + pkgName);
15462                    return;
15463                }
15464                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15465                    res.setError(INSTALL_FAILED_INVALID_APK,
15466                            "New package fails restrict-update check: " + pkgName);
15467                    return;
15468                }
15469                // retain upgrade restriction
15470                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15471            }
15472
15473            // Check for shared user id changes
15474            String invalidPackageName =
15475                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15476            if (invalidPackageName != null) {
15477                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15478                        "Package " + invalidPackageName + " tried to change user "
15479                                + oldPackage.mSharedUserId);
15480                return;
15481            }
15482
15483            // In case of rollback, remember per-user/profile install state
15484            allUsers = sUserManager.getUserIds();
15485            installedUsers = ps.queryInstalledUsers(allUsers, true);
15486
15487            // don't allow an upgrade from full to ephemeral
15488            if (isInstantApp) {
15489                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15490                    for (int currentUser : allUsers) {
15491                        if (!ps.getInstantApp(currentUser)) {
15492                            // can't downgrade from full to instant
15493                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15494                                    + " for user: " + currentUser);
15495                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15496                            return;
15497                        }
15498                    }
15499                } else if (!ps.getInstantApp(user.getIdentifier())) {
15500                    // can't downgrade from full to instant
15501                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15502                            + " for user: " + user.getIdentifier());
15503                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15504                    return;
15505                }
15506            }
15507        }
15508
15509        // Update what is removed
15510        res.removedInfo = new PackageRemovedInfo(this);
15511        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15512        res.removedInfo.removedPackage = oldPackage.packageName;
15513        res.removedInfo.installerPackageName = ps.installerPackageName;
15514        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15515        res.removedInfo.isUpdate = true;
15516        res.removedInfo.origUsers = installedUsers;
15517        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15518        for (int i = 0; i < installedUsers.length; i++) {
15519            final int userId = installedUsers[i];
15520            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15521        }
15522
15523        final int childCount = (oldPackage.childPackages != null)
15524                ? oldPackage.childPackages.size() : 0;
15525        for (int i = 0; i < childCount; i++) {
15526            boolean childPackageUpdated = false;
15527            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15528            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15529            if (res.addedChildPackages != null) {
15530                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15531                if (childRes != null) {
15532                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15533                    childRes.removedInfo.removedPackage = childPkg.packageName;
15534                    if (childPs != null) {
15535                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15536                    }
15537                    childRes.removedInfo.isUpdate = true;
15538                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15539                    childPackageUpdated = true;
15540                }
15541            }
15542            if (!childPackageUpdated) {
15543                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15544                childRemovedRes.removedPackage = childPkg.packageName;
15545                if (childPs != null) {
15546                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15547                }
15548                childRemovedRes.isUpdate = false;
15549                childRemovedRes.dataRemoved = true;
15550                synchronized (mPackages) {
15551                    if (childPs != null) {
15552                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15553                    }
15554                }
15555                if (res.removedInfo.removedChildPackages == null) {
15556                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15557                }
15558                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15559            }
15560        }
15561
15562        boolean sysPkg = (isSystemApp(oldPackage));
15563        if (sysPkg) {
15564            // Set the system/privileged/oem flags as needed
15565            final boolean privileged =
15566                    (oldPackage.applicationInfo.privateFlags
15567                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15568            final boolean oem =
15569                    (oldPackage.applicationInfo.privateFlags
15570                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15571            final int systemPolicyFlags = policyFlags
15572                    | PackageParser.PARSE_IS_SYSTEM
15573                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
15574                    | (oem ? PARSE_IS_OEM : 0);
15575
15576            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15577                    user, allUsers, installerPackageName, res, installReason);
15578        } else {
15579            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15580                    user, allUsers, installerPackageName, res, installReason);
15581        }
15582    }
15583
15584    @Override
15585    public List<String> getPreviousCodePaths(String packageName) {
15586        final int callingUid = Binder.getCallingUid();
15587        final List<String> result = new ArrayList<>();
15588        if (getInstantAppPackageName(callingUid) != null) {
15589            return result;
15590        }
15591        final PackageSetting ps = mSettings.mPackages.get(packageName);
15592        if (ps != null
15593                && ps.oldCodePaths != null
15594                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15595            result.addAll(ps.oldCodePaths);
15596        }
15597        return result;
15598    }
15599
15600    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15601            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15602            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15603            int installReason) {
15604        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15605                + deletedPackage);
15606
15607        String pkgName = deletedPackage.packageName;
15608        boolean deletedPkg = true;
15609        boolean addedPkg = false;
15610        boolean updatedSettings = false;
15611        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15612        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15613                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15614
15615        final long origUpdateTime = (pkg.mExtras != null)
15616                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15617
15618        // First delete the existing package while retaining the data directory
15619        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15620                res.removedInfo, true, pkg)) {
15621            // If the existing package wasn't successfully deleted
15622            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15623            deletedPkg = false;
15624        } else {
15625            // Successfully deleted the old package; proceed with replace.
15626
15627            // If deleted package lived in a container, give users a chance to
15628            // relinquish resources before killing.
15629            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15630                if (DEBUG_INSTALL) {
15631                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15632                }
15633                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15634                final ArrayList<String> pkgList = new ArrayList<String>(1);
15635                pkgList.add(deletedPackage.applicationInfo.packageName);
15636                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15637            }
15638
15639            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15640                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15641            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15642
15643            try {
15644                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15645                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15646                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15647                        installReason);
15648
15649                // Update the in-memory copy of the previous code paths.
15650                PackageSetting ps = mSettings.mPackages.get(pkgName);
15651                if (!killApp) {
15652                    if (ps.oldCodePaths == null) {
15653                        ps.oldCodePaths = new ArraySet<>();
15654                    }
15655                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15656                    if (deletedPackage.splitCodePaths != null) {
15657                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15658                    }
15659                } else {
15660                    ps.oldCodePaths = null;
15661                }
15662                if (ps.childPackageNames != null) {
15663                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15664                        final String childPkgName = ps.childPackageNames.get(i);
15665                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15666                        childPs.oldCodePaths = ps.oldCodePaths;
15667                    }
15668                }
15669                // set instant app status, but, only if it's explicitly specified
15670                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15671                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15672                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15673                prepareAppDataAfterInstallLIF(newPackage);
15674                addedPkg = true;
15675                mDexManager.notifyPackageUpdated(newPackage.packageName,
15676                        newPackage.baseCodePath, newPackage.splitCodePaths);
15677            } catch (PackageManagerException e) {
15678                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15679            }
15680        }
15681
15682        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15683            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15684
15685            // Revert all internal state mutations and added folders for the failed install
15686            if (addedPkg) {
15687                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15688                        res.removedInfo, true, null);
15689            }
15690
15691            // Restore the old package
15692            if (deletedPkg) {
15693                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15694                File restoreFile = new File(deletedPackage.codePath);
15695                // Parse old package
15696                boolean oldExternal = isExternal(deletedPackage);
15697                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15698                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15699                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15700                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15701                try {
15702                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15703                            null);
15704                } catch (PackageManagerException e) {
15705                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15706                            + e.getMessage());
15707                    return;
15708                }
15709
15710                synchronized (mPackages) {
15711                    // Ensure the installer package name up to date
15712                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15713
15714                    // Update permissions for restored package
15715                    mPermissionManager.updatePermissions(
15716                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15717                            mPermissionCallback);
15718
15719                    mSettings.writeLPr();
15720                }
15721
15722                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15723            }
15724        } else {
15725            synchronized (mPackages) {
15726                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15727                if (ps != null) {
15728                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15729                    if (res.removedInfo.removedChildPackages != null) {
15730                        final int childCount = res.removedInfo.removedChildPackages.size();
15731                        // Iterate in reverse as we may modify the collection
15732                        for (int i = childCount - 1; i >= 0; i--) {
15733                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15734                            if (res.addedChildPackages.containsKey(childPackageName)) {
15735                                res.removedInfo.removedChildPackages.removeAt(i);
15736                            } else {
15737                                PackageRemovedInfo childInfo = res.removedInfo
15738                                        .removedChildPackages.valueAt(i);
15739                                childInfo.removedForAllUsers = mPackages.get(
15740                                        childInfo.removedPackage) == null;
15741                            }
15742                        }
15743                    }
15744                }
15745            }
15746        }
15747    }
15748
15749    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15750            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15751            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15752            int installReason) {
15753        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15754                + ", old=" + deletedPackage);
15755
15756        final boolean disabledSystem;
15757
15758        // Remove existing system package
15759        removePackageLI(deletedPackage, true);
15760
15761        synchronized (mPackages) {
15762            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15763        }
15764        if (!disabledSystem) {
15765            // We didn't need to disable the .apk as a current system package,
15766            // which means we are replacing another update that is already
15767            // installed.  We need to make sure to delete the older one's .apk.
15768            res.removedInfo.args = createInstallArgsForExisting(0,
15769                    deletedPackage.applicationInfo.getCodePath(),
15770                    deletedPackage.applicationInfo.getResourcePath(),
15771                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15772        } else {
15773            res.removedInfo.args = null;
15774        }
15775
15776        // Successfully disabled the old package. Now proceed with re-installation
15777        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15778                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15779        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15780
15781        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15782        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15783                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15784
15785        PackageParser.Package newPackage = null;
15786        try {
15787            // Add the package to the internal data structures
15788            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
15789
15790            // Set the update and install times
15791            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15792            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15793                    System.currentTimeMillis());
15794
15795            // Update the package dynamic state if succeeded
15796            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15797                // Now that the install succeeded make sure we remove data
15798                // directories for any child package the update removed.
15799                final int deletedChildCount = (deletedPackage.childPackages != null)
15800                        ? deletedPackage.childPackages.size() : 0;
15801                final int newChildCount = (newPackage.childPackages != null)
15802                        ? newPackage.childPackages.size() : 0;
15803                for (int i = 0; i < deletedChildCount; i++) {
15804                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15805                    boolean childPackageDeleted = true;
15806                    for (int j = 0; j < newChildCount; j++) {
15807                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15808                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15809                            childPackageDeleted = false;
15810                            break;
15811                        }
15812                    }
15813                    if (childPackageDeleted) {
15814                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15815                                deletedChildPkg.packageName);
15816                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15817                            PackageRemovedInfo removedChildRes = res.removedInfo
15818                                    .removedChildPackages.get(deletedChildPkg.packageName);
15819                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15820                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15821                        }
15822                    }
15823                }
15824
15825                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15826                        installReason);
15827                prepareAppDataAfterInstallLIF(newPackage);
15828
15829                mDexManager.notifyPackageUpdated(newPackage.packageName,
15830                            newPackage.baseCodePath, newPackage.splitCodePaths);
15831            }
15832        } catch (PackageManagerException e) {
15833            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15834            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15835        }
15836
15837        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15838            // Re installation failed. Restore old information
15839            // Remove new pkg information
15840            if (newPackage != null) {
15841                removeInstalledPackageLI(newPackage, true);
15842            }
15843            // Add back the old system package
15844            try {
15845                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15846            } catch (PackageManagerException e) {
15847                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15848            }
15849
15850            synchronized (mPackages) {
15851                if (disabledSystem) {
15852                    enableSystemPackageLPw(deletedPackage);
15853                }
15854
15855                // Ensure the installer package name up to date
15856                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15857
15858                // Update permissions for restored package
15859                mPermissionManager.updatePermissions(
15860                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15861                        mPermissionCallback);
15862
15863                mSettings.writeLPr();
15864            }
15865
15866            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15867                    + " after failed upgrade");
15868        }
15869    }
15870
15871    /**
15872     * Checks whether the parent or any of the child packages have a change shared
15873     * user. For a package to be a valid update the shred users of the parent and
15874     * the children should match. We may later support changing child shared users.
15875     * @param oldPkg The updated package.
15876     * @param newPkg The update package.
15877     * @return The shared user that change between the versions.
15878     */
15879    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15880            PackageParser.Package newPkg) {
15881        // Check parent shared user
15882        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15883            return newPkg.packageName;
15884        }
15885        // Check child shared users
15886        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15887        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15888        for (int i = 0; i < newChildCount; i++) {
15889            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15890            // If this child was present, did it have the same shared user?
15891            for (int j = 0; j < oldChildCount; j++) {
15892                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15893                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15894                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15895                    return newChildPkg.packageName;
15896                }
15897            }
15898        }
15899        return null;
15900    }
15901
15902    private void removeNativeBinariesLI(PackageSetting ps) {
15903        // Remove the lib path for the parent package
15904        if (ps != null) {
15905            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15906            // Remove the lib path for the child packages
15907            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15908            for (int i = 0; i < childCount; i++) {
15909                PackageSetting childPs = null;
15910                synchronized (mPackages) {
15911                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15912                }
15913                if (childPs != null) {
15914                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15915                            .legacyNativeLibraryPathString);
15916                }
15917            }
15918        }
15919    }
15920
15921    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15922        // Enable the parent package
15923        mSettings.enableSystemPackageLPw(pkg.packageName);
15924        // Enable the child packages
15925        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15926        for (int i = 0; i < childCount; i++) {
15927            PackageParser.Package childPkg = pkg.childPackages.get(i);
15928            mSettings.enableSystemPackageLPw(childPkg.packageName);
15929        }
15930    }
15931
15932    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15933            PackageParser.Package newPkg) {
15934        // Disable the parent package (parent always replaced)
15935        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15936        // Disable the child packages
15937        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15938        for (int i = 0; i < childCount; i++) {
15939            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15940            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15941            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15942        }
15943        return disabled;
15944    }
15945
15946    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15947            String installerPackageName) {
15948        // Enable the parent package
15949        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15950        // Enable the child packages
15951        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15952        for (int i = 0; i < childCount; i++) {
15953            PackageParser.Package childPkg = pkg.childPackages.get(i);
15954            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15955        }
15956    }
15957
15958    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15959            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15960        // Update the parent package setting
15961        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15962                res, user, installReason);
15963        // Update the child packages setting
15964        final int childCount = (newPackage.childPackages != null)
15965                ? newPackage.childPackages.size() : 0;
15966        for (int i = 0; i < childCount; i++) {
15967            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15968            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15969            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15970                    childRes.origUsers, childRes, user, installReason);
15971        }
15972    }
15973
15974    private void updateSettingsInternalLI(PackageParser.Package pkg,
15975            String installerPackageName, int[] allUsers, int[] installedForUsers,
15976            PackageInstalledInfo res, UserHandle user, int installReason) {
15977        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15978
15979        String pkgName = pkg.packageName;
15980        synchronized (mPackages) {
15981            //write settings. the installStatus will be incomplete at this stage.
15982            //note that the new package setting would have already been
15983            //added to mPackages. It hasn't been persisted yet.
15984            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15985            // TODO: Remove this write? It's also written at the end of this method
15986            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15987            mSettings.writeLPr();
15988            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15989        }
15990
15991        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
15992        synchronized (mPackages) {
15993// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
15994            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
15995                    mPermissionCallback);
15996            // For system-bundled packages, we assume that installing an upgraded version
15997            // of the package implies that the user actually wants to run that new code,
15998            // so we enable the package.
15999            PackageSetting ps = mSettings.mPackages.get(pkgName);
16000            final int userId = user.getIdentifier();
16001            if (ps != null) {
16002                if (isSystemApp(pkg)) {
16003                    if (DEBUG_INSTALL) {
16004                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16005                    }
16006                    // Enable system package for requested users
16007                    if (res.origUsers != null) {
16008                        for (int origUserId : res.origUsers) {
16009                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16010                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16011                                        origUserId, installerPackageName);
16012                            }
16013                        }
16014                    }
16015                    // Also convey the prior install/uninstall state
16016                    if (allUsers != null && installedForUsers != null) {
16017                        for (int currentUserId : allUsers) {
16018                            final boolean installed = ArrayUtils.contains(
16019                                    installedForUsers, currentUserId);
16020                            if (DEBUG_INSTALL) {
16021                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16022                            }
16023                            ps.setInstalled(installed, currentUserId);
16024                        }
16025                        // these install state changes will be persisted in the
16026                        // upcoming call to mSettings.writeLPr().
16027                    }
16028                }
16029                // It's implied that when a user requests installation, they want the app to be
16030                // installed and enabled.
16031                if (userId != UserHandle.USER_ALL) {
16032                    ps.setInstalled(true, userId);
16033                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16034                }
16035
16036                // When replacing an existing package, preserve the original install reason for all
16037                // users that had the package installed before.
16038                final Set<Integer> previousUserIds = new ArraySet<>();
16039                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16040                    final int installReasonCount = res.removedInfo.installReasons.size();
16041                    for (int i = 0; i < installReasonCount; i++) {
16042                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16043                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16044                        ps.setInstallReason(previousInstallReason, previousUserId);
16045                        previousUserIds.add(previousUserId);
16046                    }
16047                }
16048
16049                // Set install reason for users that are having the package newly installed.
16050                if (userId == UserHandle.USER_ALL) {
16051                    for (int currentUserId : sUserManager.getUserIds()) {
16052                        if (!previousUserIds.contains(currentUserId)) {
16053                            ps.setInstallReason(installReason, currentUserId);
16054                        }
16055                    }
16056                } else if (!previousUserIds.contains(userId)) {
16057                    ps.setInstallReason(installReason, userId);
16058                }
16059                mSettings.writeKernelMappingLPr(ps);
16060            }
16061            res.name = pkgName;
16062            res.uid = pkg.applicationInfo.uid;
16063            res.pkg = pkg;
16064            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16065            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16066            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16067            //to update install status
16068            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16069            mSettings.writeLPr();
16070            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16071        }
16072
16073        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16074    }
16075
16076    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16077        try {
16078            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16079            installPackageLI(args, res);
16080        } finally {
16081            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16082        }
16083    }
16084
16085    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16086        final int installFlags = args.installFlags;
16087        final String installerPackageName = args.installerPackageName;
16088        final String volumeUuid = args.volumeUuid;
16089        final File tmpPackageFile = new File(args.getCodePath());
16090        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16091        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16092                || (args.volumeUuid != null));
16093        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16094        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16095        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16096        final boolean virtualPreload =
16097                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16098        boolean replace = false;
16099        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16100        if (args.move != null) {
16101            // moving a complete application; perform an initial scan on the new install location
16102            scanFlags |= SCAN_INITIAL;
16103        }
16104        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16105            scanFlags |= SCAN_DONT_KILL_APP;
16106        }
16107        if (instantApp) {
16108            scanFlags |= SCAN_AS_INSTANT_APP;
16109        }
16110        if (fullApp) {
16111            scanFlags |= SCAN_AS_FULL_APP;
16112        }
16113        if (virtualPreload) {
16114            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16115        }
16116
16117        // Result object to be returned
16118        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16119        res.installerPackageName = installerPackageName;
16120
16121        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16122
16123        // Sanity check
16124        if (instantApp && (forwardLocked || onExternal)) {
16125            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16126                    + " external=" + onExternal);
16127            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16128            return;
16129        }
16130
16131        // Retrieve PackageSettings and parse package
16132        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16133                | PackageParser.PARSE_ENFORCE_CODE
16134                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16135                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16136                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16137                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16138        PackageParser pp = new PackageParser();
16139        pp.setSeparateProcesses(mSeparateProcesses);
16140        pp.setDisplayMetrics(mMetrics);
16141        pp.setCallback(mPackageParserCallback);
16142
16143        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16144        final PackageParser.Package pkg;
16145        try {
16146            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16147        } catch (PackageParserException e) {
16148            res.setError("Failed parse during installPackageLI", e);
16149            return;
16150        } finally {
16151            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16152        }
16153
16154        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16155        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16156            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
16157            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16158                    "Instant app package must target O");
16159            return;
16160        }
16161        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16162            Slog.w(TAG, "Instant app package " + pkg.packageName
16163                    + " does not target targetSandboxVersion 2");
16164            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16165                    "Instant app package must use targetSanboxVersion 2");
16166            return;
16167        }
16168
16169        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16170            // Static shared libraries have synthetic package names
16171            renameStaticSharedLibraryPackage(pkg);
16172
16173            // No static shared libs on external storage
16174            if (onExternal) {
16175                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16176                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16177                        "Packages declaring static-shared libs cannot be updated");
16178                return;
16179            }
16180        }
16181
16182        // If we are installing a clustered package add results for the children
16183        if (pkg.childPackages != null) {
16184            synchronized (mPackages) {
16185                final int childCount = pkg.childPackages.size();
16186                for (int i = 0; i < childCount; i++) {
16187                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16188                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16189                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16190                    childRes.pkg = childPkg;
16191                    childRes.name = childPkg.packageName;
16192                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16193                    if (childPs != null) {
16194                        childRes.origUsers = childPs.queryInstalledUsers(
16195                                sUserManager.getUserIds(), true);
16196                    }
16197                    if ((mPackages.containsKey(childPkg.packageName))) {
16198                        childRes.removedInfo = new PackageRemovedInfo(this);
16199                        childRes.removedInfo.removedPackage = childPkg.packageName;
16200                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16201                    }
16202                    if (res.addedChildPackages == null) {
16203                        res.addedChildPackages = new ArrayMap<>();
16204                    }
16205                    res.addedChildPackages.put(childPkg.packageName, childRes);
16206                }
16207            }
16208        }
16209
16210        // If package doesn't declare API override, mark that we have an install
16211        // time CPU ABI override.
16212        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16213            pkg.cpuAbiOverride = args.abiOverride;
16214        }
16215
16216        String pkgName = res.name = pkg.packageName;
16217        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16218            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16219                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16220                return;
16221            }
16222        }
16223
16224        try {
16225            // either use what we've been given or parse directly from the APK
16226            if (args.certificates != null) {
16227                try {
16228                    PackageParser.populateCertificates(pkg, args.certificates);
16229                } catch (PackageParserException e) {
16230                    // there was something wrong with the certificates we were given;
16231                    // try to pull them from the APK
16232                    PackageParser.collectCertificates(pkg, parseFlags);
16233                }
16234            } else {
16235                PackageParser.collectCertificates(pkg, parseFlags);
16236            }
16237        } catch (PackageParserException e) {
16238            res.setError("Failed collect during installPackageLI", e);
16239            return;
16240        }
16241
16242        // Get rid of all references to package scan path via parser.
16243        pp = null;
16244        String oldCodePath = null;
16245        boolean systemApp = false;
16246        synchronized (mPackages) {
16247            // Check if installing already existing package
16248            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16249                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16250                if (pkg.mOriginalPackages != null
16251                        && pkg.mOriginalPackages.contains(oldName)
16252                        && mPackages.containsKey(oldName)) {
16253                    // This package is derived from an original package,
16254                    // and this device has been updating from that original
16255                    // name.  We must continue using the original name, so
16256                    // rename the new package here.
16257                    pkg.setPackageName(oldName);
16258                    pkgName = pkg.packageName;
16259                    replace = true;
16260                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16261                            + oldName + " pkgName=" + pkgName);
16262                } else if (mPackages.containsKey(pkgName)) {
16263                    // This package, under its official name, already exists
16264                    // on the device; we should replace it.
16265                    replace = true;
16266                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16267                }
16268
16269                // Child packages are installed through the parent package
16270                if (pkg.parentPackage != null) {
16271                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16272                            "Package " + pkg.packageName + " is child of package "
16273                                    + pkg.parentPackage.parentPackage + ". Child packages "
16274                                    + "can be updated only through the parent package.");
16275                    return;
16276                }
16277
16278                if (replace) {
16279                    // Prevent apps opting out from runtime permissions
16280                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16281                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16282                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16283                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16284                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16285                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16286                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16287                                        + " doesn't support runtime permissions but the old"
16288                                        + " target SDK " + oldTargetSdk + " does.");
16289                        return;
16290                    }
16291                    // Prevent apps from downgrading their targetSandbox.
16292                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16293                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16294                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16295                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16296                                "Package " + pkg.packageName + " new target sandbox "
16297                                + newTargetSandbox + " is incompatible with the previous value of"
16298                                + oldTargetSandbox + ".");
16299                        return;
16300                    }
16301
16302                    // Prevent installing of child packages
16303                    if (oldPackage.parentPackage != null) {
16304                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16305                                "Package " + pkg.packageName + " is child of package "
16306                                        + oldPackage.parentPackage + ". Child packages "
16307                                        + "can be updated only through the parent package.");
16308                        return;
16309                    }
16310                }
16311            }
16312
16313            PackageSetting ps = mSettings.mPackages.get(pkgName);
16314            if (ps != null) {
16315                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16316
16317                // Static shared libs have same package with different versions where
16318                // we internally use a synthetic package name to allow multiple versions
16319                // of the same package, therefore we need to compare signatures against
16320                // the package setting for the latest library version.
16321                PackageSetting signatureCheckPs = ps;
16322                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16323                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16324                    if (libraryEntry != null) {
16325                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16326                    }
16327                }
16328
16329                // Quick sanity check that we're signed correctly if updating;
16330                // we'll check this again later when scanning, but we want to
16331                // bail early here before tripping over redefined permissions.
16332                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16333                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16334                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16335                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16336                                + pkg.packageName + " upgrade keys do not match the "
16337                                + "previously installed version");
16338                        return;
16339                    }
16340                } else {
16341                    try {
16342                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16343                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16344                        final boolean compatMatch = verifySignatures(
16345                                signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover);
16346                        // The new KeySets will be re-added later in the scanning process.
16347                        if (compatMatch) {
16348                            synchronized (mPackages) {
16349                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16350                            }
16351                        }
16352                    } catch (PackageManagerException e) {
16353                        res.setError(e.error, e.getMessage());
16354                        return;
16355                    }
16356                }
16357
16358                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16359                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16360                    systemApp = (ps.pkg.applicationInfo.flags &
16361                            ApplicationInfo.FLAG_SYSTEM) != 0;
16362                }
16363                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16364            }
16365
16366            int N = pkg.permissions.size();
16367            for (int i = N-1; i >= 0; i--) {
16368                final PackageParser.Permission perm = pkg.permissions.get(i);
16369                final BasePermission bp =
16370                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16371
16372                // Don't allow anyone but the system to define ephemeral permissions.
16373                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16374                        && !systemApp) {
16375                    Slog.w(TAG, "Non-System package " + pkg.packageName
16376                            + " attempting to delcare ephemeral permission "
16377                            + perm.info.name + "; Removing ephemeral.");
16378                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16379                }
16380
16381                // Check whether the newly-scanned package wants to define an already-defined perm
16382                if (bp != null) {
16383                    // If the defining package is signed with our cert, it's okay.  This
16384                    // also includes the "updating the same package" case, of course.
16385                    // "updating same package" could also involve key-rotation.
16386                    final boolean sigsOk;
16387                    final String sourcePackageName = bp.getSourcePackageName();
16388                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16389                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16390                    if (sourcePackageName.equals(pkg.packageName)
16391                            && (ksms.shouldCheckUpgradeKeySetLocked(
16392                                    sourcePackageSetting, scanFlags))) {
16393                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16394                    } else {
16395                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16396                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16397                    }
16398                    if (!sigsOk) {
16399                        // If the owning package is the system itself, we log but allow
16400                        // install to proceed; we fail the install on all other permission
16401                        // redefinitions.
16402                        if (!sourcePackageName.equals("android")) {
16403                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16404                                    + pkg.packageName + " attempting to redeclare permission "
16405                                    + perm.info.name + " already owned by " + sourcePackageName);
16406                            res.origPermission = perm.info.name;
16407                            res.origPackage = sourcePackageName;
16408                            return;
16409                        } else {
16410                            Slog.w(TAG, "Package " + pkg.packageName
16411                                    + " attempting to redeclare system permission "
16412                                    + perm.info.name + "; ignoring new declaration");
16413                            pkg.permissions.remove(i);
16414                        }
16415                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16416                        // Prevent apps to change protection level to dangerous from any other
16417                        // type as this would allow a privilege escalation where an app adds a
16418                        // normal/signature permission in other app's group and later redefines
16419                        // it as dangerous leading to the group auto-grant.
16420                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16421                                == PermissionInfo.PROTECTION_DANGEROUS) {
16422                            if (bp != null && !bp.isRuntime()) {
16423                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16424                                        + "non-runtime permission " + perm.info.name
16425                                        + " to runtime; keeping old protection level");
16426                                perm.info.protectionLevel = bp.getProtectionLevel();
16427                            }
16428                        }
16429                    }
16430                }
16431            }
16432        }
16433
16434        if (systemApp) {
16435            if (onExternal) {
16436                // Abort update; system app can't be replaced with app on sdcard
16437                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16438                        "Cannot install updates to system apps on sdcard");
16439                return;
16440            } else if (instantApp) {
16441                // Abort update; system app can't be replaced with an instant app
16442                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16443                        "Cannot update a system app with an instant app");
16444                return;
16445            }
16446        }
16447
16448        if (args.move != null) {
16449            // We did an in-place move, so dex is ready to roll
16450            scanFlags |= SCAN_NO_DEX;
16451            scanFlags |= SCAN_MOVE;
16452
16453            synchronized (mPackages) {
16454                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16455                if (ps == null) {
16456                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16457                            "Missing settings for moved package " + pkgName);
16458                }
16459
16460                // We moved the entire application as-is, so bring over the
16461                // previously derived ABI information.
16462                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16463                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16464            }
16465
16466        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16467            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16468            scanFlags |= SCAN_NO_DEX;
16469
16470            try {
16471                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16472                    args.abiOverride : pkg.cpuAbiOverride);
16473                final boolean extractNativeLibs = !pkg.isLibrary();
16474                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16475                        extractNativeLibs, mAppLib32InstallDir);
16476            } catch (PackageManagerException pme) {
16477                Slog.e(TAG, "Error deriving application ABI", pme);
16478                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16479                return;
16480            }
16481
16482            // Shared libraries for the package need to be updated.
16483            synchronized (mPackages) {
16484                try {
16485                    updateSharedLibrariesLPr(pkg, null);
16486                } catch (PackageManagerException e) {
16487                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16488                }
16489            }
16490        }
16491
16492        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16493            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16494            return;
16495        }
16496
16497        // Verify if we need to dexopt the app.
16498        //
16499        // NOTE: it is *important* to call dexopt after doRename which will sync the
16500        // package data from PackageParser.Package and its corresponding ApplicationInfo.
16501        //
16502        // We only need to dexopt if the package meets ALL of the following conditions:
16503        //   1) it is not forward locked.
16504        //   2) it is not on on an external ASEC container.
16505        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16506        //
16507        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16508        // complete, so we skip this step during installation. Instead, we'll take extra time
16509        // the first time the instant app starts. It's preferred to do it this way to provide
16510        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16511        // middle of running an instant app. The default behaviour can be overridden
16512        // via gservices.
16513        final boolean performDexopt = !forwardLocked
16514            && !pkg.applicationInfo.isExternalAsec()
16515            && (!instantApp || Global.getInt(mContext.getContentResolver(),
16516                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16517
16518        if (performDexopt) {
16519            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16520            // Do not run PackageDexOptimizer through the local performDexOpt
16521            // method because `pkg` may not be in `mPackages` yet.
16522            //
16523            // Also, don't fail application installs if the dexopt step fails.
16524            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16525                REASON_INSTALL,
16526                DexoptOptions.DEXOPT_BOOT_COMPLETE);
16527            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16528                null /* instructionSets */,
16529                getOrCreateCompilerPackageStats(pkg),
16530                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16531                dexoptOptions);
16532            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16533        }
16534
16535        // Notify BackgroundDexOptService that the package has been changed.
16536        // If this is an update of a package which used to fail to compile,
16537        // BackgroundDexOptService will remove it from its blacklist.
16538        // TODO: Layering violation
16539        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16540
16541        if (!instantApp) {
16542            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16543        } else {
16544            if (DEBUG_DOMAIN_VERIFICATION) {
16545                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16546            }
16547        }
16548
16549        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16550                "installPackageLI")) {
16551            if (replace) {
16552                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16553                    // Static libs have a synthetic package name containing the version
16554                    // and cannot be updated as an update would get a new package name,
16555                    // unless this is the exact same version code which is useful for
16556                    // development.
16557                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16558                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16559                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16560                                + "static-shared libs cannot be updated");
16561                        return;
16562                    }
16563                }
16564                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16565                        installerPackageName, res, args.installReason);
16566            } else {
16567                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16568                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16569            }
16570        }
16571
16572        synchronized (mPackages) {
16573            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16574            if (ps != null) {
16575                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16576                ps.setUpdateAvailable(false /*updateAvailable*/);
16577            }
16578
16579            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16580            for (int i = 0; i < childCount; i++) {
16581                PackageParser.Package childPkg = pkg.childPackages.get(i);
16582                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16583                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16584                if (childPs != null) {
16585                    childRes.newUsers = childPs.queryInstalledUsers(
16586                            sUserManager.getUserIds(), true);
16587                }
16588            }
16589
16590            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16591                updateSequenceNumberLP(ps, res.newUsers);
16592                updateInstantAppInstallerLocked(pkgName);
16593            }
16594        }
16595    }
16596
16597    private void startIntentFilterVerifications(int userId, boolean replacing,
16598            PackageParser.Package pkg) {
16599        if (mIntentFilterVerifierComponent == null) {
16600            Slog.w(TAG, "No IntentFilter verification will not be done as "
16601                    + "there is no IntentFilterVerifier available!");
16602            return;
16603        }
16604
16605        final int verifierUid = getPackageUid(
16606                mIntentFilterVerifierComponent.getPackageName(),
16607                MATCH_DEBUG_TRIAGED_MISSING,
16608                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16609
16610        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16611        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16612        mHandler.sendMessage(msg);
16613
16614        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16615        for (int i = 0; i < childCount; i++) {
16616            PackageParser.Package childPkg = pkg.childPackages.get(i);
16617            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16618            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16619            mHandler.sendMessage(msg);
16620        }
16621    }
16622
16623    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16624            PackageParser.Package pkg) {
16625        int size = pkg.activities.size();
16626        if (size == 0) {
16627            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16628                    "No activity, so no need to verify any IntentFilter!");
16629            return;
16630        }
16631
16632        final boolean hasDomainURLs = hasDomainURLs(pkg);
16633        if (!hasDomainURLs) {
16634            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16635                    "No domain URLs, so no need to verify any IntentFilter!");
16636            return;
16637        }
16638
16639        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16640                + " if any IntentFilter from the " + size
16641                + " Activities needs verification ...");
16642
16643        int count = 0;
16644        final String packageName = pkg.packageName;
16645
16646        synchronized (mPackages) {
16647            // If this is a new install and we see that we've already run verification for this
16648            // package, we have nothing to do: it means the state was restored from backup.
16649            if (!replacing) {
16650                IntentFilterVerificationInfo ivi =
16651                        mSettings.getIntentFilterVerificationLPr(packageName);
16652                if (ivi != null) {
16653                    if (DEBUG_DOMAIN_VERIFICATION) {
16654                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16655                                + ivi.getStatusString());
16656                    }
16657                    return;
16658                }
16659            }
16660
16661            // If any filters need to be verified, then all need to be.
16662            boolean needToVerify = false;
16663            for (PackageParser.Activity a : pkg.activities) {
16664                for (ActivityIntentInfo filter : a.intents) {
16665                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16666                        if (DEBUG_DOMAIN_VERIFICATION) {
16667                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16668                        }
16669                        needToVerify = true;
16670                        break;
16671                    }
16672                }
16673            }
16674
16675            if (needToVerify) {
16676                final int verificationId = mIntentFilterVerificationToken++;
16677                for (PackageParser.Activity a : pkg.activities) {
16678                    for (ActivityIntentInfo filter : a.intents) {
16679                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16680                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16681                                    "Verification needed for IntentFilter:" + filter.toString());
16682                            mIntentFilterVerifier.addOneIntentFilterVerification(
16683                                    verifierUid, userId, verificationId, filter, packageName);
16684                            count++;
16685                        }
16686                    }
16687                }
16688            }
16689        }
16690
16691        if (count > 0) {
16692            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16693                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16694                    +  " for userId:" + userId);
16695            mIntentFilterVerifier.startVerifications(userId);
16696        } else {
16697            if (DEBUG_DOMAIN_VERIFICATION) {
16698                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16699            }
16700        }
16701    }
16702
16703    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16704        final ComponentName cn  = filter.activity.getComponentName();
16705        final String packageName = cn.getPackageName();
16706
16707        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16708                packageName);
16709        if (ivi == null) {
16710            return true;
16711        }
16712        int status = ivi.getStatus();
16713        switch (status) {
16714            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16715            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16716                return true;
16717
16718            default:
16719                // Nothing to do
16720                return false;
16721        }
16722    }
16723
16724    private static boolean isMultiArch(ApplicationInfo info) {
16725        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16726    }
16727
16728    private static boolean isExternal(PackageParser.Package pkg) {
16729        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16730    }
16731
16732    private static boolean isExternal(PackageSetting ps) {
16733        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16734    }
16735
16736    private static boolean isSystemApp(PackageParser.Package pkg) {
16737        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16738    }
16739
16740    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16741        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16742    }
16743
16744    private static boolean isOemApp(PackageParser.Package pkg) {
16745        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16746    }
16747
16748    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16749        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16750    }
16751
16752    private static boolean isSystemApp(PackageSetting ps) {
16753        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16754    }
16755
16756    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16757        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16758    }
16759
16760    private int packageFlagsToInstallFlags(PackageSetting ps) {
16761        int installFlags = 0;
16762        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16763            // This existing package was an external ASEC install when we have
16764            // the external flag without a UUID
16765            installFlags |= PackageManager.INSTALL_EXTERNAL;
16766        }
16767        if (ps.isForwardLocked()) {
16768            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16769        }
16770        return installFlags;
16771    }
16772
16773    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16774        if (isExternal(pkg)) {
16775            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16776                return mSettings.getExternalVersion();
16777            } else {
16778                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16779            }
16780        } else {
16781            return mSettings.getInternalVersion();
16782        }
16783    }
16784
16785    private void deleteTempPackageFiles() {
16786        final FilenameFilter filter = new FilenameFilter() {
16787            public boolean accept(File dir, String name) {
16788                return name.startsWith("vmdl") && name.endsWith(".tmp");
16789            }
16790        };
16791        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16792            file.delete();
16793        }
16794    }
16795
16796    @Override
16797    public void deletePackageAsUser(String packageName, int versionCode,
16798            IPackageDeleteObserver observer, int userId, int flags) {
16799        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
16800                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
16801    }
16802
16803    @Override
16804    public void deletePackageVersioned(VersionedPackage versionedPackage,
16805            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16806        final int callingUid = Binder.getCallingUid();
16807        mContext.enforceCallingOrSelfPermission(
16808                android.Manifest.permission.DELETE_PACKAGES, null);
16809        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
16810        Preconditions.checkNotNull(versionedPackage);
16811        Preconditions.checkNotNull(observer);
16812        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
16813                PackageManager.VERSION_CODE_HIGHEST,
16814                Integer.MAX_VALUE, "versionCode must be >= -1");
16815
16816        final String packageName = versionedPackage.getPackageName();
16817        final int versionCode = versionedPackage.getVersionCode();
16818        final String internalPackageName;
16819        synchronized (mPackages) {
16820            // Normalize package name to handle renamed packages and static libs
16821            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
16822                    versionedPackage.getVersionCode());
16823        }
16824
16825        final int uid = Binder.getCallingUid();
16826        if (!isOrphaned(internalPackageName)
16827                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
16828            try {
16829                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16830                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16831                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16832                observer.onUserActionRequired(intent);
16833            } catch (RemoteException re) {
16834            }
16835            return;
16836        }
16837        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16838        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16839        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16840            mContext.enforceCallingOrSelfPermission(
16841                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16842                    "deletePackage for user " + userId);
16843        }
16844
16845        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16846            try {
16847                observer.onPackageDeleted(packageName,
16848                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16849            } catch (RemoteException re) {
16850            }
16851            return;
16852        }
16853
16854        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
16855            try {
16856                observer.onPackageDeleted(packageName,
16857                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16858            } catch (RemoteException re) {
16859            }
16860            return;
16861        }
16862
16863        if (DEBUG_REMOVE) {
16864            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
16865                    + " deleteAllUsers: " + deleteAllUsers + " version="
16866                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
16867                    ? "VERSION_CODE_HIGHEST" : versionCode));
16868        }
16869        // Queue up an async operation since the package deletion may take a little while.
16870        mHandler.post(new Runnable() {
16871            public void run() {
16872                mHandler.removeCallbacks(this);
16873                int returnCode;
16874                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
16875                boolean doDeletePackage = true;
16876                if (ps != null) {
16877                    final boolean targetIsInstantApp =
16878                            ps.getInstantApp(UserHandle.getUserId(callingUid));
16879                    doDeletePackage = !targetIsInstantApp
16880                            || canViewInstantApps;
16881                }
16882                if (doDeletePackage) {
16883                    if (!deleteAllUsers) {
16884                        returnCode = deletePackageX(internalPackageName, versionCode,
16885                                userId, deleteFlags);
16886                    } else {
16887                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
16888                                internalPackageName, users);
16889                        // If nobody is blocking uninstall, proceed with delete for all users
16890                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16891                            returnCode = deletePackageX(internalPackageName, versionCode,
16892                                    userId, deleteFlags);
16893                        } else {
16894                            // Otherwise uninstall individually for users with blockUninstalls=false
16895                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16896                            for (int userId : users) {
16897                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16898                                    returnCode = deletePackageX(internalPackageName, versionCode,
16899                                            userId, userFlags);
16900                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16901                                        Slog.w(TAG, "Package delete failed for user " + userId
16902                                                + ", returnCode " + returnCode);
16903                                    }
16904                                }
16905                            }
16906                            // The app has only been marked uninstalled for certain users.
16907                            // We still need to report that delete was blocked
16908                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16909                        }
16910                    }
16911                } else {
16912                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16913                }
16914                try {
16915                    observer.onPackageDeleted(packageName, returnCode, null);
16916                } catch (RemoteException e) {
16917                    Log.i(TAG, "Observer no longer exists.");
16918                } //end catch
16919            } //end run
16920        });
16921    }
16922
16923    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
16924        if (pkg.staticSharedLibName != null) {
16925            return pkg.manifestPackageName;
16926        }
16927        return pkg.packageName;
16928    }
16929
16930    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
16931        // Handle renamed packages
16932        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
16933        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
16934
16935        // Is this a static library?
16936        SparseArray<SharedLibraryEntry> versionedLib =
16937                mStaticLibsByDeclaringPackage.get(packageName);
16938        if (versionedLib == null || versionedLib.size() <= 0) {
16939            return packageName;
16940        }
16941
16942        // Figure out which lib versions the caller can see
16943        SparseIntArray versionsCallerCanSee = null;
16944        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
16945        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
16946                && callingAppId != Process.ROOT_UID) {
16947            versionsCallerCanSee = new SparseIntArray();
16948            String libName = versionedLib.valueAt(0).info.getName();
16949            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
16950            if (uidPackages != null) {
16951                for (String uidPackage : uidPackages) {
16952                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
16953                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
16954                    if (libIdx >= 0) {
16955                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
16956                        versionsCallerCanSee.append(libVersion, libVersion);
16957                    }
16958                }
16959            }
16960        }
16961
16962        // Caller can see nothing - done
16963        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
16964            return packageName;
16965        }
16966
16967        // Find the version the caller can see and the app version code
16968        SharedLibraryEntry highestVersion = null;
16969        final int versionCount = versionedLib.size();
16970        for (int i = 0; i < versionCount; i++) {
16971            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
16972            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
16973                    libEntry.info.getVersion()) < 0) {
16974                continue;
16975            }
16976            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
16977            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
16978                if (libVersionCode == versionCode) {
16979                    return libEntry.apk;
16980                }
16981            } else if (highestVersion == null) {
16982                highestVersion = libEntry;
16983            } else if (libVersionCode  > highestVersion.info
16984                    .getDeclaringPackage().getVersionCode()) {
16985                highestVersion = libEntry;
16986            }
16987        }
16988
16989        if (highestVersion != null) {
16990            return highestVersion.apk;
16991        }
16992
16993        return packageName;
16994    }
16995
16996    boolean isCallerVerifier(int callingUid) {
16997        final int callingUserId = UserHandle.getUserId(callingUid);
16998        return mRequiredVerifierPackage != null &&
16999                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17000    }
17001
17002    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17003        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17004              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17005            return true;
17006        }
17007        final int callingUserId = UserHandle.getUserId(callingUid);
17008        // If the caller installed the pkgName, then allow it to silently uninstall.
17009        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17010            return true;
17011        }
17012
17013        // Allow package verifier to silently uninstall.
17014        if (mRequiredVerifierPackage != null &&
17015                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17016            return true;
17017        }
17018
17019        // Allow package uninstaller to silently uninstall.
17020        if (mRequiredUninstallerPackage != null &&
17021                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17022            return true;
17023        }
17024
17025        // Allow storage manager to silently uninstall.
17026        if (mStorageManagerPackage != null &&
17027                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17028            return true;
17029        }
17030
17031        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17032        // uninstall for device owner provisioning.
17033        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17034                == PERMISSION_GRANTED) {
17035            return true;
17036        }
17037
17038        return false;
17039    }
17040
17041    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17042        int[] result = EMPTY_INT_ARRAY;
17043        for (int userId : userIds) {
17044            if (getBlockUninstallForUser(packageName, userId)) {
17045                result = ArrayUtils.appendInt(result, userId);
17046            }
17047        }
17048        return result;
17049    }
17050
17051    @Override
17052    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17053        final int callingUid = Binder.getCallingUid();
17054        if (getInstantAppPackageName(callingUid) != null
17055                && !isCallerSameApp(packageName, callingUid)) {
17056            return false;
17057        }
17058        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17059    }
17060
17061    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17062        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17063                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17064        try {
17065            if (dpm != null) {
17066                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17067                        /* callingUserOnly =*/ false);
17068                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17069                        : deviceOwnerComponentName.getPackageName();
17070                // Does the package contains the device owner?
17071                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17072                // this check is probably not needed, since DO should be registered as a device
17073                // admin on some user too. (Original bug for this: b/17657954)
17074                if (packageName.equals(deviceOwnerPackageName)) {
17075                    return true;
17076                }
17077                // Does it contain a device admin for any user?
17078                int[] users;
17079                if (userId == UserHandle.USER_ALL) {
17080                    users = sUserManager.getUserIds();
17081                } else {
17082                    users = new int[]{userId};
17083                }
17084                for (int i = 0; i < users.length; ++i) {
17085                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17086                        return true;
17087                    }
17088                }
17089            }
17090        } catch (RemoteException e) {
17091        }
17092        return false;
17093    }
17094
17095    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17096        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17097    }
17098
17099    /**
17100     *  This method is an internal method that could be get invoked either
17101     *  to delete an installed package or to clean up a failed installation.
17102     *  After deleting an installed package, a broadcast is sent to notify any
17103     *  listeners that the package has been removed. For cleaning up a failed
17104     *  installation, the broadcast is not necessary since the package's
17105     *  installation wouldn't have sent the initial broadcast either
17106     *  The key steps in deleting a package are
17107     *  deleting the package information in internal structures like mPackages,
17108     *  deleting the packages base directories through installd
17109     *  updating mSettings to reflect current status
17110     *  persisting settings for later use
17111     *  sending a broadcast if necessary
17112     */
17113    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17114        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17115        final boolean res;
17116
17117        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17118                ? UserHandle.USER_ALL : userId;
17119
17120        if (isPackageDeviceAdmin(packageName, removeUser)) {
17121            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17122            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17123        }
17124
17125        PackageSetting uninstalledPs = null;
17126        PackageParser.Package pkg = null;
17127
17128        // for the uninstall-updates case and restricted profiles, remember the per-
17129        // user handle installed state
17130        int[] allUsers;
17131        synchronized (mPackages) {
17132            uninstalledPs = mSettings.mPackages.get(packageName);
17133            if (uninstalledPs == null) {
17134                Slog.w(TAG, "Not removing non-existent package " + packageName);
17135                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17136            }
17137
17138            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17139                    && uninstalledPs.versionCode != versionCode) {
17140                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17141                        + uninstalledPs.versionCode + " != " + versionCode);
17142                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17143            }
17144
17145            // Static shared libs can be declared by any package, so let us not
17146            // allow removing a package if it provides a lib others depend on.
17147            pkg = mPackages.get(packageName);
17148
17149            allUsers = sUserManager.getUserIds();
17150
17151            if (pkg != null && pkg.staticSharedLibName != null) {
17152                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17153                        pkg.staticSharedLibVersion);
17154                if (libEntry != null) {
17155                    for (int currUserId : allUsers) {
17156                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17157                            continue;
17158                        }
17159                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17160                                libEntry.info, 0, currUserId);
17161                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17162                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17163                                    + " hosting lib " + libEntry.info.getName() + " version "
17164                                    + libEntry.info.getVersion() + " used by " + libClientPackages
17165                                    + " for user " + currUserId);
17166                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17167                        }
17168                    }
17169                }
17170            }
17171
17172            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17173        }
17174
17175        final int freezeUser;
17176        if (isUpdatedSystemApp(uninstalledPs)
17177                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17178            // We're downgrading a system app, which will apply to all users, so
17179            // freeze them all during the downgrade
17180            freezeUser = UserHandle.USER_ALL;
17181        } else {
17182            freezeUser = removeUser;
17183        }
17184
17185        synchronized (mInstallLock) {
17186            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17187            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17188                    deleteFlags, "deletePackageX")) {
17189                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17190                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17191            }
17192            synchronized (mPackages) {
17193                if (res) {
17194                    if (pkg != null) {
17195                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17196                    }
17197                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17198                    updateInstantAppInstallerLocked(packageName);
17199                }
17200            }
17201        }
17202
17203        if (res) {
17204            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17205            info.sendPackageRemovedBroadcasts(killApp);
17206            info.sendSystemPackageUpdatedBroadcasts();
17207            info.sendSystemPackageAppearedBroadcasts();
17208        }
17209        // Force a gc here.
17210        Runtime.getRuntime().gc();
17211        // Delete the resources here after sending the broadcast to let
17212        // other processes clean up before deleting resources.
17213        if (info.args != null) {
17214            synchronized (mInstallLock) {
17215                info.args.doPostDeleteLI(true);
17216            }
17217        }
17218
17219        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17220    }
17221
17222    static class PackageRemovedInfo {
17223        final PackageSender packageSender;
17224        String removedPackage;
17225        String installerPackageName;
17226        int uid = -1;
17227        int removedAppId = -1;
17228        int[] origUsers;
17229        int[] removedUsers = null;
17230        int[] broadcastUsers = null;
17231        SparseArray<Integer> installReasons;
17232        boolean isRemovedPackageSystemUpdate = false;
17233        boolean isUpdate;
17234        boolean dataRemoved;
17235        boolean removedForAllUsers;
17236        boolean isStaticSharedLib;
17237        // Clean up resources deleted packages.
17238        InstallArgs args = null;
17239        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17240        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17241
17242        PackageRemovedInfo(PackageSender packageSender) {
17243            this.packageSender = packageSender;
17244        }
17245
17246        void sendPackageRemovedBroadcasts(boolean killApp) {
17247            sendPackageRemovedBroadcastInternal(killApp);
17248            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17249            for (int i = 0; i < childCount; i++) {
17250                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17251                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17252            }
17253        }
17254
17255        void sendSystemPackageUpdatedBroadcasts() {
17256            if (isRemovedPackageSystemUpdate) {
17257                sendSystemPackageUpdatedBroadcastsInternal();
17258                final int childCount = (removedChildPackages != null)
17259                        ? removedChildPackages.size() : 0;
17260                for (int i = 0; i < childCount; i++) {
17261                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17262                    if (childInfo.isRemovedPackageSystemUpdate) {
17263                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17264                    }
17265                }
17266            }
17267        }
17268
17269        void sendSystemPackageAppearedBroadcasts() {
17270            final int packageCount = (appearedChildPackages != null)
17271                    ? appearedChildPackages.size() : 0;
17272            for (int i = 0; i < packageCount; i++) {
17273                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17274                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17275                    true /*sendBootCompleted*/, false /*startReceiver*/,
17276                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17277            }
17278        }
17279
17280        private void sendSystemPackageUpdatedBroadcastsInternal() {
17281            Bundle extras = new Bundle(2);
17282            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17283            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17284            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17285                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17286            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17287                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17288            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17289                null, null, 0, removedPackage, null, null);
17290            if (installerPackageName != null) {
17291                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17292                        removedPackage, extras, 0 /*flags*/,
17293                        installerPackageName, null, null);
17294                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17295                        removedPackage, extras, 0 /*flags*/,
17296                        installerPackageName, null, null);
17297            }
17298        }
17299
17300        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17301            // Don't send static shared library removal broadcasts as these
17302            // libs are visible only the the apps that depend on them an one
17303            // cannot remove the library if it has a dependency.
17304            if (isStaticSharedLib) {
17305                return;
17306            }
17307            Bundle extras = new Bundle(2);
17308            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17309            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17310            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17311            if (isUpdate || isRemovedPackageSystemUpdate) {
17312                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17313            }
17314            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17315            if (removedPackage != null) {
17316                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17317                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
17318                if (installerPackageName != null) {
17319                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17320                            removedPackage, extras, 0 /*flags*/,
17321                            installerPackageName, null, broadcastUsers);
17322                }
17323                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17324                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17325                        removedPackage, extras,
17326                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17327                        null, null, broadcastUsers);
17328                }
17329            }
17330            if (removedAppId >= 0) {
17331                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17332                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17333                    null, null, broadcastUsers);
17334            }
17335        }
17336
17337        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17338            removedUsers = userIds;
17339            if (removedUsers == null) {
17340                broadcastUsers = null;
17341                return;
17342            }
17343
17344            broadcastUsers = EMPTY_INT_ARRAY;
17345            for (int i = userIds.length - 1; i >= 0; --i) {
17346                final int userId = userIds[i];
17347                if (deletedPackageSetting.getInstantApp(userId)) {
17348                    continue;
17349                }
17350                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17351            }
17352        }
17353    }
17354
17355    /*
17356     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17357     * flag is not set, the data directory is removed as well.
17358     * make sure this flag is set for partially installed apps. If not its meaningless to
17359     * delete a partially installed application.
17360     */
17361    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17362            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17363        String packageName = ps.name;
17364        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17365        // Retrieve object to delete permissions for shared user later on
17366        final PackageParser.Package deletedPkg;
17367        final PackageSetting deletedPs;
17368        // reader
17369        synchronized (mPackages) {
17370            deletedPkg = mPackages.get(packageName);
17371            deletedPs = mSettings.mPackages.get(packageName);
17372            if (outInfo != null) {
17373                outInfo.removedPackage = packageName;
17374                outInfo.installerPackageName = ps.installerPackageName;
17375                outInfo.isStaticSharedLib = deletedPkg != null
17376                        && deletedPkg.staticSharedLibName != null;
17377                outInfo.populateUsers(deletedPs == null ? null
17378                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17379            }
17380        }
17381
17382        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17383
17384        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17385            final PackageParser.Package resolvedPkg;
17386            if (deletedPkg != null) {
17387                resolvedPkg = deletedPkg;
17388            } else {
17389                // We don't have a parsed package when it lives on an ejected
17390                // adopted storage device, so fake something together
17391                resolvedPkg = new PackageParser.Package(ps.name);
17392                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17393            }
17394            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17395                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17396            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17397            if (outInfo != null) {
17398                outInfo.dataRemoved = true;
17399            }
17400            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17401        }
17402
17403        int removedAppId = -1;
17404
17405        // writer
17406        synchronized (mPackages) {
17407            boolean installedStateChanged = false;
17408            if (deletedPs != null) {
17409                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17410                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17411                    clearDefaultBrowserIfNeeded(packageName);
17412                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17413                    removedAppId = mSettings.removePackageLPw(packageName);
17414                    if (outInfo != null) {
17415                        outInfo.removedAppId = removedAppId;
17416                    }
17417                    mPermissionManager.updatePermissions(
17418                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17419                    if (deletedPs.sharedUser != null) {
17420                        // Remove permissions associated with package. Since runtime
17421                        // permissions are per user we have to kill the removed package
17422                        // or packages running under the shared user of the removed
17423                        // package if revoking the permissions requested only by the removed
17424                        // package is successful and this causes a change in gids.
17425                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17426                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17427                                    userId);
17428                            if (userIdToKill == UserHandle.USER_ALL
17429                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17430                                // If gids changed for this user, kill all affected packages.
17431                                mHandler.post(new Runnable() {
17432                                    @Override
17433                                    public void run() {
17434                                        // This has to happen with no lock held.
17435                                        killApplication(deletedPs.name, deletedPs.appId,
17436                                                KILL_APP_REASON_GIDS_CHANGED);
17437                                    }
17438                                });
17439                                break;
17440                            }
17441                        }
17442                    }
17443                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17444                }
17445                // make sure to preserve per-user disabled state if this removal was just
17446                // a downgrade of a system app to the factory package
17447                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17448                    if (DEBUG_REMOVE) {
17449                        Slog.d(TAG, "Propagating install state across downgrade");
17450                    }
17451                    for (int userId : allUserHandles) {
17452                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17453                        if (DEBUG_REMOVE) {
17454                            Slog.d(TAG, "    user " + userId + " => " + installed);
17455                        }
17456                        if (installed != ps.getInstalled(userId)) {
17457                            installedStateChanged = true;
17458                        }
17459                        ps.setInstalled(installed, userId);
17460                    }
17461                }
17462            }
17463            // can downgrade to reader
17464            if (writeSettings) {
17465                // Save settings now
17466                mSettings.writeLPr();
17467            }
17468            if (installedStateChanged) {
17469                mSettings.writeKernelMappingLPr(ps);
17470            }
17471        }
17472        if (removedAppId != -1) {
17473            // A user ID was deleted here. Go through all users and remove it
17474            // from KeyStore.
17475            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17476        }
17477    }
17478
17479    static boolean locationIsPrivileged(File path) {
17480        try {
17481            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17482                    .getCanonicalPath();
17483            return path.getCanonicalPath().startsWith(privilegedAppDir);
17484        } catch (IOException e) {
17485            Slog.e(TAG, "Unable to access code path " + path);
17486        }
17487        return false;
17488    }
17489
17490    static boolean locationIsOem(File path) {
17491        try {
17492            return path.getCanonicalPath().startsWith(
17493                    Environment.getOemDirectory().getCanonicalPath());
17494        } catch (IOException e) {
17495            Slog.e(TAG, "Unable to access code path " + path);
17496        }
17497        return false;
17498    }
17499
17500    /*
17501     * Tries to delete system package.
17502     */
17503    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17504            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17505            boolean writeSettings) {
17506        if (deletedPs.parentPackageName != null) {
17507            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17508            return false;
17509        }
17510
17511        final boolean applyUserRestrictions
17512                = (allUserHandles != null) && (outInfo.origUsers != null);
17513        final PackageSetting disabledPs;
17514        // Confirm if the system package has been updated
17515        // An updated system app can be deleted. This will also have to restore
17516        // the system pkg from system partition
17517        // reader
17518        synchronized (mPackages) {
17519            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17520        }
17521
17522        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17523                + " disabledPs=" + disabledPs);
17524
17525        if (disabledPs == null) {
17526            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17527            return false;
17528        } else if (DEBUG_REMOVE) {
17529            Slog.d(TAG, "Deleting system pkg from data partition");
17530        }
17531
17532        if (DEBUG_REMOVE) {
17533            if (applyUserRestrictions) {
17534                Slog.d(TAG, "Remembering install states:");
17535                for (int userId : allUserHandles) {
17536                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17537                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17538                }
17539            }
17540        }
17541
17542        // Delete the updated package
17543        outInfo.isRemovedPackageSystemUpdate = true;
17544        if (outInfo.removedChildPackages != null) {
17545            final int childCount = (deletedPs.childPackageNames != null)
17546                    ? deletedPs.childPackageNames.size() : 0;
17547            for (int i = 0; i < childCount; i++) {
17548                String childPackageName = deletedPs.childPackageNames.get(i);
17549                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17550                        .contains(childPackageName)) {
17551                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17552                            childPackageName);
17553                    if (childInfo != null) {
17554                        childInfo.isRemovedPackageSystemUpdate = true;
17555                    }
17556                }
17557            }
17558        }
17559
17560        if (disabledPs.versionCode < deletedPs.versionCode) {
17561            // Delete data for downgrades
17562            flags &= ~PackageManager.DELETE_KEEP_DATA;
17563        } else {
17564            // Preserve data by setting flag
17565            flags |= PackageManager.DELETE_KEEP_DATA;
17566        }
17567
17568        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17569                outInfo, writeSettings, disabledPs.pkg);
17570        if (!ret) {
17571            return false;
17572        }
17573
17574        // writer
17575        synchronized (mPackages) {
17576            // NOTE: The system package always needs to be enabled; even if it's for
17577            // a compressed stub. If we don't, installing the system package fails
17578            // during scan [scanning checks the disabled packages]. We will reverse
17579            // this later, after we've "installed" the stub.
17580            // Reinstate the old system package
17581            enableSystemPackageLPw(disabledPs.pkg);
17582            // Remove any native libraries from the upgraded package.
17583            removeNativeBinariesLI(deletedPs);
17584        }
17585
17586        // Install the system package
17587        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17588        try {
17589            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
17590                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17591        } catch (PackageManagerException e) {
17592            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17593                    + e.getMessage());
17594            return false;
17595        } finally {
17596            if (disabledPs.pkg.isStub) {
17597                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
17598            }
17599        }
17600        return true;
17601    }
17602
17603    /**
17604     * Installs a package that's already on the system partition.
17605     */
17606    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
17607            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
17608            @Nullable PermissionsState origPermissionState, boolean writeSettings)
17609                    throws PackageManagerException {
17610        int parseFlags = mDefParseFlags
17611                | PackageParser.PARSE_MUST_BE_APK
17612                | PackageParser.PARSE_IS_SYSTEM
17613                | PackageParser.PARSE_IS_SYSTEM_DIR;
17614        if (isPrivileged || locationIsPrivileged(codePath)) {
17615            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17616        }
17617        if (locationIsOem(codePath)) {
17618            parseFlags |= PackageParser.PARSE_IS_OEM;
17619        }
17620
17621        final PackageParser.Package pkg =
17622                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
17623
17624        try {
17625            // update shared libraries for the newly re-installed system package
17626            updateSharedLibrariesLPr(pkg, null);
17627        } catch (PackageManagerException e) {
17628            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17629        }
17630
17631        prepareAppDataAfterInstallLIF(pkg);
17632
17633        // writer
17634        synchronized (mPackages) {
17635            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
17636
17637            // Propagate the permissions state as we do not want to drop on the floor
17638            // runtime permissions. The update permissions method below will take
17639            // care of removing obsolete permissions and grant install permissions.
17640            if (origPermissionState != null) {
17641                ps.getPermissionsState().copyFrom(origPermissionState);
17642            }
17643            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
17644                    mPermissionCallback);
17645
17646            final boolean applyUserRestrictions
17647                    = (allUserHandles != null) && (origUserHandles != null);
17648            if (applyUserRestrictions) {
17649                boolean installedStateChanged = false;
17650                if (DEBUG_REMOVE) {
17651                    Slog.d(TAG, "Propagating install state across reinstall");
17652                }
17653                for (int userId : allUserHandles) {
17654                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
17655                    if (DEBUG_REMOVE) {
17656                        Slog.d(TAG, "    user " + userId + " => " + installed);
17657                    }
17658                    if (installed != ps.getInstalled(userId)) {
17659                        installedStateChanged = true;
17660                    }
17661                    ps.setInstalled(installed, userId);
17662
17663                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17664                }
17665                // Regardless of writeSettings we need to ensure that this restriction
17666                // state propagation is persisted
17667                mSettings.writeAllUsersPackageRestrictionsLPr();
17668                if (installedStateChanged) {
17669                    mSettings.writeKernelMappingLPr(ps);
17670                }
17671            }
17672            // can downgrade to reader here
17673            if (writeSettings) {
17674                mSettings.writeLPr();
17675            }
17676        }
17677        return pkg;
17678    }
17679
17680    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17681            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17682            PackageRemovedInfo outInfo, boolean writeSettings,
17683            PackageParser.Package replacingPackage) {
17684        synchronized (mPackages) {
17685            if (outInfo != null) {
17686                outInfo.uid = ps.appId;
17687            }
17688
17689            if (outInfo != null && outInfo.removedChildPackages != null) {
17690                final int childCount = (ps.childPackageNames != null)
17691                        ? ps.childPackageNames.size() : 0;
17692                for (int i = 0; i < childCount; i++) {
17693                    String childPackageName = ps.childPackageNames.get(i);
17694                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17695                    if (childPs == null) {
17696                        return false;
17697                    }
17698                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17699                            childPackageName);
17700                    if (childInfo != null) {
17701                        childInfo.uid = childPs.appId;
17702                    }
17703                }
17704            }
17705        }
17706
17707        // Delete package data from internal structures and also remove data if flag is set
17708        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17709
17710        // Delete the child packages data
17711        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17712        for (int i = 0; i < childCount; i++) {
17713            PackageSetting childPs;
17714            synchronized (mPackages) {
17715                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17716            }
17717            if (childPs != null) {
17718                PackageRemovedInfo childOutInfo = (outInfo != null
17719                        && outInfo.removedChildPackages != null)
17720                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17721                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17722                        && (replacingPackage != null
17723                        && !replacingPackage.hasChildPackage(childPs.name))
17724                        ? flags & ~DELETE_KEEP_DATA : flags;
17725                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17726                        deleteFlags, writeSettings);
17727            }
17728        }
17729
17730        // Delete application code and resources only for parent packages
17731        if (ps.parentPackageName == null) {
17732            if (deleteCodeAndResources && (outInfo != null)) {
17733                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17734                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17735                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17736            }
17737        }
17738
17739        return true;
17740    }
17741
17742    @Override
17743    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17744            int userId) {
17745        mContext.enforceCallingOrSelfPermission(
17746                android.Manifest.permission.DELETE_PACKAGES, null);
17747        synchronized (mPackages) {
17748            // Cannot block uninstall of static shared libs as they are
17749            // considered a part of the using app (emulating static linking).
17750            // Also static libs are installed always on internal storage.
17751            PackageParser.Package pkg = mPackages.get(packageName);
17752            if (pkg != null && pkg.staticSharedLibName != null) {
17753                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17754                        + " providing static shared library: " + pkg.staticSharedLibName);
17755                return false;
17756            }
17757            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
17758            mSettings.writePackageRestrictionsLPr(userId);
17759        }
17760        return true;
17761    }
17762
17763    @Override
17764    public boolean getBlockUninstallForUser(String packageName, int userId) {
17765        synchronized (mPackages) {
17766            final PackageSetting ps = mSettings.mPackages.get(packageName);
17767            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
17768                return false;
17769            }
17770            return mSettings.getBlockUninstallLPr(userId, packageName);
17771        }
17772    }
17773
17774    @Override
17775    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17776        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
17777        synchronized (mPackages) {
17778            PackageSetting ps = mSettings.mPackages.get(packageName);
17779            if (ps == null) {
17780                Log.w(TAG, "Package doesn't exist: " + packageName);
17781                return false;
17782            }
17783            if (systemUserApp) {
17784                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17785            } else {
17786                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17787            }
17788            mSettings.writeLPr();
17789        }
17790        return true;
17791    }
17792
17793    /*
17794     * This method handles package deletion in general
17795     */
17796    private boolean deletePackageLIF(String packageName, UserHandle user,
17797            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17798            PackageRemovedInfo outInfo, boolean writeSettings,
17799            PackageParser.Package replacingPackage) {
17800        if (packageName == null) {
17801            Slog.w(TAG, "Attempt to delete null packageName.");
17802            return false;
17803        }
17804
17805        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17806
17807        PackageSetting ps;
17808        synchronized (mPackages) {
17809            ps = mSettings.mPackages.get(packageName);
17810            if (ps == null) {
17811                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17812                return false;
17813            }
17814
17815            if (ps.parentPackageName != null && (!isSystemApp(ps)
17816                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17817                if (DEBUG_REMOVE) {
17818                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17819                            + ((user == null) ? UserHandle.USER_ALL : user));
17820                }
17821                final int removedUserId = (user != null) ? user.getIdentifier()
17822                        : UserHandle.USER_ALL;
17823                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17824                    return false;
17825                }
17826                markPackageUninstalledForUserLPw(ps, user);
17827                scheduleWritePackageRestrictionsLocked(user);
17828                return true;
17829            }
17830        }
17831
17832        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17833                && user.getIdentifier() != UserHandle.USER_ALL)) {
17834            // The caller is asking that the package only be deleted for a single
17835            // user.  To do this, we just mark its uninstalled state and delete
17836            // its data. If this is a system app, we only allow this to happen if
17837            // they have set the special DELETE_SYSTEM_APP which requests different
17838            // semantics than normal for uninstalling system apps.
17839            markPackageUninstalledForUserLPw(ps, user);
17840
17841            if (!isSystemApp(ps)) {
17842                // Do not uninstall the APK if an app should be cached
17843                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17844                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17845                    // Other user still have this package installed, so all
17846                    // we need to do is clear this user's data and save that
17847                    // it is uninstalled.
17848                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17849                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17850                        return false;
17851                    }
17852                    scheduleWritePackageRestrictionsLocked(user);
17853                    return true;
17854                } else {
17855                    // We need to set it back to 'installed' so the uninstall
17856                    // broadcasts will be sent correctly.
17857                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17858                    ps.setInstalled(true, user.getIdentifier());
17859                    mSettings.writeKernelMappingLPr(ps);
17860                }
17861            } else {
17862                // This is a system app, so we assume that the
17863                // other users still have this package installed, so all
17864                // we need to do is clear this user's data and save that
17865                // it is uninstalled.
17866                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17867                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17868                    return false;
17869                }
17870                scheduleWritePackageRestrictionsLocked(user);
17871                return true;
17872            }
17873        }
17874
17875        // If we are deleting a composite package for all users, keep track
17876        // of result for each child.
17877        if (ps.childPackageNames != null && outInfo != null) {
17878            synchronized (mPackages) {
17879                final int childCount = ps.childPackageNames.size();
17880                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17881                for (int i = 0; i < childCount; i++) {
17882                    String childPackageName = ps.childPackageNames.get(i);
17883                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
17884                    childInfo.removedPackage = childPackageName;
17885                    childInfo.installerPackageName = ps.installerPackageName;
17886                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17887                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17888                    if (childPs != null) {
17889                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17890                    }
17891                }
17892            }
17893        }
17894
17895        boolean ret = false;
17896        if (isSystemApp(ps)) {
17897            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17898            // When an updated system application is deleted we delete the existing resources
17899            // as well and fall back to existing code in system partition
17900            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17901        } else {
17902            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17903            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17904                    outInfo, writeSettings, replacingPackage);
17905        }
17906
17907        // Take a note whether we deleted the package for all users
17908        if (outInfo != null) {
17909            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17910            if (outInfo.removedChildPackages != null) {
17911                synchronized (mPackages) {
17912                    final int childCount = outInfo.removedChildPackages.size();
17913                    for (int i = 0; i < childCount; i++) {
17914                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17915                        if (childInfo != null) {
17916                            childInfo.removedForAllUsers = mPackages.get(
17917                                    childInfo.removedPackage) == null;
17918                        }
17919                    }
17920                }
17921            }
17922            // If we uninstalled an update to a system app there may be some
17923            // child packages that appeared as they are declared in the system
17924            // app but were not declared in the update.
17925            if (isSystemApp(ps)) {
17926                synchronized (mPackages) {
17927                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17928                    final int childCount = (updatedPs.childPackageNames != null)
17929                            ? updatedPs.childPackageNames.size() : 0;
17930                    for (int i = 0; i < childCount; i++) {
17931                        String childPackageName = updatedPs.childPackageNames.get(i);
17932                        if (outInfo.removedChildPackages == null
17933                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17934                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17935                            if (childPs == null) {
17936                                continue;
17937                            }
17938                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17939                            installRes.name = childPackageName;
17940                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17941                            installRes.pkg = mPackages.get(childPackageName);
17942                            installRes.uid = childPs.pkg.applicationInfo.uid;
17943                            if (outInfo.appearedChildPackages == null) {
17944                                outInfo.appearedChildPackages = new ArrayMap<>();
17945                            }
17946                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17947                        }
17948                    }
17949                }
17950            }
17951        }
17952
17953        return ret;
17954    }
17955
17956    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17957        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17958                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17959        for (int nextUserId : userIds) {
17960            if (DEBUG_REMOVE) {
17961                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17962            }
17963            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17964                    false /*installed*/,
17965                    true /*stopped*/,
17966                    true /*notLaunched*/,
17967                    false /*hidden*/,
17968                    false /*suspended*/,
17969                    false /*instantApp*/,
17970                    false /*virtualPreload*/,
17971                    null /*lastDisableAppCaller*/,
17972                    null /*enabledComponents*/,
17973                    null /*disabledComponents*/,
17974                    ps.readUserState(nextUserId).domainVerificationStatus,
17975                    0, PackageManager.INSTALL_REASON_UNKNOWN);
17976        }
17977        mSettings.writeKernelMappingLPr(ps);
17978    }
17979
17980    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17981            PackageRemovedInfo outInfo) {
17982        final PackageParser.Package pkg;
17983        synchronized (mPackages) {
17984            pkg = mPackages.get(ps.name);
17985        }
17986
17987        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
17988                : new int[] {userId};
17989        for (int nextUserId : userIds) {
17990            if (DEBUG_REMOVE) {
17991                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
17992                        + nextUserId);
17993            }
17994
17995            destroyAppDataLIF(pkg, userId,
17996                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17997            destroyAppProfilesLIF(pkg, userId);
17998            clearDefaultBrowserIfNeededForUser(ps.name, userId);
17999            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18000            schedulePackageCleaning(ps.name, nextUserId, false);
18001            synchronized (mPackages) {
18002                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18003                    scheduleWritePackageRestrictionsLocked(nextUserId);
18004                }
18005                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18006            }
18007        }
18008
18009        if (outInfo != null) {
18010            outInfo.removedPackage = ps.name;
18011            outInfo.installerPackageName = ps.installerPackageName;
18012            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18013            outInfo.removedAppId = ps.appId;
18014            outInfo.removedUsers = userIds;
18015            outInfo.broadcastUsers = userIds;
18016        }
18017
18018        return true;
18019    }
18020
18021    private final class ClearStorageConnection implements ServiceConnection {
18022        IMediaContainerService mContainerService;
18023
18024        @Override
18025        public void onServiceConnected(ComponentName name, IBinder service) {
18026            synchronized (this) {
18027                mContainerService = IMediaContainerService.Stub
18028                        .asInterface(Binder.allowBlocking(service));
18029                notifyAll();
18030            }
18031        }
18032
18033        @Override
18034        public void onServiceDisconnected(ComponentName name) {
18035        }
18036    }
18037
18038    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18039        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18040
18041        final boolean mounted;
18042        if (Environment.isExternalStorageEmulated()) {
18043            mounted = true;
18044        } else {
18045            final String status = Environment.getExternalStorageState();
18046
18047            mounted = status.equals(Environment.MEDIA_MOUNTED)
18048                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18049        }
18050
18051        if (!mounted) {
18052            return;
18053        }
18054
18055        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18056        int[] users;
18057        if (userId == UserHandle.USER_ALL) {
18058            users = sUserManager.getUserIds();
18059        } else {
18060            users = new int[] { userId };
18061        }
18062        final ClearStorageConnection conn = new ClearStorageConnection();
18063        if (mContext.bindServiceAsUser(
18064                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18065            try {
18066                for (int curUser : users) {
18067                    long timeout = SystemClock.uptimeMillis() + 5000;
18068                    synchronized (conn) {
18069                        long now;
18070                        while (conn.mContainerService == null &&
18071                                (now = SystemClock.uptimeMillis()) < timeout) {
18072                            try {
18073                                conn.wait(timeout - now);
18074                            } catch (InterruptedException e) {
18075                            }
18076                        }
18077                    }
18078                    if (conn.mContainerService == null) {
18079                        return;
18080                    }
18081
18082                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18083                    clearDirectory(conn.mContainerService,
18084                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18085                    if (allData) {
18086                        clearDirectory(conn.mContainerService,
18087                                userEnv.buildExternalStorageAppDataDirs(packageName));
18088                        clearDirectory(conn.mContainerService,
18089                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18090                    }
18091                }
18092            } finally {
18093                mContext.unbindService(conn);
18094            }
18095        }
18096    }
18097
18098    @Override
18099    public void clearApplicationProfileData(String packageName) {
18100        enforceSystemOrRoot("Only the system can clear all profile data");
18101
18102        final PackageParser.Package pkg;
18103        synchronized (mPackages) {
18104            pkg = mPackages.get(packageName);
18105        }
18106
18107        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18108            synchronized (mInstallLock) {
18109                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18110            }
18111        }
18112    }
18113
18114    @Override
18115    public void clearApplicationUserData(final String packageName,
18116            final IPackageDataObserver observer, final int userId) {
18117        mContext.enforceCallingOrSelfPermission(
18118                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18119
18120        final int callingUid = Binder.getCallingUid();
18121        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18122                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18123
18124        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18125        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18126        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18127            throw new SecurityException("Cannot clear data for a protected package: "
18128                    + packageName);
18129        }
18130        // Queue up an async operation since the package deletion may take a little while.
18131        mHandler.post(new Runnable() {
18132            public void run() {
18133                mHandler.removeCallbacks(this);
18134                final boolean succeeded;
18135                if (!filterApp) {
18136                    try (PackageFreezer freezer = freezePackage(packageName,
18137                            "clearApplicationUserData")) {
18138                        synchronized (mInstallLock) {
18139                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18140                        }
18141                        clearExternalStorageDataSync(packageName, userId, true);
18142                        synchronized (mPackages) {
18143                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18144                                    packageName, userId);
18145                        }
18146                    }
18147                    if (succeeded) {
18148                        // invoke DeviceStorageMonitor's update method to clear any notifications
18149                        DeviceStorageMonitorInternal dsm = LocalServices
18150                                .getService(DeviceStorageMonitorInternal.class);
18151                        if (dsm != null) {
18152                            dsm.checkMemory();
18153                        }
18154                    }
18155                } else {
18156                    succeeded = false;
18157                }
18158                if (observer != null) {
18159                    try {
18160                        observer.onRemoveCompleted(packageName, succeeded);
18161                    } catch (RemoteException e) {
18162                        Log.i(TAG, "Observer no longer exists.");
18163                    }
18164                } //end if observer
18165            } //end run
18166        });
18167    }
18168
18169    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18170        if (packageName == null) {
18171            Slog.w(TAG, "Attempt to delete null packageName.");
18172            return false;
18173        }
18174
18175        // Try finding details about the requested package
18176        PackageParser.Package pkg;
18177        synchronized (mPackages) {
18178            pkg = mPackages.get(packageName);
18179            if (pkg == null) {
18180                final PackageSetting ps = mSettings.mPackages.get(packageName);
18181                if (ps != null) {
18182                    pkg = ps.pkg;
18183                }
18184            }
18185
18186            if (pkg == null) {
18187                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18188                return false;
18189            }
18190
18191            PackageSetting ps = (PackageSetting) pkg.mExtras;
18192            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18193        }
18194
18195        clearAppDataLIF(pkg, userId,
18196                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18197
18198        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18199        removeKeystoreDataIfNeeded(userId, appId);
18200
18201        UserManagerInternal umInternal = getUserManagerInternal();
18202        final int flags;
18203        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18204            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18205        } else if (umInternal.isUserRunning(userId)) {
18206            flags = StorageManager.FLAG_STORAGE_DE;
18207        } else {
18208            flags = 0;
18209        }
18210        prepareAppDataContentsLIF(pkg, userId, flags);
18211
18212        return true;
18213    }
18214
18215    /**
18216     * Reverts user permission state changes (permissions and flags) in
18217     * all packages for a given user.
18218     *
18219     * @param userId The device user for which to do a reset.
18220     */
18221    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18222        final int packageCount = mPackages.size();
18223        for (int i = 0; i < packageCount; i++) {
18224            PackageParser.Package pkg = mPackages.valueAt(i);
18225            PackageSetting ps = (PackageSetting) pkg.mExtras;
18226            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18227        }
18228    }
18229
18230    private void resetNetworkPolicies(int userId) {
18231        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18232    }
18233
18234    /**
18235     * Reverts user permission state changes (permissions and flags).
18236     *
18237     * @param ps The package for which to reset.
18238     * @param userId The device user for which to do a reset.
18239     */
18240    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18241            final PackageSetting ps, final int userId) {
18242        if (ps.pkg == null) {
18243            return;
18244        }
18245
18246        // These are flags that can change base on user actions.
18247        final int userSettableMask = FLAG_PERMISSION_USER_SET
18248                | FLAG_PERMISSION_USER_FIXED
18249                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18250                | FLAG_PERMISSION_REVIEW_REQUIRED;
18251
18252        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18253                | FLAG_PERMISSION_POLICY_FIXED;
18254
18255        boolean writeInstallPermissions = false;
18256        boolean writeRuntimePermissions = false;
18257
18258        final int permissionCount = ps.pkg.requestedPermissions.size();
18259        for (int i = 0; i < permissionCount; i++) {
18260            final String permName = ps.pkg.requestedPermissions.get(i);
18261            final BasePermission bp =
18262                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18263            if (bp == null) {
18264                continue;
18265            }
18266
18267            // If shared user we just reset the state to which only this app contributed.
18268            if (ps.sharedUser != null) {
18269                boolean used = false;
18270                final int packageCount = ps.sharedUser.packages.size();
18271                for (int j = 0; j < packageCount; j++) {
18272                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18273                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18274                            && pkg.pkg.requestedPermissions.contains(permName)) {
18275                        used = true;
18276                        break;
18277                    }
18278                }
18279                if (used) {
18280                    continue;
18281                }
18282            }
18283
18284            final PermissionsState permissionsState = ps.getPermissionsState();
18285
18286            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18287
18288            // Always clear the user settable flags.
18289            final boolean hasInstallState =
18290                    permissionsState.getInstallPermissionState(permName) != null;
18291            // If permission review is enabled and this is a legacy app, mark the
18292            // permission as requiring a review as this is the initial state.
18293            int flags = 0;
18294            if (mSettings.mPermissions.mPermissionReviewRequired
18295                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18296                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18297            }
18298            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18299                if (hasInstallState) {
18300                    writeInstallPermissions = true;
18301                } else {
18302                    writeRuntimePermissions = true;
18303                }
18304            }
18305
18306            // Below is only runtime permission handling.
18307            if (!bp.isRuntime()) {
18308                continue;
18309            }
18310
18311            // Never clobber system or policy.
18312            if ((oldFlags & policyOrSystemFlags) != 0) {
18313                continue;
18314            }
18315
18316            // If this permission was granted by default, make sure it is.
18317            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18318                if (permissionsState.grantRuntimePermission(bp, userId)
18319                        != PERMISSION_OPERATION_FAILURE) {
18320                    writeRuntimePermissions = true;
18321                }
18322            // If permission review is enabled the permissions for a legacy apps
18323            // are represented as constantly granted runtime ones, so don't revoke.
18324            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18325                // Otherwise, reset the permission.
18326                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18327                switch (revokeResult) {
18328                    case PERMISSION_OPERATION_SUCCESS:
18329                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18330                        writeRuntimePermissions = true;
18331                        final int appId = ps.appId;
18332                        mHandler.post(new Runnable() {
18333                            @Override
18334                            public void run() {
18335                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18336                            }
18337                        });
18338                    } break;
18339                }
18340            }
18341        }
18342
18343        // Synchronously write as we are taking permissions away.
18344        if (writeRuntimePermissions) {
18345            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18346        }
18347
18348        // Synchronously write as we are taking permissions away.
18349        if (writeInstallPermissions) {
18350            mSettings.writeLPr();
18351        }
18352    }
18353
18354    /**
18355     * Remove entries from the keystore daemon. Will only remove it if the
18356     * {@code appId} is valid.
18357     */
18358    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18359        if (appId < 0) {
18360            return;
18361        }
18362
18363        final KeyStore keyStore = KeyStore.getInstance();
18364        if (keyStore != null) {
18365            if (userId == UserHandle.USER_ALL) {
18366                for (final int individual : sUserManager.getUserIds()) {
18367                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18368                }
18369            } else {
18370                keyStore.clearUid(UserHandle.getUid(userId, appId));
18371            }
18372        } else {
18373            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18374        }
18375    }
18376
18377    @Override
18378    public void deleteApplicationCacheFiles(final String packageName,
18379            final IPackageDataObserver observer) {
18380        final int userId = UserHandle.getCallingUserId();
18381        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18382    }
18383
18384    @Override
18385    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18386            final IPackageDataObserver observer) {
18387        final int callingUid = Binder.getCallingUid();
18388        mContext.enforceCallingOrSelfPermission(
18389                android.Manifest.permission.DELETE_CACHE_FILES, null);
18390        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18391                /* requireFullPermission= */ true, /* checkShell= */ false,
18392                "delete application cache files");
18393        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18394                android.Manifest.permission.ACCESS_INSTANT_APPS);
18395
18396        final PackageParser.Package pkg;
18397        synchronized (mPackages) {
18398            pkg = mPackages.get(packageName);
18399        }
18400
18401        // Queue up an async operation since the package deletion may take a little while.
18402        mHandler.post(new Runnable() {
18403            public void run() {
18404                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18405                boolean doClearData = true;
18406                if (ps != null) {
18407                    final boolean targetIsInstantApp =
18408                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18409                    doClearData = !targetIsInstantApp
18410                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18411                }
18412                if (doClearData) {
18413                    synchronized (mInstallLock) {
18414                        final int flags = StorageManager.FLAG_STORAGE_DE
18415                                | StorageManager.FLAG_STORAGE_CE;
18416                        // We're only clearing cache files, so we don't care if the
18417                        // app is unfrozen and still able to run
18418                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18419                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18420                    }
18421                    clearExternalStorageDataSync(packageName, userId, false);
18422                }
18423                if (observer != null) {
18424                    try {
18425                        observer.onRemoveCompleted(packageName, true);
18426                    } catch (RemoteException e) {
18427                        Log.i(TAG, "Observer no longer exists.");
18428                    }
18429                }
18430            }
18431        });
18432    }
18433
18434    @Override
18435    public void getPackageSizeInfo(final String packageName, int userHandle,
18436            final IPackageStatsObserver observer) {
18437        throw new UnsupportedOperationException(
18438                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18439    }
18440
18441    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18442        final PackageSetting ps;
18443        synchronized (mPackages) {
18444            ps = mSettings.mPackages.get(packageName);
18445            if (ps == null) {
18446                Slog.w(TAG, "Failed to find settings for " + packageName);
18447                return false;
18448            }
18449        }
18450
18451        final String[] packageNames = { packageName };
18452        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18453        final String[] codePaths = { ps.codePathString };
18454
18455        try {
18456            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18457                    ps.appId, ceDataInodes, codePaths, stats);
18458
18459            // For now, ignore code size of packages on system partition
18460            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18461                stats.codeSize = 0;
18462            }
18463
18464            // External clients expect these to be tracked separately
18465            stats.dataSize -= stats.cacheSize;
18466
18467        } catch (InstallerException e) {
18468            Slog.w(TAG, String.valueOf(e));
18469            return false;
18470        }
18471
18472        return true;
18473    }
18474
18475    private int getUidTargetSdkVersionLockedLPr(int uid) {
18476        Object obj = mSettings.getUserIdLPr(uid);
18477        if (obj instanceof SharedUserSetting) {
18478            final SharedUserSetting sus = (SharedUserSetting) obj;
18479            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18480            final Iterator<PackageSetting> it = sus.packages.iterator();
18481            while (it.hasNext()) {
18482                final PackageSetting ps = it.next();
18483                if (ps.pkg != null) {
18484                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18485                    if (v < vers) vers = v;
18486                }
18487            }
18488            return vers;
18489        } else if (obj instanceof PackageSetting) {
18490            final PackageSetting ps = (PackageSetting) obj;
18491            if (ps.pkg != null) {
18492                return ps.pkg.applicationInfo.targetSdkVersion;
18493            }
18494        }
18495        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18496    }
18497
18498    @Override
18499    public void addPreferredActivity(IntentFilter filter, int match,
18500            ComponentName[] set, ComponentName activity, int userId) {
18501        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18502                "Adding preferred");
18503    }
18504
18505    private void addPreferredActivityInternal(IntentFilter filter, int match,
18506            ComponentName[] set, ComponentName activity, boolean always, int userId,
18507            String opname) {
18508        // writer
18509        int callingUid = Binder.getCallingUid();
18510        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18511                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18512        if (filter.countActions() == 0) {
18513            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18514            return;
18515        }
18516        synchronized (mPackages) {
18517            if (mContext.checkCallingOrSelfPermission(
18518                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18519                    != PackageManager.PERMISSION_GRANTED) {
18520                if (getUidTargetSdkVersionLockedLPr(callingUid)
18521                        < Build.VERSION_CODES.FROYO) {
18522                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18523                            + callingUid);
18524                    return;
18525                }
18526                mContext.enforceCallingOrSelfPermission(
18527                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18528            }
18529
18530            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18531            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18532                    + userId + ":");
18533            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18534            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18535            scheduleWritePackageRestrictionsLocked(userId);
18536            postPreferredActivityChangedBroadcast(userId);
18537        }
18538    }
18539
18540    private void postPreferredActivityChangedBroadcast(int userId) {
18541        mHandler.post(() -> {
18542            final IActivityManager am = ActivityManager.getService();
18543            if (am == null) {
18544                return;
18545            }
18546
18547            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18548            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18549            try {
18550                am.broadcastIntent(null, intent, null, null,
18551                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18552                        null, false, false, userId);
18553            } catch (RemoteException e) {
18554            }
18555        });
18556    }
18557
18558    @Override
18559    public void replacePreferredActivity(IntentFilter filter, int match,
18560            ComponentName[] set, ComponentName activity, int userId) {
18561        if (filter.countActions() != 1) {
18562            throw new IllegalArgumentException(
18563                    "replacePreferredActivity expects filter to have only 1 action.");
18564        }
18565        if (filter.countDataAuthorities() != 0
18566                || filter.countDataPaths() != 0
18567                || filter.countDataSchemes() > 1
18568                || filter.countDataTypes() != 0) {
18569            throw new IllegalArgumentException(
18570                    "replacePreferredActivity expects filter to have no data authorities, " +
18571                    "paths, or types; and at most one scheme.");
18572        }
18573
18574        final int callingUid = Binder.getCallingUid();
18575        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18576                true /* requireFullPermission */, false /* checkShell */,
18577                "replace preferred activity");
18578        synchronized (mPackages) {
18579            if (mContext.checkCallingOrSelfPermission(
18580                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18581                    != PackageManager.PERMISSION_GRANTED) {
18582                if (getUidTargetSdkVersionLockedLPr(callingUid)
18583                        < Build.VERSION_CODES.FROYO) {
18584                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18585                            + Binder.getCallingUid());
18586                    return;
18587                }
18588                mContext.enforceCallingOrSelfPermission(
18589                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18590            }
18591
18592            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18593            if (pir != null) {
18594                // Get all of the existing entries that exactly match this filter.
18595                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18596                if (existing != null && existing.size() == 1) {
18597                    PreferredActivity cur = existing.get(0);
18598                    if (DEBUG_PREFERRED) {
18599                        Slog.i(TAG, "Checking replace of preferred:");
18600                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18601                        if (!cur.mPref.mAlways) {
18602                            Slog.i(TAG, "  -- CUR; not mAlways!");
18603                        } else {
18604                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18605                            Slog.i(TAG, "  -- CUR: mSet="
18606                                    + Arrays.toString(cur.mPref.mSetComponents));
18607                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18608                            Slog.i(TAG, "  -- NEW: mMatch="
18609                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18610                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18611                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18612                        }
18613                    }
18614                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18615                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18616                            && cur.mPref.sameSet(set)) {
18617                        // Setting the preferred activity to what it happens to be already
18618                        if (DEBUG_PREFERRED) {
18619                            Slog.i(TAG, "Replacing with same preferred activity "
18620                                    + cur.mPref.mShortComponent + " for user "
18621                                    + userId + ":");
18622                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18623                        }
18624                        return;
18625                    }
18626                }
18627
18628                if (existing != null) {
18629                    if (DEBUG_PREFERRED) {
18630                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18631                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18632                    }
18633                    for (int i = 0; i < existing.size(); i++) {
18634                        PreferredActivity pa = existing.get(i);
18635                        if (DEBUG_PREFERRED) {
18636                            Slog.i(TAG, "Removing existing preferred activity "
18637                                    + pa.mPref.mComponent + ":");
18638                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18639                        }
18640                        pir.removeFilter(pa);
18641                    }
18642                }
18643            }
18644            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18645                    "Replacing preferred");
18646        }
18647    }
18648
18649    @Override
18650    public void clearPackagePreferredActivities(String packageName) {
18651        final int callingUid = Binder.getCallingUid();
18652        if (getInstantAppPackageName(callingUid) != null) {
18653            return;
18654        }
18655        // writer
18656        synchronized (mPackages) {
18657            PackageParser.Package pkg = mPackages.get(packageName);
18658            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
18659                if (mContext.checkCallingOrSelfPermission(
18660                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18661                        != PackageManager.PERMISSION_GRANTED) {
18662                    if (getUidTargetSdkVersionLockedLPr(callingUid)
18663                            < Build.VERSION_CODES.FROYO) {
18664                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18665                                + callingUid);
18666                        return;
18667                    }
18668                    mContext.enforceCallingOrSelfPermission(
18669                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18670                }
18671            }
18672            final PackageSetting ps = mSettings.getPackageLPr(packageName);
18673            if (ps != null
18674                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
18675                return;
18676            }
18677            int user = UserHandle.getCallingUserId();
18678            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18679                scheduleWritePackageRestrictionsLocked(user);
18680            }
18681        }
18682    }
18683
18684    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18685    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18686        ArrayList<PreferredActivity> removed = null;
18687        boolean changed = false;
18688        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18689            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18690            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18691            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18692                continue;
18693            }
18694            Iterator<PreferredActivity> it = pir.filterIterator();
18695            while (it.hasNext()) {
18696                PreferredActivity pa = it.next();
18697                // Mark entry for removal only if it matches the package name
18698                // and the entry is of type "always".
18699                if (packageName == null ||
18700                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18701                                && pa.mPref.mAlways)) {
18702                    if (removed == null) {
18703                        removed = new ArrayList<PreferredActivity>();
18704                    }
18705                    removed.add(pa);
18706                }
18707            }
18708            if (removed != null) {
18709                for (int j=0; j<removed.size(); j++) {
18710                    PreferredActivity pa = removed.get(j);
18711                    pir.removeFilter(pa);
18712                }
18713                changed = true;
18714            }
18715        }
18716        if (changed) {
18717            postPreferredActivityChangedBroadcast(userId);
18718        }
18719        return changed;
18720    }
18721
18722    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18723    private void clearIntentFilterVerificationsLPw(int userId) {
18724        final int packageCount = mPackages.size();
18725        for (int i = 0; i < packageCount; i++) {
18726            PackageParser.Package pkg = mPackages.valueAt(i);
18727            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18728        }
18729    }
18730
18731    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18732    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18733        if (userId == UserHandle.USER_ALL) {
18734            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18735                    sUserManager.getUserIds())) {
18736                for (int oneUserId : sUserManager.getUserIds()) {
18737                    scheduleWritePackageRestrictionsLocked(oneUserId);
18738                }
18739            }
18740        } else {
18741            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18742                scheduleWritePackageRestrictionsLocked(userId);
18743            }
18744        }
18745    }
18746
18747    /** Clears state for all users, and touches intent filter verification policy */
18748    void clearDefaultBrowserIfNeeded(String packageName) {
18749        for (int oneUserId : sUserManager.getUserIds()) {
18750            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
18751        }
18752    }
18753
18754    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
18755        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
18756        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
18757            if (packageName.equals(defaultBrowserPackageName)) {
18758                setDefaultBrowserPackageName(null, userId);
18759            }
18760        }
18761    }
18762
18763    @Override
18764    public void resetApplicationPreferences(int userId) {
18765        mContext.enforceCallingOrSelfPermission(
18766                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18767        final long identity = Binder.clearCallingIdentity();
18768        // writer
18769        try {
18770            synchronized (mPackages) {
18771                clearPackagePreferredActivitiesLPw(null, userId);
18772                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18773                // TODO: We have to reset the default SMS and Phone. This requires
18774                // significant refactoring to keep all default apps in the package
18775                // manager (cleaner but more work) or have the services provide
18776                // callbacks to the package manager to request a default app reset.
18777                applyFactoryDefaultBrowserLPw(userId);
18778                clearIntentFilterVerificationsLPw(userId);
18779                primeDomainVerificationsLPw(userId);
18780                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18781                scheduleWritePackageRestrictionsLocked(userId);
18782            }
18783            resetNetworkPolicies(userId);
18784        } finally {
18785            Binder.restoreCallingIdentity(identity);
18786        }
18787    }
18788
18789    @Override
18790    public int getPreferredActivities(List<IntentFilter> outFilters,
18791            List<ComponentName> outActivities, String packageName) {
18792        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
18793            return 0;
18794        }
18795        int num = 0;
18796        final int userId = UserHandle.getCallingUserId();
18797        // reader
18798        synchronized (mPackages) {
18799            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18800            if (pir != null) {
18801                final Iterator<PreferredActivity> it = pir.filterIterator();
18802                while (it.hasNext()) {
18803                    final PreferredActivity pa = it.next();
18804                    if (packageName == null
18805                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18806                                    && pa.mPref.mAlways)) {
18807                        if (outFilters != null) {
18808                            outFilters.add(new IntentFilter(pa));
18809                        }
18810                        if (outActivities != null) {
18811                            outActivities.add(pa.mPref.mComponent);
18812                        }
18813                    }
18814                }
18815            }
18816        }
18817
18818        return num;
18819    }
18820
18821    @Override
18822    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18823            int userId) {
18824        int callingUid = Binder.getCallingUid();
18825        if (callingUid != Process.SYSTEM_UID) {
18826            throw new SecurityException(
18827                    "addPersistentPreferredActivity can only be run by the system");
18828        }
18829        if (filter.countActions() == 0) {
18830            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18831            return;
18832        }
18833        synchronized (mPackages) {
18834            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18835                    ":");
18836            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18837            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18838                    new PersistentPreferredActivity(filter, activity));
18839            scheduleWritePackageRestrictionsLocked(userId);
18840            postPreferredActivityChangedBroadcast(userId);
18841        }
18842    }
18843
18844    @Override
18845    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18846        int callingUid = Binder.getCallingUid();
18847        if (callingUid != Process.SYSTEM_UID) {
18848            throw new SecurityException(
18849                    "clearPackagePersistentPreferredActivities can only be run by the system");
18850        }
18851        ArrayList<PersistentPreferredActivity> removed = null;
18852        boolean changed = false;
18853        synchronized (mPackages) {
18854            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18855                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18856                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18857                        .valueAt(i);
18858                if (userId != thisUserId) {
18859                    continue;
18860                }
18861                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18862                while (it.hasNext()) {
18863                    PersistentPreferredActivity ppa = it.next();
18864                    // Mark entry for removal only if it matches the package name.
18865                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18866                        if (removed == null) {
18867                            removed = new ArrayList<PersistentPreferredActivity>();
18868                        }
18869                        removed.add(ppa);
18870                    }
18871                }
18872                if (removed != null) {
18873                    for (int j=0; j<removed.size(); j++) {
18874                        PersistentPreferredActivity ppa = removed.get(j);
18875                        ppir.removeFilter(ppa);
18876                    }
18877                    changed = true;
18878                }
18879            }
18880
18881            if (changed) {
18882                scheduleWritePackageRestrictionsLocked(userId);
18883                postPreferredActivityChangedBroadcast(userId);
18884            }
18885        }
18886    }
18887
18888    /**
18889     * Common machinery for picking apart a restored XML blob and passing
18890     * it to a caller-supplied functor to be applied to the running system.
18891     */
18892    private void restoreFromXml(XmlPullParser parser, int userId,
18893            String expectedStartTag, BlobXmlRestorer functor)
18894            throws IOException, XmlPullParserException {
18895        int type;
18896        while ((type = parser.next()) != XmlPullParser.START_TAG
18897                && type != XmlPullParser.END_DOCUMENT) {
18898        }
18899        if (type != XmlPullParser.START_TAG) {
18900            // oops didn't find a start tag?!
18901            if (DEBUG_BACKUP) {
18902                Slog.e(TAG, "Didn't find start tag during restore");
18903            }
18904            return;
18905        }
18906Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18907        // this is supposed to be TAG_PREFERRED_BACKUP
18908        if (!expectedStartTag.equals(parser.getName())) {
18909            if (DEBUG_BACKUP) {
18910                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18911            }
18912            return;
18913        }
18914
18915        // skip interfering stuff, then we're aligned with the backing implementation
18916        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18917Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18918        functor.apply(parser, userId);
18919    }
18920
18921    private interface BlobXmlRestorer {
18922        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18923    }
18924
18925    /**
18926     * Non-Binder method, support for the backup/restore mechanism: write the
18927     * full set of preferred activities in its canonical XML format.  Returns the
18928     * XML output as a byte array, or null if there is none.
18929     */
18930    @Override
18931    public byte[] getPreferredActivityBackup(int userId) {
18932        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18933            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18934        }
18935
18936        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18937        try {
18938            final XmlSerializer serializer = new FastXmlSerializer();
18939            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18940            serializer.startDocument(null, true);
18941            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18942
18943            synchronized (mPackages) {
18944                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18945            }
18946
18947            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18948            serializer.endDocument();
18949            serializer.flush();
18950        } catch (Exception e) {
18951            if (DEBUG_BACKUP) {
18952                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18953            }
18954            return null;
18955        }
18956
18957        return dataStream.toByteArray();
18958    }
18959
18960    @Override
18961    public void restorePreferredActivities(byte[] backup, int userId) {
18962        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18963            throw new SecurityException("Only the system may call restorePreferredActivities()");
18964        }
18965
18966        try {
18967            final XmlPullParser parser = Xml.newPullParser();
18968            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18969            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18970                    new BlobXmlRestorer() {
18971                        @Override
18972                        public void apply(XmlPullParser parser, int userId)
18973                                throws XmlPullParserException, IOException {
18974                            synchronized (mPackages) {
18975                                mSettings.readPreferredActivitiesLPw(parser, userId);
18976                            }
18977                        }
18978                    } );
18979        } catch (Exception e) {
18980            if (DEBUG_BACKUP) {
18981                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18982            }
18983        }
18984    }
18985
18986    /**
18987     * Non-Binder method, support for the backup/restore mechanism: write the
18988     * default browser (etc) settings in its canonical XML format.  Returns the default
18989     * browser XML representation as a byte array, or null if there is none.
18990     */
18991    @Override
18992    public byte[] getDefaultAppsBackup(int userId) {
18993        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18994            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
18995        }
18996
18997        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18998        try {
18999            final XmlSerializer serializer = new FastXmlSerializer();
19000            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19001            serializer.startDocument(null, true);
19002            serializer.startTag(null, TAG_DEFAULT_APPS);
19003
19004            synchronized (mPackages) {
19005                mSettings.writeDefaultAppsLPr(serializer, userId);
19006            }
19007
19008            serializer.endTag(null, TAG_DEFAULT_APPS);
19009            serializer.endDocument();
19010            serializer.flush();
19011        } catch (Exception e) {
19012            if (DEBUG_BACKUP) {
19013                Slog.e(TAG, "Unable to write default apps for backup", e);
19014            }
19015            return null;
19016        }
19017
19018        return dataStream.toByteArray();
19019    }
19020
19021    @Override
19022    public void restoreDefaultApps(byte[] backup, int userId) {
19023        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19024            throw new SecurityException("Only the system may call restoreDefaultApps()");
19025        }
19026
19027        try {
19028            final XmlPullParser parser = Xml.newPullParser();
19029            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19030            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19031                    new BlobXmlRestorer() {
19032                        @Override
19033                        public void apply(XmlPullParser parser, int userId)
19034                                throws XmlPullParserException, IOException {
19035                            synchronized (mPackages) {
19036                                mSettings.readDefaultAppsLPw(parser, userId);
19037                            }
19038                        }
19039                    } );
19040        } catch (Exception e) {
19041            if (DEBUG_BACKUP) {
19042                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19043            }
19044        }
19045    }
19046
19047    @Override
19048    public byte[] getIntentFilterVerificationBackup(int userId) {
19049        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19050            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19051        }
19052
19053        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19054        try {
19055            final XmlSerializer serializer = new FastXmlSerializer();
19056            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19057            serializer.startDocument(null, true);
19058            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19059
19060            synchronized (mPackages) {
19061                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19062            }
19063
19064            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19065            serializer.endDocument();
19066            serializer.flush();
19067        } catch (Exception e) {
19068            if (DEBUG_BACKUP) {
19069                Slog.e(TAG, "Unable to write default apps for backup", e);
19070            }
19071            return null;
19072        }
19073
19074        return dataStream.toByteArray();
19075    }
19076
19077    @Override
19078    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19079        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19080            throw new SecurityException("Only the system may call restorePreferredActivities()");
19081        }
19082
19083        try {
19084            final XmlPullParser parser = Xml.newPullParser();
19085            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19086            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19087                    new BlobXmlRestorer() {
19088                        @Override
19089                        public void apply(XmlPullParser parser, int userId)
19090                                throws XmlPullParserException, IOException {
19091                            synchronized (mPackages) {
19092                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19093                                mSettings.writeLPr();
19094                            }
19095                        }
19096                    } );
19097        } catch (Exception e) {
19098            if (DEBUG_BACKUP) {
19099                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19100            }
19101        }
19102    }
19103
19104    @Override
19105    public byte[] getPermissionGrantBackup(int userId) {
19106        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19107            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19108        }
19109
19110        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19111        try {
19112            final XmlSerializer serializer = new FastXmlSerializer();
19113            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19114            serializer.startDocument(null, true);
19115            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19116
19117            synchronized (mPackages) {
19118                serializeRuntimePermissionGrantsLPr(serializer, userId);
19119            }
19120
19121            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19122            serializer.endDocument();
19123            serializer.flush();
19124        } catch (Exception e) {
19125            if (DEBUG_BACKUP) {
19126                Slog.e(TAG, "Unable to write default apps for backup", e);
19127            }
19128            return null;
19129        }
19130
19131        return dataStream.toByteArray();
19132    }
19133
19134    @Override
19135    public void restorePermissionGrants(byte[] backup, int userId) {
19136        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19137            throw new SecurityException("Only the system may call restorePermissionGrants()");
19138        }
19139
19140        try {
19141            final XmlPullParser parser = Xml.newPullParser();
19142            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19143            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19144                    new BlobXmlRestorer() {
19145                        @Override
19146                        public void apply(XmlPullParser parser, int userId)
19147                                throws XmlPullParserException, IOException {
19148                            synchronized (mPackages) {
19149                                processRestoredPermissionGrantsLPr(parser, userId);
19150                            }
19151                        }
19152                    } );
19153        } catch (Exception e) {
19154            if (DEBUG_BACKUP) {
19155                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19156            }
19157        }
19158    }
19159
19160    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19161            throws IOException {
19162        serializer.startTag(null, TAG_ALL_GRANTS);
19163
19164        final int N = mSettings.mPackages.size();
19165        for (int i = 0; i < N; i++) {
19166            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19167            boolean pkgGrantsKnown = false;
19168
19169            PermissionsState packagePerms = ps.getPermissionsState();
19170
19171            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19172                final int grantFlags = state.getFlags();
19173                // only look at grants that are not system/policy fixed
19174                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19175                    final boolean isGranted = state.isGranted();
19176                    // And only back up the user-twiddled state bits
19177                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19178                        final String packageName = mSettings.mPackages.keyAt(i);
19179                        if (!pkgGrantsKnown) {
19180                            serializer.startTag(null, TAG_GRANT);
19181                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19182                            pkgGrantsKnown = true;
19183                        }
19184
19185                        final boolean userSet =
19186                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19187                        final boolean userFixed =
19188                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19189                        final boolean revoke =
19190                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19191
19192                        serializer.startTag(null, TAG_PERMISSION);
19193                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19194                        if (isGranted) {
19195                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19196                        }
19197                        if (userSet) {
19198                            serializer.attribute(null, ATTR_USER_SET, "true");
19199                        }
19200                        if (userFixed) {
19201                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19202                        }
19203                        if (revoke) {
19204                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19205                        }
19206                        serializer.endTag(null, TAG_PERMISSION);
19207                    }
19208                }
19209            }
19210
19211            if (pkgGrantsKnown) {
19212                serializer.endTag(null, TAG_GRANT);
19213            }
19214        }
19215
19216        serializer.endTag(null, TAG_ALL_GRANTS);
19217    }
19218
19219    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19220            throws XmlPullParserException, IOException {
19221        String pkgName = null;
19222        int outerDepth = parser.getDepth();
19223        int type;
19224        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19225                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19226            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19227                continue;
19228            }
19229
19230            final String tagName = parser.getName();
19231            if (tagName.equals(TAG_GRANT)) {
19232                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19233                if (DEBUG_BACKUP) {
19234                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19235                }
19236            } else if (tagName.equals(TAG_PERMISSION)) {
19237
19238                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19239                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19240
19241                int newFlagSet = 0;
19242                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19243                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19244                }
19245                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19246                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19247                }
19248                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19249                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19250                }
19251                if (DEBUG_BACKUP) {
19252                    Slog.v(TAG, "  + Restoring grant:"
19253                            + " pkg=" + pkgName
19254                            + " perm=" + permName
19255                            + " granted=" + isGranted
19256                            + " bits=0x" + Integer.toHexString(newFlagSet));
19257                }
19258                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19259                if (ps != null) {
19260                    // Already installed so we apply the grant immediately
19261                    if (DEBUG_BACKUP) {
19262                        Slog.v(TAG, "        + already installed; applying");
19263                    }
19264                    PermissionsState perms = ps.getPermissionsState();
19265                    BasePermission bp =
19266                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19267                    if (bp != null) {
19268                        if (isGranted) {
19269                            perms.grantRuntimePermission(bp, userId);
19270                        }
19271                        if (newFlagSet != 0) {
19272                            perms.updatePermissionFlags(
19273                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19274                        }
19275                    }
19276                } else {
19277                    // Need to wait for post-restore install to apply the grant
19278                    if (DEBUG_BACKUP) {
19279                        Slog.v(TAG, "        - not yet installed; saving for later");
19280                    }
19281                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19282                            isGranted, newFlagSet, userId);
19283                }
19284            } else {
19285                PackageManagerService.reportSettingsProblem(Log.WARN,
19286                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19287                XmlUtils.skipCurrentTag(parser);
19288            }
19289        }
19290
19291        scheduleWriteSettingsLocked();
19292        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19293    }
19294
19295    @Override
19296    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19297            int sourceUserId, int targetUserId, int flags) {
19298        mContext.enforceCallingOrSelfPermission(
19299                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19300        int callingUid = Binder.getCallingUid();
19301        enforceOwnerRights(ownerPackage, callingUid);
19302        PackageManagerServiceUtils.enforceShellRestriction(
19303                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19304        if (intentFilter.countActions() == 0) {
19305            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19306            return;
19307        }
19308        synchronized (mPackages) {
19309            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19310                    ownerPackage, targetUserId, flags);
19311            CrossProfileIntentResolver resolver =
19312                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19313            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19314            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19315            if (existing != null) {
19316                int size = existing.size();
19317                for (int i = 0; i < size; i++) {
19318                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19319                        return;
19320                    }
19321                }
19322            }
19323            resolver.addFilter(newFilter);
19324            scheduleWritePackageRestrictionsLocked(sourceUserId);
19325        }
19326    }
19327
19328    @Override
19329    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19330        mContext.enforceCallingOrSelfPermission(
19331                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19332        final int callingUid = Binder.getCallingUid();
19333        enforceOwnerRights(ownerPackage, callingUid);
19334        PackageManagerServiceUtils.enforceShellRestriction(
19335                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19336        synchronized (mPackages) {
19337            CrossProfileIntentResolver resolver =
19338                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19339            ArraySet<CrossProfileIntentFilter> set =
19340                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19341            for (CrossProfileIntentFilter filter : set) {
19342                if (filter.getOwnerPackage().equals(ownerPackage)) {
19343                    resolver.removeFilter(filter);
19344                }
19345            }
19346            scheduleWritePackageRestrictionsLocked(sourceUserId);
19347        }
19348    }
19349
19350    // Enforcing that callingUid is owning pkg on userId
19351    private void enforceOwnerRights(String pkg, int callingUid) {
19352        // The system owns everything.
19353        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19354            return;
19355        }
19356        final int callingUserId = UserHandle.getUserId(callingUid);
19357        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19358        if (pi == null) {
19359            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19360                    + callingUserId);
19361        }
19362        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19363            throw new SecurityException("Calling uid " + callingUid
19364                    + " does not own package " + pkg);
19365        }
19366    }
19367
19368    @Override
19369    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19370        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19371            return null;
19372        }
19373        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19374    }
19375
19376    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19377        UserManagerService ums = UserManagerService.getInstance();
19378        if (ums != null) {
19379            final UserInfo parent = ums.getProfileParent(userId);
19380            final int launcherUid = (parent != null) ? parent.id : userId;
19381            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19382            if (launcherComponent != null) {
19383                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19384                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19385                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19386                        .setPackage(launcherComponent.getPackageName());
19387                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19388            }
19389        }
19390    }
19391
19392    /**
19393     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19394     * then reports the most likely home activity or null if there are more than one.
19395     */
19396    private ComponentName getDefaultHomeActivity(int userId) {
19397        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19398        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19399        if (cn != null) {
19400            return cn;
19401        }
19402
19403        // Find the launcher with the highest priority and return that component if there are no
19404        // other home activity with the same priority.
19405        int lastPriority = Integer.MIN_VALUE;
19406        ComponentName lastComponent = null;
19407        final int size = allHomeCandidates.size();
19408        for (int i = 0; i < size; i++) {
19409            final ResolveInfo ri = allHomeCandidates.get(i);
19410            if (ri.priority > lastPriority) {
19411                lastComponent = ri.activityInfo.getComponentName();
19412                lastPriority = ri.priority;
19413            } else if (ri.priority == lastPriority) {
19414                // Two components found with same priority.
19415                lastComponent = null;
19416            }
19417        }
19418        return lastComponent;
19419    }
19420
19421    private Intent getHomeIntent() {
19422        Intent intent = new Intent(Intent.ACTION_MAIN);
19423        intent.addCategory(Intent.CATEGORY_HOME);
19424        intent.addCategory(Intent.CATEGORY_DEFAULT);
19425        return intent;
19426    }
19427
19428    private IntentFilter getHomeFilter() {
19429        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19430        filter.addCategory(Intent.CATEGORY_HOME);
19431        filter.addCategory(Intent.CATEGORY_DEFAULT);
19432        return filter;
19433    }
19434
19435    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19436            int userId) {
19437        Intent intent  = getHomeIntent();
19438        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19439                PackageManager.GET_META_DATA, userId);
19440        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19441                true, false, false, userId);
19442
19443        allHomeCandidates.clear();
19444        if (list != null) {
19445            for (ResolveInfo ri : list) {
19446                allHomeCandidates.add(ri);
19447            }
19448        }
19449        return (preferred == null || preferred.activityInfo == null)
19450                ? null
19451                : new ComponentName(preferred.activityInfo.packageName,
19452                        preferred.activityInfo.name);
19453    }
19454
19455    @Override
19456    public void setHomeActivity(ComponentName comp, int userId) {
19457        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19458            return;
19459        }
19460        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19461        getHomeActivitiesAsUser(homeActivities, userId);
19462
19463        boolean found = false;
19464
19465        final int size = homeActivities.size();
19466        final ComponentName[] set = new ComponentName[size];
19467        for (int i = 0; i < size; i++) {
19468            final ResolveInfo candidate = homeActivities.get(i);
19469            final ActivityInfo info = candidate.activityInfo;
19470            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19471            set[i] = activityName;
19472            if (!found && activityName.equals(comp)) {
19473                found = true;
19474            }
19475        }
19476        if (!found) {
19477            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19478                    + userId);
19479        }
19480        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19481                set, comp, userId);
19482    }
19483
19484    private @Nullable String getSetupWizardPackageName() {
19485        final Intent intent = new Intent(Intent.ACTION_MAIN);
19486        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19487
19488        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19489                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19490                        | MATCH_DISABLED_COMPONENTS,
19491                UserHandle.myUserId());
19492        if (matches.size() == 1) {
19493            return matches.get(0).getComponentInfo().packageName;
19494        } else {
19495            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19496                    + ": matches=" + matches);
19497            return null;
19498        }
19499    }
19500
19501    private @Nullable String getStorageManagerPackageName() {
19502        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19503
19504        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19505                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19506                        | MATCH_DISABLED_COMPONENTS,
19507                UserHandle.myUserId());
19508        if (matches.size() == 1) {
19509            return matches.get(0).getComponentInfo().packageName;
19510        } else {
19511            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19512                    + matches.size() + ": matches=" + matches);
19513            return null;
19514        }
19515    }
19516
19517    @Override
19518    public void setApplicationEnabledSetting(String appPackageName,
19519            int newState, int flags, int userId, String callingPackage) {
19520        if (!sUserManager.exists(userId)) return;
19521        if (callingPackage == null) {
19522            callingPackage = Integer.toString(Binder.getCallingUid());
19523        }
19524        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19525    }
19526
19527    @Override
19528    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19529        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19530        synchronized (mPackages) {
19531            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19532            if (pkgSetting != null) {
19533                pkgSetting.setUpdateAvailable(updateAvailable);
19534            }
19535        }
19536    }
19537
19538    @Override
19539    public void setComponentEnabledSetting(ComponentName componentName,
19540            int newState, int flags, int userId) {
19541        if (!sUserManager.exists(userId)) return;
19542        setEnabledSetting(componentName.getPackageName(),
19543                componentName.getClassName(), newState, flags, userId, null);
19544    }
19545
19546    private void setEnabledSetting(final String packageName, String className, int newState,
19547            final int flags, int userId, String callingPackage) {
19548        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19549              || newState == COMPONENT_ENABLED_STATE_ENABLED
19550              || newState == COMPONENT_ENABLED_STATE_DISABLED
19551              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19552              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19553            throw new IllegalArgumentException("Invalid new component state: "
19554                    + newState);
19555        }
19556        PackageSetting pkgSetting;
19557        final int callingUid = Binder.getCallingUid();
19558        final int permission;
19559        if (callingUid == Process.SYSTEM_UID) {
19560            permission = PackageManager.PERMISSION_GRANTED;
19561        } else {
19562            permission = mContext.checkCallingOrSelfPermission(
19563                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19564        }
19565        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19566                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19567        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19568        boolean sendNow = false;
19569        boolean isApp = (className == null);
19570        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19571        String componentName = isApp ? packageName : className;
19572        int packageUid = -1;
19573        ArrayList<String> components;
19574
19575        // reader
19576        synchronized (mPackages) {
19577            pkgSetting = mSettings.mPackages.get(packageName);
19578            if (pkgSetting == null) {
19579                if (!isCallerInstantApp) {
19580                    if (className == null) {
19581                        throw new IllegalArgumentException("Unknown package: " + packageName);
19582                    }
19583                    throw new IllegalArgumentException(
19584                            "Unknown component: " + packageName + "/" + className);
19585                } else {
19586                    // throw SecurityException to prevent leaking package information
19587                    throw new SecurityException(
19588                            "Attempt to change component state; "
19589                            + "pid=" + Binder.getCallingPid()
19590                            + ", uid=" + callingUid
19591                            + (className == null
19592                                    ? ", package=" + packageName
19593                                    : ", component=" + packageName + "/" + className));
19594                }
19595            }
19596        }
19597
19598        // Limit who can change which apps
19599        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
19600            // Don't allow apps that don't have permission to modify other apps
19601            if (!allowedByPermission
19602                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
19603                throw new SecurityException(
19604                        "Attempt to change component state; "
19605                        + "pid=" + Binder.getCallingPid()
19606                        + ", uid=" + callingUid
19607                        + (className == null
19608                                ? ", package=" + packageName
19609                                : ", component=" + packageName + "/" + className));
19610            }
19611            // Don't allow changing protected packages.
19612            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19613                throw new SecurityException("Cannot disable a protected package: " + packageName);
19614            }
19615        }
19616
19617        synchronized (mPackages) {
19618            if (callingUid == Process.SHELL_UID
19619                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19620                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19621                // unless it is a test package.
19622                int oldState = pkgSetting.getEnabled(userId);
19623                if (className == null
19624                        &&
19625                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19626                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19627                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19628                        &&
19629                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19630                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
19631                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19632                    // ok
19633                } else {
19634                    throw new SecurityException(
19635                            "Shell cannot change component state for " + packageName + "/"
19636                                    + className + " to " + newState);
19637                }
19638            }
19639        }
19640        if (className == null) {
19641            // We're dealing with an application/package level state change
19642            synchronized (mPackages) {
19643                if (pkgSetting.getEnabled(userId) == newState) {
19644                    // Nothing to do
19645                    return;
19646                }
19647            }
19648            // If we're enabling a system stub, there's a little more work to do.
19649            // Prior to enabling the package, we need to decompress the APK(s) to the
19650            // data partition and then replace the version on the system partition.
19651            final PackageParser.Package deletedPkg = pkgSetting.pkg;
19652            final boolean isSystemStub = deletedPkg.isStub
19653                    && deletedPkg.isSystem();
19654            if (isSystemStub
19655                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19656                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
19657                final File codePath = decompressPackage(deletedPkg);
19658                if (codePath == null) {
19659                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
19660                    return;
19661                }
19662                // TODO remove direct parsing of the package object during internal cleanup
19663                // of scan package
19664                // We need to call parse directly here for no other reason than we need
19665                // the new package in order to disable the old one [we use the information
19666                // for some internal optimization to optionally create a new package setting
19667                // object on replace]. However, we can't get the package from the scan
19668                // because the scan modifies live structures and we need to remove the
19669                // old [system] package from the system before a scan can be attempted.
19670                // Once scan is indempotent we can remove this parse and use the package
19671                // object we scanned, prior to adding it to package settings.
19672                final PackageParser pp = new PackageParser();
19673                pp.setSeparateProcesses(mSeparateProcesses);
19674                pp.setDisplayMetrics(mMetrics);
19675                pp.setCallback(mPackageParserCallback);
19676                final PackageParser.Package tmpPkg;
19677                try {
19678                    final int parseFlags = mDefParseFlags
19679                            | PackageParser.PARSE_MUST_BE_APK
19680                            | PackageParser.PARSE_IS_SYSTEM
19681                            | PackageParser.PARSE_IS_SYSTEM_DIR;
19682                    tmpPkg = pp.parsePackage(codePath, parseFlags);
19683                } catch (PackageParserException e) {
19684                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
19685                    return;
19686                }
19687                synchronized (mInstallLock) {
19688                    // Disable the stub and remove any package entries
19689                    removePackageLI(deletedPkg, true);
19690                    synchronized (mPackages) {
19691                        disableSystemPackageLPw(deletedPkg, tmpPkg);
19692                    }
19693                    final PackageParser.Package pkg;
19694                    try (PackageFreezer freezer =
19695                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19696                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
19697                                | PackageParser.PARSE_ENFORCE_CODE;
19698                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
19699                                0 /*currentTime*/, null /*user*/);
19700                        prepareAppDataAfterInstallLIF(pkg);
19701                        synchronized (mPackages) {
19702                            try {
19703                                updateSharedLibrariesLPr(pkg, null);
19704                            } catch (PackageManagerException e) {
19705                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
19706                            }
19707                            mPermissionManager.updatePermissions(
19708                                    pkg.packageName, pkg, true, mPackages.values(),
19709                                    mPermissionCallback);
19710                            mSettings.writeLPr();
19711                        }
19712                    } catch (PackageManagerException e) {
19713                        // Whoops! Something went wrong; try to roll back to the stub
19714                        Slog.w(TAG, "Failed to install compressed system package:"
19715                                + pkgSetting.name, e);
19716                        // Remove the failed install
19717                        removeCodePathLI(codePath);
19718
19719                        // Install the system package
19720                        try (PackageFreezer freezer =
19721                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19722                            synchronized (mPackages) {
19723                                // NOTE: The system package always needs to be enabled; even
19724                                // if it's for a compressed stub. If we don't, installing the
19725                                // system package fails during scan [scanning checks the disabled
19726                                // packages]. We will reverse this later, after we've "installed"
19727                                // the stub.
19728                                // This leaves us in a fragile state; the stub should never be
19729                                // enabled, so, cross your fingers and hope nothing goes wrong
19730                                // until we can disable the package later.
19731                                enableSystemPackageLPw(deletedPkg);
19732                            }
19733                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
19734                                    false /*isPrivileged*/, null /*allUserHandles*/,
19735                                    null /*origUserHandles*/, null /*origPermissionsState*/,
19736                                    true /*writeSettings*/);
19737                        } catch (PackageManagerException pme) {
19738                            Slog.w(TAG, "Failed to restore system package:"
19739                                    + deletedPkg.packageName, pme);
19740                        } finally {
19741                            synchronized (mPackages) {
19742                                mSettings.disableSystemPackageLPw(
19743                                        deletedPkg.packageName, true /*replaced*/);
19744                                mSettings.writeLPr();
19745                            }
19746                        }
19747                        return;
19748                    }
19749                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
19750                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19751                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19752                    mDexManager.notifyPackageUpdated(pkg.packageName,
19753                            pkg.baseCodePath, pkg.splitCodePaths);
19754                }
19755            }
19756            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19757                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19758                // Don't care about who enables an app.
19759                callingPackage = null;
19760            }
19761            synchronized (mPackages) {
19762                pkgSetting.setEnabled(newState, userId, callingPackage);
19763            }
19764        } else {
19765            synchronized (mPackages) {
19766                // We're dealing with a component level state change
19767                // First, verify that this is a valid class name.
19768                PackageParser.Package pkg = pkgSetting.pkg;
19769                if (pkg == null || !pkg.hasComponentClassName(className)) {
19770                    if (pkg != null &&
19771                            pkg.applicationInfo.targetSdkVersion >=
19772                                    Build.VERSION_CODES.JELLY_BEAN) {
19773                        throw new IllegalArgumentException("Component class " + className
19774                                + " does not exist in " + packageName);
19775                    } else {
19776                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19777                                + className + " does not exist in " + packageName);
19778                    }
19779                }
19780                switch (newState) {
19781                    case COMPONENT_ENABLED_STATE_ENABLED:
19782                        if (!pkgSetting.enableComponentLPw(className, userId)) {
19783                            return;
19784                        }
19785                        break;
19786                    case COMPONENT_ENABLED_STATE_DISABLED:
19787                        if (!pkgSetting.disableComponentLPw(className, userId)) {
19788                            return;
19789                        }
19790                        break;
19791                    case COMPONENT_ENABLED_STATE_DEFAULT:
19792                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
19793                            return;
19794                        }
19795                        break;
19796                    default:
19797                        Slog.e(TAG, "Invalid new component state: " + newState);
19798                        return;
19799                }
19800            }
19801        }
19802        synchronized (mPackages) {
19803            scheduleWritePackageRestrictionsLocked(userId);
19804            updateSequenceNumberLP(pkgSetting, new int[] { userId });
19805            final long callingId = Binder.clearCallingIdentity();
19806            try {
19807                updateInstantAppInstallerLocked(packageName);
19808            } finally {
19809                Binder.restoreCallingIdentity(callingId);
19810            }
19811            components = mPendingBroadcasts.get(userId, packageName);
19812            final boolean newPackage = components == null;
19813            if (newPackage) {
19814                components = new ArrayList<String>();
19815            }
19816            if (!components.contains(componentName)) {
19817                components.add(componentName);
19818            }
19819            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19820                sendNow = true;
19821                // Purge entry from pending broadcast list if another one exists already
19822                // since we are sending one right away.
19823                mPendingBroadcasts.remove(userId, packageName);
19824            } else {
19825                if (newPackage) {
19826                    mPendingBroadcasts.put(userId, packageName, components);
19827                }
19828                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19829                    // Schedule a message
19830                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19831                }
19832            }
19833        }
19834
19835        long callingId = Binder.clearCallingIdentity();
19836        try {
19837            if (sendNow) {
19838                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19839                sendPackageChangedBroadcast(packageName,
19840                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19841            }
19842        } finally {
19843            Binder.restoreCallingIdentity(callingId);
19844        }
19845    }
19846
19847    @Override
19848    public void flushPackageRestrictionsAsUser(int userId) {
19849        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19850            return;
19851        }
19852        if (!sUserManager.exists(userId)) {
19853            return;
19854        }
19855        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19856                false /* checkShell */, "flushPackageRestrictions");
19857        synchronized (mPackages) {
19858            mSettings.writePackageRestrictionsLPr(userId);
19859            mDirtyUsers.remove(userId);
19860            if (mDirtyUsers.isEmpty()) {
19861                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19862            }
19863        }
19864    }
19865
19866    private void sendPackageChangedBroadcast(String packageName,
19867            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19868        if (DEBUG_INSTALL)
19869            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19870                    + componentNames);
19871        Bundle extras = new Bundle(4);
19872        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19873        String nameList[] = new String[componentNames.size()];
19874        componentNames.toArray(nameList);
19875        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19876        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19877        extras.putInt(Intent.EXTRA_UID, packageUid);
19878        // If this is not reporting a change of the overall package, then only send it
19879        // to registered receivers.  We don't want to launch a swath of apps for every
19880        // little component state change.
19881        final int flags = !componentNames.contains(packageName)
19882                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19883        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19884                new int[] {UserHandle.getUserId(packageUid)});
19885    }
19886
19887    @Override
19888    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19889        if (!sUserManager.exists(userId)) return;
19890        final int callingUid = Binder.getCallingUid();
19891        if (getInstantAppPackageName(callingUid) != null) {
19892            return;
19893        }
19894        final int permission = mContext.checkCallingOrSelfPermission(
19895                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19896        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19897        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19898                true /* requireFullPermission */, true /* checkShell */, "stop package");
19899        // writer
19900        synchronized (mPackages) {
19901            final PackageSetting ps = mSettings.mPackages.get(packageName);
19902            if (!filterAppAccessLPr(ps, callingUid, userId)
19903                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19904                            allowedByPermission, callingUid, userId)) {
19905                scheduleWritePackageRestrictionsLocked(userId);
19906            }
19907        }
19908    }
19909
19910    @Override
19911    public String getInstallerPackageName(String packageName) {
19912        final int callingUid = Binder.getCallingUid();
19913        if (getInstantAppPackageName(callingUid) != null) {
19914            return null;
19915        }
19916        // reader
19917        synchronized (mPackages) {
19918            final PackageSetting ps = mSettings.mPackages.get(packageName);
19919            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19920                return null;
19921            }
19922            return mSettings.getInstallerPackageNameLPr(packageName);
19923        }
19924    }
19925
19926    public boolean isOrphaned(String packageName) {
19927        // reader
19928        synchronized (mPackages) {
19929            return mSettings.isOrphaned(packageName);
19930        }
19931    }
19932
19933    @Override
19934    public int getApplicationEnabledSetting(String packageName, int userId) {
19935        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19936        int callingUid = Binder.getCallingUid();
19937        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19938                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19939        // reader
19940        synchronized (mPackages) {
19941            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
19942                return COMPONENT_ENABLED_STATE_DISABLED;
19943            }
19944            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19945        }
19946    }
19947
19948    @Override
19949    public int getComponentEnabledSetting(ComponentName component, int userId) {
19950        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19951        int callingUid = Binder.getCallingUid();
19952        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19953                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
19954        synchronized (mPackages) {
19955            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
19956                    component, TYPE_UNKNOWN, userId)) {
19957                return COMPONENT_ENABLED_STATE_DISABLED;
19958            }
19959            return mSettings.getComponentEnabledSettingLPr(component, userId);
19960        }
19961    }
19962
19963    @Override
19964    public void enterSafeMode() {
19965        enforceSystemOrRoot("Only the system can request entering safe mode");
19966
19967        if (!mSystemReady) {
19968            mSafeMode = true;
19969        }
19970    }
19971
19972    @Override
19973    public void systemReady() {
19974        enforceSystemOrRoot("Only the system can claim the system is ready");
19975
19976        mSystemReady = true;
19977        final ContentResolver resolver = mContext.getContentResolver();
19978        ContentObserver co = new ContentObserver(mHandler) {
19979            @Override
19980            public void onChange(boolean selfChange) {
19981                mEphemeralAppsDisabled =
19982                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
19983                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
19984            }
19985        };
19986        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
19987                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
19988                false, co, UserHandle.USER_SYSTEM);
19989        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
19990                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
19991        co.onChange(true);
19992
19993        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19994        // disabled after already being started.
19995        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19996                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19997
19998        // Read the compatibilty setting when the system is ready.
19999        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20000                mContext.getContentResolver(),
20001                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20002        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20003        if (DEBUG_SETTINGS) {
20004            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20005        }
20006
20007        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20008
20009        synchronized (mPackages) {
20010            // Verify that all of the preferred activity components actually
20011            // exist.  It is possible for applications to be updated and at
20012            // that point remove a previously declared activity component that
20013            // had been set as a preferred activity.  We try to clean this up
20014            // the next time we encounter that preferred activity, but it is
20015            // possible for the user flow to never be able to return to that
20016            // situation so here we do a sanity check to make sure we haven't
20017            // left any junk around.
20018            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20019            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20020                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20021                removed.clear();
20022                for (PreferredActivity pa : pir.filterSet()) {
20023                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20024                        removed.add(pa);
20025                    }
20026                }
20027                if (removed.size() > 0) {
20028                    for (int r=0; r<removed.size(); r++) {
20029                        PreferredActivity pa = removed.get(r);
20030                        Slog.w(TAG, "Removing dangling preferred activity: "
20031                                + pa.mPref.mComponent);
20032                        pir.removeFilter(pa);
20033                    }
20034                    mSettings.writePackageRestrictionsLPr(
20035                            mSettings.mPreferredActivities.keyAt(i));
20036                }
20037            }
20038
20039            for (int userId : UserManagerService.getInstance().getUserIds()) {
20040                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20041                    grantPermissionsUserIds = ArrayUtils.appendInt(
20042                            grantPermissionsUserIds, userId);
20043                }
20044            }
20045        }
20046        sUserManager.systemReady();
20047
20048        // If we upgraded grant all default permissions before kicking off.
20049        for (int userId : grantPermissionsUserIds) {
20050            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
20051        }
20052
20053        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20054            // If we did not grant default permissions, we preload from this the
20055            // default permission exceptions lazily to ensure we don't hit the
20056            // disk on a new user creation.
20057            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20058        }
20059
20060        // Now that we've scanned all packages, and granted any default
20061        // permissions, ensure permissions are updated. Beware of dragons if you
20062        // try optimizing this.
20063        synchronized (mPackages) {
20064            mPermissionManager.updateAllPermissions(
20065                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20066                    mPermissionCallback);
20067        }
20068
20069        // Kick off any messages waiting for system ready
20070        if (mPostSystemReadyMessages != null) {
20071            for (Message msg : mPostSystemReadyMessages) {
20072                msg.sendToTarget();
20073            }
20074            mPostSystemReadyMessages = null;
20075        }
20076
20077        // Watch for external volumes that come and go over time
20078        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20079        storage.registerListener(mStorageListener);
20080
20081        mInstallerService.systemReady();
20082        mPackageDexOptimizer.systemReady();
20083
20084        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20085                StorageManagerInternal.class);
20086        StorageManagerInternal.addExternalStoragePolicy(
20087                new StorageManagerInternal.ExternalStorageMountPolicy() {
20088            @Override
20089            public int getMountMode(int uid, String packageName) {
20090                if (Process.isIsolated(uid)) {
20091                    return Zygote.MOUNT_EXTERNAL_NONE;
20092                }
20093                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20094                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20095                }
20096                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20097                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20098                }
20099                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20100                    return Zygote.MOUNT_EXTERNAL_READ;
20101                }
20102                return Zygote.MOUNT_EXTERNAL_WRITE;
20103            }
20104
20105            @Override
20106            public boolean hasExternalStorage(int uid, String packageName) {
20107                return true;
20108            }
20109        });
20110
20111        // Now that we're mostly running, clean up stale users and apps
20112        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20113        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20114
20115        mPermissionManager.systemReady();
20116    }
20117
20118    public void waitForAppDataPrepared() {
20119        if (mPrepareAppDataFuture == null) {
20120            return;
20121        }
20122        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20123        mPrepareAppDataFuture = null;
20124    }
20125
20126    @Override
20127    public boolean isSafeMode() {
20128        // allow instant applications
20129        return mSafeMode;
20130    }
20131
20132    @Override
20133    public boolean hasSystemUidErrors() {
20134        // allow instant applications
20135        return mHasSystemUidErrors;
20136    }
20137
20138    static String arrayToString(int[] array) {
20139        StringBuffer buf = new StringBuffer(128);
20140        buf.append('[');
20141        if (array != null) {
20142            for (int i=0; i<array.length; i++) {
20143                if (i > 0) buf.append(", ");
20144                buf.append(array[i]);
20145            }
20146        }
20147        buf.append(']');
20148        return buf.toString();
20149    }
20150
20151    @Override
20152    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20153            FileDescriptor err, String[] args, ShellCallback callback,
20154            ResultReceiver resultReceiver) {
20155        (new PackageManagerShellCommand(this)).exec(
20156                this, in, out, err, args, callback, resultReceiver);
20157    }
20158
20159    @Override
20160    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20161        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20162
20163        DumpState dumpState = new DumpState();
20164        boolean fullPreferred = false;
20165        boolean checkin = false;
20166
20167        String packageName = null;
20168        ArraySet<String> permissionNames = null;
20169
20170        int opti = 0;
20171        while (opti < args.length) {
20172            String opt = args[opti];
20173            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20174                break;
20175            }
20176            opti++;
20177
20178            if ("-a".equals(opt)) {
20179                // Right now we only know how to print all.
20180            } else if ("-h".equals(opt)) {
20181                pw.println("Package manager dump options:");
20182                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20183                pw.println("    --checkin: dump for a checkin");
20184                pw.println("    -f: print details of intent filters");
20185                pw.println("    -h: print this help");
20186                pw.println("  cmd may be one of:");
20187                pw.println("    l[ibraries]: list known shared libraries");
20188                pw.println("    f[eatures]: list device features");
20189                pw.println("    k[eysets]: print known keysets");
20190                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20191                pw.println("    perm[issions]: dump permissions");
20192                pw.println("    permission [name ...]: dump declaration and use of given permission");
20193                pw.println("    pref[erred]: print preferred package settings");
20194                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20195                pw.println("    prov[iders]: dump content providers");
20196                pw.println("    p[ackages]: dump installed packages");
20197                pw.println("    s[hared-users]: dump shared user IDs");
20198                pw.println("    m[essages]: print collected runtime messages");
20199                pw.println("    v[erifiers]: print package verifier info");
20200                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20201                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20202                pw.println("    version: print database version info");
20203                pw.println("    write: write current settings now");
20204                pw.println("    installs: details about install sessions");
20205                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20206                pw.println("    dexopt: dump dexopt state");
20207                pw.println("    compiler-stats: dump compiler statistics");
20208                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20209                pw.println("    <package.name>: info about given package");
20210                return;
20211            } else if ("--checkin".equals(opt)) {
20212                checkin = true;
20213            } else if ("-f".equals(opt)) {
20214                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20215            } else if ("--proto".equals(opt)) {
20216                dumpProto(fd);
20217                return;
20218            } else {
20219                pw.println("Unknown argument: " + opt + "; use -h for help");
20220            }
20221        }
20222
20223        // Is the caller requesting to dump a particular piece of data?
20224        if (opti < args.length) {
20225            String cmd = args[opti];
20226            opti++;
20227            // Is this a package name?
20228            if ("android".equals(cmd) || cmd.contains(".")) {
20229                packageName = cmd;
20230                // When dumping a single package, we always dump all of its
20231                // filter information since the amount of data will be reasonable.
20232                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20233            } else if ("check-permission".equals(cmd)) {
20234                if (opti >= args.length) {
20235                    pw.println("Error: check-permission missing permission argument");
20236                    return;
20237                }
20238                String perm = args[opti];
20239                opti++;
20240                if (opti >= args.length) {
20241                    pw.println("Error: check-permission missing package argument");
20242                    return;
20243                }
20244
20245                String pkg = args[opti];
20246                opti++;
20247                int user = UserHandle.getUserId(Binder.getCallingUid());
20248                if (opti < args.length) {
20249                    try {
20250                        user = Integer.parseInt(args[opti]);
20251                    } catch (NumberFormatException e) {
20252                        pw.println("Error: check-permission user argument is not a number: "
20253                                + args[opti]);
20254                        return;
20255                    }
20256                }
20257
20258                // Normalize package name to handle renamed packages and static libs
20259                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20260
20261                pw.println(checkPermission(perm, pkg, user));
20262                return;
20263            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20264                dumpState.setDump(DumpState.DUMP_LIBS);
20265            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20266                dumpState.setDump(DumpState.DUMP_FEATURES);
20267            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20268                if (opti >= args.length) {
20269                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20270                            | DumpState.DUMP_SERVICE_RESOLVERS
20271                            | DumpState.DUMP_RECEIVER_RESOLVERS
20272                            | DumpState.DUMP_CONTENT_RESOLVERS);
20273                } else {
20274                    while (opti < args.length) {
20275                        String name = args[opti];
20276                        if ("a".equals(name) || "activity".equals(name)) {
20277                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20278                        } else if ("s".equals(name) || "service".equals(name)) {
20279                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20280                        } else if ("r".equals(name) || "receiver".equals(name)) {
20281                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20282                        } else if ("c".equals(name) || "content".equals(name)) {
20283                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20284                        } else {
20285                            pw.println("Error: unknown resolver table type: " + name);
20286                            return;
20287                        }
20288                        opti++;
20289                    }
20290                }
20291            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20292                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20293            } else if ("permission".equals(cmd)) {
20294                if (opti >= args.length) {
20295                    pw.println("Error: permission requires permission name");
20296                    return;
20297                }
20298                permissionNames = new ArraySet<>();
20299                while (opti < args.length) {
20300                    permissionNames.add(args[opti]);
20301                    opti++;
20302                }
20303                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20304                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20305            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20306                dumpState.setDump(DumpState.DUMP_PREFERRED);
20307            } else if ("preferred-xml".equals(cmd)) {
20308                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20309                if (opti < args.length && "--full".equals(args[opti])) {
20310                    fullPreferred = true;
20311                    opti++;
20312                }
20313            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20314                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20315            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20316                dumpState.setDump(DumpState.DUMP_PACKAGES);
20317            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20318                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20319            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20320                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20321            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20322                dumpState.setDump(DumpState.DUMP_MESSAGES);
20323            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20324                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20325            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20326                    || "intent-filter-verifiers".equals(cmd)) {
20327                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20328            } else if ("version".equals(cmd)) {
20329                dumpState.setDump(DumpState.DUMP_VERSION);
20330            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20331                dumpState.setDump(DumpState.DUMP_KEYSETS);
20332            } else if ("installs".equals(cmd)) {
20333                dumpState.setDump(DumpState.DUMP_INSTALLS);
20334            } else if ("frozen".equals(cmd)) {
20335                dumpState.setDump(DumpState.DUMP_FROZEN);
20336            } else if ("volumes".equals(cmd)) {
20337                dumpState.setDump(DumpState.DUMP_VOLUMES);
20338            } else if ("dexopt".equals(cmd)) {
20339                dumpState.setDump(DumpState.DUMP_DEXOPT);
20340            } else if ("compiler-stats".equals(cmd)) {
20341                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20342            } else if ("changes".equals(cmd)) {
20343                dumpState.setDump(DumpState.DUMP_CHANGES);
20344            } else if ("write".equals(cmd)) {
20345                synchronized (mPackages) {
20346                    mSettings.writeLPr();
20347                    pw.println("Settings written.");
20348                    return;
20349                }
20350            }
20351        }
20352
20353        if (checkin) {
20354            pw.println("vers,1");
20355        }
20356
20357        // reader
20358        synchronized (mPackages) {
20359            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20360                if (!checkin) {
20361                    if (dumpState.onTitlePrinted())
20362                        pw.println();
20363                    pw.println("Database versions:");
20364                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20365                }
20366            }
20367
20368            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20369                if (!checkin) {
20370                    if (dumpState.onTitlePrinted())
20371                        pw.println();
20372                    pw.println("Verifiers:");
20373                    pw.print("  Required: ");
20374                    pw.print(mRequiredVerifierPackage);
20375                    pw.print(" (uid=");
20376                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20377                            UserHandle.USER_SYSTEM));
20378                    pw.println(")");
20379                } else if (mRequiredVerifierPackage != null) {
20380                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20381                    pw.print(",");
20382                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20383                            UserHandle.USER_SYSTEM));
20384                }
20385            }
20386
20387            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20388                    packageName == null) {
20389                if (mIntentFilterVerifierComponent != null) {
20390                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20391                    if (!checkin) {
20392                        if (dumpState.onTitlePrinted())
20393                            pw.println();
20394                        pw.println("Intent Filter Verifier:");
20395                        pw.print("  Using: ");
20396                        pw.print(verifierPackageName);
20397                        pw.print(" (uid=");
20398                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20399                                UserHandle.USER_SYSTEM));
20400                        pw.println(")");
20401                    } else if (verifierPackageName != null) {
20402                        pw.print("ifv,"); pw.print(verifierPackageName);
20403                        pw.print(",");
20404                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20405                                UserHandle.USER_SYSTEM));
20406                    }
20407                } else {
20408                    pw.println();
20409                    pw.println("No Intent Filter Verifier available!");
20410                }
20411            }
20412
20413            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20414                boolean printedHeader = false;
20415                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20416                while (it.hasNext()) {
20417                    String libName = it.next();
20418                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20419                    if (versionedLib == null) {
20420                        continue;
20421                    }
20422                    final int versionCount = versionedLib.size();
20423                    for (int i = 0; i < versionCount; i++) {
20424                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20425                        if (!checkin) {
20426                            if (!printedHeader) {
20427                                if (dumpState.onTitlePrinted())
20428                                    pw.println();
20429                                pw.println("Libraries:");
20430                                printedHeader = true;
20431                            }
20432                            pw.print("  ");
20433                        } else {
20434                            pw.print("lib,");
20435                        }
20436                        pw.print(libEntry.info.getName());
20437                        if (libEntry.info.isStatic()) {
20438                            pw.print(" version=" + libEntry.info.getVersion());
20439                        }
20440                        if (!checkin) {
20441                            pw.print(" -> ");
20442                        }
20443                        if (libEntry.path != null) {
20444                            pw.print(" (jar) ");
20445                            pw.print(libEntry.path);
20446                        } else {
20447                            pw.print(" (apk) ");
20448                            pw.print(libEntry.apk);
20449                        }
20450                        pw.println();
20451                    }
20452                }
20453            }
20454
20455            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20456                if (dumpState.onTitlePrinted())
20457                    pw.println();
20458                if (!checkin) {
20459                    pw.println("Features:");
20460                }
20461
20462                synchronized (mAvailableFeatures) {
20463                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20464                        if (checkin) {
20465                            pw.print("feat,");
20466                            pw.print(feat.name);
20467                            pw.print(",");
20468                            pw.println(feat.version);
20469                        } else {
20470                            pw.print("  ");
20471                            pw.print(feat.name);
20472                            if (feat.version > 0) {
20473                                pw.print(" version=");
20474                                pw.print(feat.version);
20475                            }
20476                            pw.println();
20477                        }
20478                    }
20479                }
20480            }
20481
20482            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20483                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20484                        : "Activity Resolver Table:", "  ", packageName,
20485                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20486                    dumpState.setTitlePrinted(true);
20487                }
20488            }
20489            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20490                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20491                        : "Receiver Resolver Table:", "  ", packageName,
20492                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20493                    dumpState.setTitlePrinted(true);
20494                }
20495            }
20496            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20497                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20498                        : "Service Resolver Table:", "  ", packageName,
20499                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20500                    dumpState.setTitlePrinted(true);
20501                }
20502            }
20503            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20504                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20505                        : "Provider Resolver Table:", "  ", packageName,
20506                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20507                    dumpState.setTitlePrinted(true);
20508                }
20509            }
20510
20511            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20512                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20513                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20514                    int user = mSettings.mPreferredActivities.keyAt(i);
20515                    if (pir.dump(pw,
20516                            dumpState.getTitlePrinted()
20517                                ? "\nPreferred Activities User " + user + ":"
20518                                : "Preferred Activities User " + user + ":", "  ",
20519                            packageName, true, false)) {
20520                        dumpState.setTitlePrinted(true);
20521                    }
20522                }
20523            }
20524
20525            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20526                pw.flush();
20527                FileOutputStream fout = new FileOutputStream(fd);
20528                BufferedOutputStream str = new BufferedOutputStream(fout);
20529                XmlSerializer serializer = new FastXmlSerializer();
20530                try {
20531                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20532                    serializer.startDocument(null, true);
20533                    serializer.setFeature(
20534                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20535                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20536                    serializer.endDocument();
20537                    serializer.flush();
20538                } catch (IllegalArgumentException e) {
20539                    pw.println("Failed writing: " + e);
20540                } catch (IllegalStateException e) {
20541                    pw.println("Failed writing: " + e);
20542                } catch (IOException e) {
20543                    pw.println("Failed writing: " + e);
20544                }
20545            }
20546
20547            if (!checkin
20548                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20549                    && packageName == null) {
20550                pw.println();
20551                int count = mSettings.mPackages.size();
20552                if (count == 0) {
20553                    pw.println("No applications!");
20554                    pw.println();
20555                } else {
20556                    final String prefix = "  ";
20557                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20558                    if (allPackageSettings.size() == 0) {
20559                        pw.println("No domain preferred apps!");
20560                        pw.println();
20561                    } else {
20562                        pw.println("App verification status:");
20563                        pw.println();
20564                        count = 0;
20565                        for (PackageSetting ps : allPackageSettings) {
20566                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20567                            if (ivi == null || ivi.getPackageName() == null) continue;
20568                            pw.println(prefix + "Package: " + ivi.getPackageName());
20569                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20570                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20571                            pw.println();
20572                            count++;
20573                        }
20574                        if (count == 0) {
20575                            pw.println(prefix + "No app verification established.");
20576                            pw.println();
20577                        }
20578                        for (int userId : sUserManager.getUserIds()) {
20579                            pw.println("App linkages for user " + userId + ":");
20580                            pw.println();
20581                            count = 0;
20582                            for (PackageSetting ps : allPackageSettings) {
20583                                final long status = ps.getDomainVerificationStatusForUser(userId);
20584                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20585                                        && !DEBUG_DOMAIN_VERIFICATION) {
20586                                    continue;
20587                                }
20588                                pw.println(prefix + "Package: " + ps.name);
20589                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20590                                String statusStr = IntentFilterVerificationInfo.
20591                                        getStatusStringFromValue(status);
20592                                pw.println(prefix + "Status:  " + statusStr);
20593                                pw.println();
20594                                count++;
20595                            }
20596                            if (count == 0) {
20597                                pw.println(prefix + "No configured app linkages.");
20598                                pw.println();
20599                            }
20600                        }
20601                    }
20602                }
20603            }
20604
20605            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20606                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20607            }
20608
20609            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20610                boolean printedSomething = false;
20611                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20612                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20613                        continue;
20614                    }
20615                    if (!printedSomething) {
20616                        if (dumpState.onTitlePrinted())
20617                            pw.println();
20618                        pw.println("Registered ContentProviders:");
20619                        printedSomething = true;
20620                    }
20621                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20622                    pw.print("    "); pw.println(p.toString());
20623                }
20624                printedSomething = false;
20625                for (Map.Entry<String, PackageParser.Provider> entry :
20626                        mProvidersByAuthority.entrySet()) {
20627                    PackageParser.Provider p = entry.getValue();
20628                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20629                        continue;
20630                    }
20631                    if (!printedSomething) {
20632                        if (dumpState.onTitlePrinted())
20633                            pw.println();
20634                        pw.println("ContentProvider Authorities:");
20635                        printedSomething = true;
20636                    }
20637                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20638                    pw.print("    "); pw.println(p.toString());
20639                    if (p.info != null && p.info.applicationInfo != null) {
20640                        final String appInfo = p.info.applicationInfo.toString();
20641                        pw.print("      applicationInfo="); pw.println(appInfo);
20642                    }
20643                }
20644            }
20645
20646            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20647                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20648            }
20649
20650            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20651                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20652            }
20653
20654            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20655                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20656            }
20657
20658            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
20659                if (dumpState.onTitlePrinted()) pw.println();
20660                pw.println("Package Changes:");
20661                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
20662                final int K = mChangedPackages.size();
20663                for (int i = 0; i < K; i++) {
20664                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
20665                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
20666                    final int N = changes.size();
20667                    if (N == 0) {
20668                        pw.print("    "); pw.println("No packages changed");
20669                    } else {
20670                        for (int j = 0; j < N; j++) {
20671                            final String pkgName = changes.valueAt(j);
20672                            final int sequenceNumber = changes.keyAt(j);
20673                            pw.print("    ");
20674                            pw.print("seq=");
20675                            pw.print(sequenceNumber);
20676                            pw.print(", package=");
20677                            pw.println(pkgName);
20678                        }
20679                    }
20680                }
20681            }
20682
20683            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20684                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20685            }
20686
20687            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20688                // XXX should handle packageName != null by dumping only install data that
20689                // the given package is involved with.
20690                if (dumpState.onTitlePrinted()) pw.println();
20691
20692                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20693                ipw.println();
20694                ipw.println("Frozen packages:");
20695                ipw.increaseIndent();
20696                if (mFrozenPackages.size() == 0) {
20697                    ipw.println("(none)");
20698                } else {
20699                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20700                        ipw.println(mFrozenPackages.valueAt(i));
20701                    }
20702                }
20703                ipw.decreaseIndent();
20704            }
20705
20706            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
20707                if (dumpState.onTitlePrinted()) pw.println();
20708
20709                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20710                ipw.println();
20711                ipw.println("Loaded volumes:");
20712                ipw.increaseIndent();
20713                if (mLoadedVolumes.size() == 0) {
20714                    ipw.println("(none)");
20715                } else {
20716                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
20717                        ipw.println(mLoadedVolumes.valueAt(i));
20718                    }
20719                }
20720                ipw.decreaseIndent();
20721            }
20722
20723            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20724                if (dumpState.onTitlePrinted()) pw.println();
20725                dumpDexoptStateLPr(pw, packageName);
20726            }
20727
20728            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20729                if (dumpState.onTitlePrinted()) pw.println();
20730                dumpCompilerStatsLPr(pw, packageName);
20731            }
20732
20733            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20734                if (dumpState.onTitlePrinted()) pw.println();
20735                mSettings.dumpReadMessagesLPr(pw, dumpState);
20736
20737                pw.println();
20738                pw.println("Package warning messages:");
20739                dumpCriticalInfo(pw, null);
20740            }
20741
20742            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20743                dumpCriticalInfo(pw, "msg,");
20744            }
20745        }
20746
20747        // PackageInstaller should be called outside of mPackages lock
20748        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20749            // XXX should handle packageName != null by dumping only install data that
20750            // the given package is involved with.
20751            if (dumpState.onTitlePrinted()) pw.println();
20752            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20753        }
20754    }
20755
20756    private void dumpProto(FileDescriptor fd) {
20757        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20758
20759        synchronized (mPackages) {
20760            final long requiredVerifierPackageToken =
20761                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20762            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20763            proto.write(
20764                    PackageServiceDumpProto.PackageShortProto.UID,
20765                    getPackageUid(
20766                            mRequiredVerifierPackage,
20767                            MATCH_DEBUG_TRIAGED_MISSING,
20768                            UserHandle.USER_SYSTEM));
20769            proto.end(requiredVerifierPackageToken);
20770
20771            if (mIntentFilterVerifierComponent != null) {
20772                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20773                final long verifierPackageToken =
20774                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20775                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20776                proto.write(
20777                        PackageServiceDumpProto.PackageShortProto.UID,
20778                        getPackageUid(
20779                                verifierPackageName,
20780                                MATCH_DEBUG_TRIAGED_MISSING,
20781                                UserHandle.USER_SYSTEM));
20782                proto.end(verifierPackageToken);
20783            }
20784
20785            dumpSharedLibrariesProto(proto);
20786            dumpFeaturesProto(proto);
20787            mSettings.dumpPackagesProto(proto);
20788            mSettings.dumpSharedUsersProto(proto);
20789            dumpCriticalInfo(proto);
20790        }
20791        proto.flush();
20792    }
20793
20794    private void dumpFeaturesProto(ProtoOutputStream proto) {
20795        synchronized (mAvailableFeatures) {
20796            final int count = mAvailableFeatures.size();
20797            for (int i = 0; i < count; i++) {
20798                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
20799            }
20800        }
20801    }
20802
20803    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20804        final int count = mSharedLibraries.size();
20805        for (int i = 0; i < count; i++) {
20806            final String libName = mSharedLibraries.keyAt(i);
20807            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20808            if (versionedLib == null) {
20809                continue;
20810            }
20811            final int versionCount = versionedLib.size();
20812            for (int j = 0; j < versionCount; j++) {
20813                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20814                final long sharedLibraryToken =
20815                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20816                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20817                final boolean isJar = (libEntry.path != null);
20818                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20819                if (isJar) {
20820                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20821                } else {
20822                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20823                }
20824                proto.end(sharedLibraryToken);
20825            }
20826        }
20827    }
20828
20829    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20830        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20831        ipw.println();
20832        ipw.println("Dexopt state:");
20833        ipw.increaseIndent();
20834        Collection<PackageParser.Package> packages = null;
20835        if (packageName != null) {
20836            PackageParser.Package targetPackage = mPackages.get(packageName);
20837            if (targetPackage != null) {
20838                packages = Collections.singletonList(targetPackage);
20839            } else {
20840                ipw.println("Unable to find package: " + packageName);
20841                return;
20842            }
20843        } else {
20844            packages = mPackages.values();
20845        }
20846
20847        for (PackageParser.Package pkg : packages) {
20848            ipw.println("[" + pkg.packageName + "]");
20849            ipw.increaseIndent();
20850            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
20851                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
20852            ipw.decreaseIndent();
20853        }
20854    }
20855
20856    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20857        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20858        ipw.println();
20859        ipw.println("Compiler stats:");
20860        ipw.increaseIndent();
20861        Collection<PackageParser.Package> packages = null;
20862        if (packageName != null) {
20863            PackageParser.Package targetPackage = mPackages.get(packageName);
20864            if (targetPackage != null) {
20865                packages = Collections.singletonList(targetPackage);
20866            } else {
20867                ipw.println("Unable to find package: " + packageName);
20868                return;
20869            }
20870        } else {
20871            packages = mPackages.values();
20872        }
20873
20874        for (PackageParser.Package pkg : packages) {
20875            ipw.println("[" + pkg.packageName + "]");
20876            ipw.increaseIndent();
20877
20878            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20879            if (stats == null) {
20880                ipw.println("(No recorded stats)");
20881            } else {
20882                stats.dump(ipw);
20883            }
20884            ipw.decreaseIndent();
20885        }
20886    }
20887
20888    private String dumpDomainString(String packageName) {
20889        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20890                .getList();
20891        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20892
20893        ArraySet<String> result = new ArraySet<>();
20894        if (iviList.size() > 0) {
20895            for (IntentFilterVerificationInfo ivi : iviList) {
20896                for (String host : ivi.getDomains()) {
20897                    result.add(host);
20898                }
20899            }
20900        }
20901        if (filters != null && filters.size() > 0) {
20902            for (IntentFilter filter : filters) {
20903                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20904                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20905                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20906                    result.addAll(filter.getHostsList());
20907                }
20908            }
20909        }
20910
20911        StringBuilder sb = new StringBuilder(result.size() * 16);
20912        for (String domain : result) {
20913            if (sb.length() > 0) sb.append(" ");
20914            sb.append(domain);
20915        }
20916        return sb.toString();
20917    }
20918
20919    // ------- apps on sdcard specific code -------
20920    static final boolean DEBUG_SD_INSTALL = false;
20921
20922    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20923
20924    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20925
20926    private boolean mMediaMounted = false;
20927
20928    static String getEncryptKey() {
20929        try {
20930            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20931                    SD_ENCRYPTION_KEYSTORE_NAME);
20932            if (sdEncKey == null) {
20933                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20934                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20935                if (sdEncKey == null) {
20936                    Slog.e(TAG, "Failed to create encryption keys");
20937                    return null;
20938                }
20939            }
20940            return sdEncKey;
20941        } catch (NoSuchAlgorithmException nsae) {
20942            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20943            return null;
20944        } catch (IOException ioe) {
20945            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20946            return null;
20947        }
20948    }
20949
20950    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20951            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20952        final int size = infos.size();
20953        final String[] packageNames = new String[size];
20954        final int[] packageUids = new int[size];
20955        for (int i = 0; i < size; i++) {
20956            final ApplicationInfo info = infos.get(i);
20957            packageNames[i] = info.packageName;
20958            packageUids[i] = info.uid;
20959        }
20960        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20961                finishedReceiver);
20962    }
20963
20964    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20965            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20966        sendResourcesChangedBroadcast(mediaStatus, replacing,
20967                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20968    }
20969
20970    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20971            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20972        int size = pkgList.length;
20973        if (size > 0) {
20974            // Send broadcasts here
20975            Bundle extras = new Bundle();
20976            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20977            if (uidArr != null) {
20978                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20979            }
20980            if (replacing) {
20981                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20982            }
20983            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20984                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20985            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20986        }
20987    }
20988
20989    private void loadPrivatePackages(final VolumeInfo vol) {
20990        mHandler.post(new Runnable() {
20991            @Override
20992            public void run() {
20993                loadPrivatePackagesInner(vol);
20994            }
20995        });
20996    }
20997
20998    private void loadPrivatePackagesInner(VolumeInfo vol) {
20999        final String volumeUuid = vol.fsUuid;
21000        if (TextUtils.isEmpty(volumeUuid)) {
21001            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21002            return;
21003        }
21004
21005        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21006        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21007        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21008
21009        final VersionInfo ver;
21010        final List<PackageSetting> packages;
21011        synchronized (mPackages) {
21012            ver = mSettings.findOrCreateVersion(volumeUuid);
21013            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21014        }
21015
21016        for (PackageSetting ps : packages) {
21017            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21018            synchronized (mInstallLock) {
21019                final PackageParser.Package pkg;
21020                try {
21021                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21022                    loaded.add(pkg.applicationInfo);
21023
21024                } catch (PackageManagerException e) {
21025                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21026                }
21027
21028                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21029                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21030                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21031                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21032                }
21033            }
21034        }
21035
21036        // Reconcile app data for all started/unlocked users
21037        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21038        final UserManager um = mContext.getSystemService(UserManager.class);
21039        UserManagerInternal umInternal = getUserManagerInternal();
21040        for (UserInfo user : um.getUsers()) {
21041            final int flags;
21042            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21043                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21044            } else if (umInternal.isUserRunning(user.id)) {
21045                flags = StorageManager.FLAG_STORAGE_DE;
21046            } else {
21047                continue;
21048            }
21049
21050            try {
21051                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21052                synchronized (mInstallLock) {
21053                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21054                }
21055            } catch (IllegalStateException e) {
21056                // Device was probably ejected, and we'll process that event momentarily
21057                Slog.w(TAG, "Failed to prepare storage: " + e);
21058            }
21059        }
21060
21061        synchronized (mPackages) {
21062            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21063            if (sdkUpdated) {
21064                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21065                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21066            }
21067            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21068                    mPermissionCallback);
21069
21070            // Yay, everything is now upgraded
21071            ver.forceCurrent();
21072
21073            mSettings.writeLPr();
21074        }
21075
21076        for (PackageFreezer freezer : freezers) {
21077            freezer.close();
21078        }
21079
21080        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21081        sendResourcesChangedBroadcast(true, false, loaded, null);
21082        mLoadedVolumes.add(vol.getId());
21083    }
21084
21085    private void unloadPrivatePackages(final VolumeInfo vol) {
21086        mHandler.post(new Runnable() {
21087            @Override
21088            public void run() {
21089                unloadPrivatePackagesInner(vol);
21090            }
21091        });
21092    }
21093
21094    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21095        final String volumeUuid = vol.fsUuid;
21096        if (TextUtils.isEmpty(volumeUuid)) {
21097            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21098            return;
21099        }
21100
21101        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21102        synchronized (mInstallLock) {
21103        synchronized (mPackages) {
21104            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21105            for (PackageSetting ps : packages) {
21106                if (ps.pkg == null) continue;
21107
21108                final ApplicationInfo info = ps.pkg.applicationInfo;
21109                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21110                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21111
21112                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21113                        "unloadPrivatePackagesInner")) {
21114                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21115                            false, null)) {
21116                        unloaded.add(info);
21117                    } else {
21118                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21119                    }
21120                }
21121
21122                // Try very hard to release any references to this package
21123                // so we don't risk the system server being killed due to
21124                // open FDs
21125                AttributeCache.instance().removePackage(ps.name);
21126            }
21127
21128            mSettings.writeLPr();
21129        }
21130        }
21131
21132        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21133        sendResourcesChangedBroadcast(false, false, unloaded, null);
21134        mLoadedVolumes.remove(vol.getId());
21135
21136        // Try very hard to release any references to this path so we don't risk
21137        // the system server being killed due to open FDs
21138        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21139
21140        for (int i = 0; i < 3; i++) {
21141            System.gc();
21142            System.runFinalization();
21143        }
21144    }
21145
21146    private void assertPackageKnown(String volumeUuid, String packageName)
21147            throws PackageManagerException {
21148        synchronized (mPackages) {
21149            // Normalize package name to handle renamed packages
21150            packageName = normalizePackageNameLPr(packageName);
21151
21152            final PackageSetting ps = mSettings.mPackages.get(packageName);
21153            if (ps == null) {
21154                throw new PackageManagerException("Package " + packageName + " is unknown");
21155            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21156                throw new PackageManagerException(
21157                        "Package " + packageName + " found on unknown volume " + volumeUuid
21158                                + "; expected volume " + ps.volumeUuid);
21159            }
21160        }
21161    }
21162
21163    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21164            throws PackageManagerException {
21165        synchronized (mPackages) {
21166            // Normalize package name to handle renamed packages
21167            packageName = normalizePackageNameLPr(packageName);
21168
21169            final PackageSetting ps = mSettings.mPackages.get(packageName);
21170            if (ps == null) {
21171                throw new PackageManagerException("Package " + packageName + " is unknown");
21172            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21173                throw new PackageManagerException(
21174                        "Package " + packageName + " found on unknown volume " + volumeUuid
21175                                + "; expected volume " + ps.volumeUuid);
21176            } else if (!ps.getInstalled(userId)) {
21177                throw new PackageManagerException(
21178                        "Package " + packageName + " not installed for user " + userId);
21179            }
21180        }
21181    }
21182
21183    private List<String> collectAbsoluteCodePaths() {
21184        synchronized (mPackages) {
21185            List<String> codePaths = new ArrayList<>();
21186            final int packageCount = mSettings.mPackages.size();
21187            for (int i = 0; i < packageCount; i++) {
21188                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21189                codePaths.add(ps.codePath.getAbsolutePath());
21190            }
21191            return codePaths;
21192        }
21193    }
21194
21195    /**
21196     * Examine all apps present on given mounted volume, and destroy apps that
21197     * aren't expected, either due to uninstallation or reinstallation on
21198     * another volume.
21199     */
21200    private void reconcileApps(String volumeUuid) {
21201        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21202        List<File> filesToDelete = null;
21203
21204        final File[] files = FileUtils.listFilesOrEmpty(
21205                Environment.getDataAppDirectory(volumeUuid));
21206        for (File file : files) {
21207            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21208                    && !PackageInstallerService.isStageName(file.getName());
21209            if (!isPackage) {
21210                // Ignore entries which are not packages
21211                continue;
21212            }
21213
21214            String absolutePath = file.getAbsolutePath();
21215
21216            boolean pathValid = false;
21217            final int absoluteCodePathCount = absoluteCodePaths.size();
21218            for (int i = 0; i < absoluteCodePathCount; i++) {
21219                String absoluteCodePath = absoluteCodePaths.get(i);
21220                if (absolutePath.startsWith(absoluteCodePath)) {
21221                    pathValid = true;
21222                    break;
21223                }
21224            }
21225
21226            if (!pathValid) {
21227                if (filesToDelete == null) {
21228                    filesToDelete = new ArrayList<>();
21229                }
21230                filesToDelete.add(file);
21231            }
21232        }
21233
21234        if (filesToDelete != null) {
21235            final int fileToDeleteCount = filesToDelete.size();
21236            for (int i = 0; i < fileToDeleteCount; i++) {
21237                File fileToDelete = filesToDelete.get(i);
21238                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21239                synchronized (mInstallLock) {
21240                    removeCodePathLI(fileToDelete);
21241                }
21242            }
21243        }
21244    }
21245
21246    /**
21247     * Reconcile all app data for the given user.
21248     * <p>
21249     * Verifies that directories exist and that ownership and labeling is
21250     * correct for all installed apps on all mounted volumes.
21251     */
21252    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21253        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21254        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21255            final String volumeUuid = vol.getFsUuid();
21256            synchronized (mInstallLock) {
21257                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21258            }
21259        }
21260    }
21261
21262    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21263            boolean migrateAppData) {
21264        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21265    }
21266
21267    /**
21268     * Reconcile all app data on given mounted volume.
21269     * <p>
21270     * Destroys app data that isn't expected, either due to uninstallation or
21271     * reinstallation on another volume.
21272     * <p>
21273     * Verifies that directories exist and that ownership and labeling is
21274     * correct for all installed apps.
21275     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21276     */
21277    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21278            boolean migrateAppData, boolean onlyCoreApps) {
21279        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21280                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21281        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21282
21283        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21284        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21285
21286        // First look for stale data that doesn't belong, and check if things
21287        // have changed since we did our last restorecon
21288        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21289            if (StorageManager.isFileEncryptedNativeOrEmulated()
21290                    && !StorageManager.isUserKeyUnlocked(userId)) {
21291                throw new RuntimeException(
21292                        "Yikes, someone asked us to reconcile CE storage while " + userId
21293                                + " was still locked; this would have caused massive data loss!");
21294            }
21295
21296            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21297            for (File file : files) {
21298                final String packageName = file.getName();
21299                try {
21300                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21301                } catch (PackageManagerException e) {
21302                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21303                    try {
21304                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21305                                StorageManager.FLAG_STORAGE_CE, 0);
21306                    } catch (InstallerException e2) {
21307                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21308                    }
21309                }
21310            }
21311        }
21312        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21313            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21314            for (File file : files) {
21315                final String packageName = file.getName();
21316                try {
21317                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21318                } catch (PackageManagerException e) {
21319                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21320                    try {
21321                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21322                                StorageManager.FLAG_STORAGE_DE, 0);
21323                    } catch (InstallerException e2) {
21324                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21325                    }
21326                }
21327            }
21328        }
21329
21330        // Ensure that data directories are ready to roll for all packages
21331        // installed for this volume and user
21332        final List<PackageSetting> packages;
21333        synchronized (mPackages) {
21334            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21335        }
21336        int preparedCount = 0;
21337        for (PackageSetting ps : packages) {
21338            final String packageName = ps.name;
21339            if (ps.pkg == null) {
21340                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21341                // TODO: might be due to legacy ASEC apps; we should circle back
21342                // and reconcile again once they're scanned
21343                continue;
21344            }
21345            // Skip non-core apps if requested
21346            if (onlyCoreApps && !ps.pkg.coreApp) {
21347                result.add(packageName);
21348                continue;
21349            }
21350
21351            if (ps.getInstalled(userId)) {
21352                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21353                preparedCount++;
21354            }
21355        }
21356
21357        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21358        return result;
21359    }
21360
21361    /**
21362     * Prepare app data for the given app just after it was installed or
21363     * upgraded. This method carefully only touches users that it's installed
21364     * for, and it forces a restorecon to handle any seinfo changes.
21365     * <p>
21366     * Verifies that directories exist and that ownership and labeling is
21367     * correct for all installed apps. If there is an ownership mismatch, it
21368     * will try recovering system apps by wiping data; third-party app data is
21369     * left intact.
21370     * <p>
21371     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21372     */
21373    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21374        final PackageSetting ps;
21375        synchronized (mPackages) {
21376            ps = mSettings.mPackages.get(pkg.packageName);
21377            mSettings.writeKernelMappingLPr(ps);
21378        }
21379
21380        final UserManager um = mContext.getSystemService(UserManager.class);
21381        UserManagerInternal umInternal = getUserManagerInternal();
21382        for (UserInfo user : um.getUsers()) {
21383            final int flags;
21384            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21385                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21386            } else if (umInternal.isUserRunning(user.id)) {
21387                flags = StorageManager.FLAG_STORAGE_DE;
21388            } else {
21389                continue;
21390            }
21391
21392            if (ps.getInstalled(user.id)) {
21393                // TODO: when user data is locked, mark that we're still dirty
21394                prepareAppDataLIF(pkg, user.id, flags);
21395            }
21396        }
21397    }
21398
21399    /**
21400     * Prepare app data for the given app.
21401     * <p>
21402     * Verifies that directories exist and that ownership and labeling is
21403     * correct for all installed apps. If there is an ownership mismatch, this
21404     * will try recovering system apps by wiping data; third-party app data is
21405     * left intact.
21406     */
21407    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21408        if (pkg == null) {
21409            Slog.wtf(TAG, "Package was null!", new Throwable());
21410            return;
21411        }
21412        prepareAppDataLeafLIF(pkg, userId, flags);
21413        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21414        for (int i = 0; i < childCount; i++) {
21415            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21416        }
21417    }
21418
21419    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21420            boolean maybeMigrateAppData) {
21421        prepareAppDataLIF(pkg, userId, flags);
21422
21423        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21424            // We may have just shuffled around app data directories, so
21425            // prepare them one more time
21426            prepareAppDataLIF(pkg, userId, flags);
21427        }
21428    }
21429
21430    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21431        if (DEBUG_APP_DATA) {
21432            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21433                    + Integer.toHexString(flags));
21434        }
21435
21436        final String volumeUuid = pkg.volumeUuid;
21437        final String packageName = pkg.packageName;
21438        final ApplicationInfo app = pkg.applicationInfo;
21439        final int appId = UserHandle.getAppId(app.uid);
21440
21441        Preconditions.checkNotNull(app.seInfo);
21442
21443        long ceDataInode = -1;
21444        try {
21445            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21446                    appId, app.seInfo, app.targetSdkVersion);
21447        } catch (InstallerException e) {
21448            if (app.isSystemApp()) {
21449                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21450                        + ", but trying to recover: " + e);
21451                destroyAppDataLeafLIF(pkg, userId, flags);
21452                try {
21453                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21454                            appId, app.seInfo, app.targetSdkVersion);
21455                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21456                } catch (InstallerException e2) {
21457                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21458                }
21459            } else {
21460                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21461            }
21462        }
21463
21464        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21465            // TODO: mark this structure as dirty so we persist it!
21466            synchronized (mPackages) {
21467                final PackageSetting ps = mSettings.mPackages.get(packageName);
21468                if (ps != null) {
21469                    ps.setCeDataInode(ceDataInode, userId);
21470                }
21471            }
21472        }
21473
21474        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21475    }
21476
21477    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21478        if (pkg == null) {
21479            Slog.wtf(TAG, "Package was null!", new Throwable());
21480            return;
21481        }
21482        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21483        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21484        for (int i = 0; i < childCount; i++) {
21485            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21486        }
21487    }
21488
21489    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21490        final String volumeUuid = pkg.volumeUuid;
21491        final String packageName = pkg.packageName;
21492        final ApplicationInfo app = pkg.applicationInfo;
21493
21494        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21495            // Create a native library symlink only if we have native libraries
21496            // and if the native libraries are 32 bit libraries. We do not provide
21497            // this symlink for 64 bit libraries.
21498            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21499                final String nativeLibPath = app.nativeLibraryDir;
21500                try {
21501                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21502                            nativeLibPath, userId);
21503                } catch (InstallerException e) {
21504                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21505                }
21506            }
21507        }
21508    }
21509
21510    /**
21511     * For system apps on non-FBE devices, this method migrates any existing
21512     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21513     * requested by the app.
21514     */
21515    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21516        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21517                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21518            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21519                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21520            try {
21521                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21522                        storageTarget);
21523            } catch (InstallerException e) {
21524                logCriticalInfo(Log.WARN,
21525                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21526            }
21527            return true;
21528        } else {
21529            return false;
21530        }
21531    }
21532
21533    public PackageFreezer freezePackage(String packageName, String killReason) {
21534        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21535    }
21536
21537    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21538        return new PackageFreezer(packageName, userId, killReason);
21539    }
21540
21541    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21542            String killReason) {
21543        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21544    }
21545
21546    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21547            String killReason) {
21548        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21549            return new PackageFreezer();
21550        } else {
21551            return freezePackage(packageName, userId, killReason);
21552        }
21553    }
21554
21555    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21556            String killReason) {
21557        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21558    }
21559
21560    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21561            String killReason) {
21562        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21563            return new PackageFreezer();
21564        } else {
21565            return freezePackage(packageName, userId, killReason);
21566        }
21567    }
21568
21569    /**
21570     * Class that freezes and kills the given package upon creation, and
21571     * unfreezes it upon closing. This is typically used when doing surgery on
21572     * app code/data to prevent the app from running while you're working.
21573     */
21574    private class PackageFreezer implements AutoCloseable {
21575        private final String mPackageName;
21576        private final PackageFreezer[] mChildren;
21577
21578        private final boolean mWeFroze;
21579
21580        private final AtomicBoolean mClosed = new AtomicBoolean();
21581        private final CloseGuard mCloseGuard = CloseGuard.get();
21582
21583        /**
21584         * Create and return a stub freezer that doesn't actually do anything,
21585         * typically used when someone requested
21586         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21587         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21588         */
21589        public PackageFreezer() {
21590            mPackageName = null;
21591            mChildren = null;
21592            mWeFroze = false;
21593            mCloseGuard.open("close");
21594        }
21595
21596        public PackageFreezer(String packageName, int userId, String killReason) {
21597            synchronized (mPackages) {
21598                mPackageName = packageName;
21599                mWeFroze = mFrozenPackages.add(mPackageName);
21600
21601                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21602                if (ps != null) {
21603                    killApplication(ps.name, ps.appId, userId, killReason);
21604                }
21605
21606                final PackageParser.Package p = mPackages.get(packageName);
21607                if (p != null && p.childPackages != null) {
21608                    final int N = p.childPackages.size();
21609                    mChildren = new PackageFreezer[N];
21610                    for (int i = 0; i < N; i++) {
21611                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21612                                userId, killReason);
21613                    }
21614                } else {
21615                    mChildren = null;
21616                }
21617            }
21618            mCloseGuard.open("close");
21619        }
21620
21621        @Override
21622        protected void finalize() throws Throwable {
21623            try {
21624                if (mCloseGuard != null) {
21625                    mCloseGuard.warnIfOpen();
21626                }
21627
21628                close();
21629            } finally {
21630                super.finalize();
21631            }
21632        }
21633
21634        @Override
21635        public void close() {
21636            mCloseGuard.close();
21637            if (mClosed.compareAndSet(false, true)) {
21638                synchronized (mPackages) {
21639                    if (mWeFroze) {
21640                        mFrozenPackages.remove(mPackageName);
21641                    }
21642
21643                    if (mChildren != null) {
21644                        for (PackageFreezer freezer : mChildren) {
21645                            freezer.close();
21646                        }
21647                    }
21648                }
21649            }
21650        }
21651    }
21652
21653    /**
21654     * Verify that given package is currently frozen.
21655     */
21656    private void checkPackageFrozen(String packageName) {
21657        synchronized (mPackages) {
21658            if (!mFrozenPackages.contains(packageName)) {
21659                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21660            }
21661        }
21662    }
21663
21664    @Override
21665    public int movePackage(final String packageName, final String volumeUuid) {
21666        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21667
21668        final int callingUid = Binder.getCallingUid();
21669        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
21670        final int moveId = mNextMoveId.getAndIncrement();
21671        mHandler.post(new Runnable() {
21672            @Override
21673            public void run() {
21674                try {
21675                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
21676                } catch (PackageManagerException e) {
21677                    Slog.w(TAG, "Failed to move " + packageName, e);
21678                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
21679                }
21680            }
21681        });
21682        return moveId;
21683    }
21684
21685    private void movePackageInternal(final String packageName, final String volumeUuid,
21686            final int moveId, final int callingUid, UserHandle user)
21687                    throws PackageManagerException {
21688        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21689        final PackageManager pm = mContext.getPackageManager();
21690
21691        final boolean currentAsec;
21692        final String currentVolumeUuid;
21693        final File codeFile;
21694        final String installerPackageName;
21695        final String packageAbiOverride;
21696        final int appId;
21697        final String seinfo;
21698        final String label;
21699        final int targetSdkVersion;
21700        final PackageFreezer freezer;
21701        final int[] installedUserIds;
21702
21703        // reader
21704        synchronized (mPackages) {
21705            final PackageParser.Package pkg = mPackages.get(packageName);
21706            final PackageSetting ps = mSettings.mPackages.get(packageName);
21707            if (pkg == null
21708                    || ps == null
21709                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
21710                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21711            }
21712            if (pkg.applicationInfo.isSystemApp()) {
21713                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21714                        "Cannot move system application");
21715            }
21716
21717            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21718            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21719                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21720            if (isInternalStorage && !allow3rdPartyOnInternal) {
21721                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21722                        "3rd party apps are not allowed on internal storage");
21723            }
21724
21725            if (pkg.applicationInfo.isExternalAsec()) {
21726                currentAsec = true;
21727                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21728            } else if (pkg.applicationInfo.isForwardLocked()) {
21729                currentAsec = true;
21730                currentVolumeUuid = "forward_locked";
21731            } else {
21732                currentAsec = false;
21733                currentVolumeUuid = ps.volumeUuid;
21734
21735                final File probe = new File(pkg.codePath);
21736                final File probeOat = new File(probe, "oat");
21737                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21738                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21739                            "Move only supported for modern cluster style installs");
21740                }
21741            }
21742
21743            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21744                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21745                        "Package already moved to " + volumeUuid);
21746            }
21747            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21748                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21749                        "Device admin cannot be moved");
21750            }
21751
21752            if (mFrozenPackages.contains(packageName)) {
21753                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21754                        "Failed to move already frozen package");
21755            }
21756
21757            codeFile = new File(pkg.codePath);
21758            installerPackageName = ps.installerPackageName;
21759            packageAbiOverride = ps.cpuAbiOverrideString;
21760            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21761            seinfo = pkg.applicationInfo.seInfo;
21762            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21763            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21764            freezer = freezePackage(packageName, "movePackageInternal");
21765            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21766        }
21767
21768        final Bundle extras = new Bundle();
21769        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21770        extras.putString(Intent.EXTRA_TITLE, label);
21771        mMoveCallbacks.notifyCreated(moveId, extras);
21772
21773        int installFlags;
21774        final boolean moveCompleteApp;
21775        final File measurePath;
21776
21777        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21778            installFlags = INSTALL_INTERNAL;
21779            moveCompleteApp = !currentAsec;
21780            measurePath = Environment.getDataAppDirectory(volumeUuid);
21781        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21782            installFlags = INSTALL_EXTERNAL;
21783            moveCompleteApp = false;
21784            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21785        } else {
21786            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21787            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21788                    || !volume.isMountedWritable()) {
21789                freezer.close();
21790                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21791                        "Move location not mounted private volume");
21792            }
21793
21794            Preconditions.checkState(!currentAsec);
21795
21796            installFlags = INSTALL_INTERNAL;
21797            moveCompleteApp = true;
21798            measurePath = Environment.getDataAppDirectory(volumeUuid);
21799        }
21800
21801        // If we're moving app data around, we need all the users unlocked
21802        if (moveCompleteApp) {
21803            for (int userId : installedUserIds) {
21804                if (StorageManager.isFileEncryptedNativeOrEmulated()
21805                        && !StorageManager.isUserKeyUnlocked(userId)) {
21806                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
21807                            "User " + userId + " must be unlocked");
21808                }
21809            }
21810        }
21811
21812        final PackageStats stats = new PackageStats(null, -1);
21813        synchronized (mInstaller) {
21814            for (int userId : installedUserIds) {
21815                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21816                    freezer.close();
21817                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21818                            "Failed to measure package size");
21819                }
21820            }
21821        }
21822
21823        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21824                + stats.dataSize);
21825
21826        final long startFreeBytes = measurePath.getUsableSpace();
21827        final long sizeBytes;
21828        if (moveCompleteApp) {
21829            sizeBytes = stats.codeSize + stats.dataSize;
21830        } else {
21831            sizeBytes = stats.codeSize;
21832        }
21833
21834        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21835            freezer.close();
21836            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21837                    "Not enough free space to move");
21838        }
21839
21840        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21841
21842        final CountDownLatch installedLatch = new CountDownLatch(1);
21843        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21844            @Override
21845            public void onUserActionRequired(Intent intent) throws RemoteException {
21846                throw new IllegalStateException();
21847            }
21848
21849            @Override
21850            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21851                    Bundle extras) throws RemoteException {
21852                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21853                        + PackageManager.installStatusToString(returnCode, msg));
21854
21855                installedLatch.countDown();
21856                freezer.close();
21857
21858                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21859                switch (status) {
21860                    case PackageInstaller.STATUS_SUCCESS:
21861                        mMoveCallbacks.notifyStatusChanged(moveId,
21862                                PackageManager.MOVE_SUCCEEDED);
21863                        break;
21864                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21865                        mMoveCallbacks.notifyStatusChanged(moveId,
21866                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21867                        break;
21868                    default:
21869                        mMoveCallbacks.notifyStatusChanged(moveId,
21870                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21871                        break;
21872                }
21873            }
21874        };
21875
21876        final MoveInfo move;
21877        if (moveCompleteApp) {
21878            // Kick off a thread to report progress estimates
21879            new Thread() {
21880                @Override
21881                public void run() {
21882                    while (true) {
21883                        try {
21884                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21885                                break;
21886                            }
21887                        } catch (InterruptedException ignored) {
21888                        }
21889
21890                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
21891                        final int progress = 10 + (int) MathUtils.constrain(
21892                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21893                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21894                    }
21895                }
21896            }.start();
21897
21898            final String dataAppName = codeFile.getName();
21899            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21900                    dataAppName, appId, seinfo, targetSdkVersion);
21901        } else {
21902            move = null;
21903        }
21904
21905        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21906
21907        final Message msg = mHandler.obtainMessage(INIT_COPY);
21908        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21909        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21910                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21911                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21912                PackageManager.INSTALL_REASON_UNKNOWN);
21913        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21914        msg.obj = params;
21915
21916        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21917                System.identityHashCode(msg.obj));
21918        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21919                System.identityHashCode(msg.obj));
21920
21921        mHandler.sendMessage(msg);
21922    }
21923
21924    @Override
21925    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21926        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21927
21928        final int realMoveId = mNextMoveId.getAndIncrement();
21929        final Bundle extras = new Bundle();
21930        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21931        mMoveCallbacks.notifyCreated(realMoveId, extras);
21932
21933        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21934            @Override
21935            public void onCreated(int moveId, Bundle extras) {
21936                // Ignored
21937            }
21938
21939            @Override
21940            public void onStatusChanged(int moveId, int status, long estMillis) {
21941                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21942            }
21943        };
21944
21945        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21946        storage.setPrimaryStorageUuid(volumeUuid, callback);
21947        return realMoveId;
21948    }
21949
21950    @Override
21951    public int getMoveStatus(int moveId) {
21952        mContext.enforceCallingOrSelfPermission(
21953                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21954        return mMoveCallbacks.mLastStatus.get(moveId);
21955    }
21956
21957    @Override
21958    public void registerMoveCallback(IPackageMoveObserver callback) {
21959        mContext.enforceCallingOrSelfPermission(
21960                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21961        mMoveCallbacks.register(callback);
21962    }
21963
21964    @Override
21965    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21966        mContext.enforceCallingOrSelfPermission(
21967                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21968        mMoveCallbacks.unregister(callback);
21969    }
21970
21971    @Override
21972    public boolean setInstallLocation(int loc) {
21973        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21974                null);
21975        if (getInstallLocation() == loc) {
21976            return true;
21977        }
21978        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21979                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21980            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21981                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21982            return true;
21983        }
21984        return false;
21985   }
21986
21987    @Override
21988    public int getInstallLocation() {
21989        // allow instant app access
21990        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21991                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21992                PackageHelper.APP_INSTALL_AUTO);
21993    }
21994
21995    /** Called by UserManagerService */
21996    void cleanUpUser(UserManagerService userManager, int userHandle) {
21997        synchronized (mPackages) {
21998            mDirtyUsers.remove(userHandle);
21999            mUserNeedsBadging.delete(userHandle);
22000            mSettings.removeUserLPw(userHandle);
22001            mPendingBroadcasts.remove(userHandle);
22002            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22003            removeUnusedPackagesLPw(userManager, userHandle);
22004        }
22005    }
22006
22007    /**
22008     * We're removing userHandle and would like to remove any downloaded packages
22009     * that are no longer in use by any other user.
22010     * @param userHandle the user being removed
22011     */
22012    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22013        final boolean DEBUG_CLEAN_APKS = false;
22014        int [] users = userManager.getUserIds();
22015        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22016        while (psit.hasNext()) {
22017            PackageSetting ps = psit.next();
22018            if (ps.pkg == null) {
22019                continue;
22020            }
22021            final String packageName = ps.pkg.packageName;
22022            // Skip over if system app
22023            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22024                continue;
22025            }
22026            if (DEBUG_CLEAN_APKS) {
22027                Slog.i(TAG, "Checking package " + packageName);
22028            }
22029            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22030            if (keep) {
22031                if (DEBUG_CLEAN_APKS) {
22032                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22033                }
22034            } else {
22035                for (int i = 0; i < users.length; i++) {
22036                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22037                        keep = true;
22038                        if (DEBUG_CLEAN_APKS) {
22039                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22040                                    + users[i]);
22041                        }
22042                        break;
22043                    }
22044                }
22045            }
22046            if (!keep) {
22047                if (DEBUG_CLEAN_APKS) {
22048                    Slog.i(TAG, "  Removing package " + packageName);
22049                }
22050                mHandler.post(new Runnable() {
22051                    public void run() {
22052                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22053                                userHandle, 0);
22054                    } //end run
22055                });
22056            }
22057        }
22058    }
22059
22060    /** Called by UserManagerService */
22061    void createNewUser(int userId, String[] disallowedPackages) {
22062        synchronized (mInstallLock) {
22063            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22064        }
22065        synchronized (mPackages) {
22066            scheduleWritePackageRestrictionsLocked(userId);
22067            scheduleWritePackageListLocked(userId);
22068            applyFactoryDefaultBrowserLPw(userId);
22069            primeDomainVerificationsLPw(userId);
22070        }
22071    }
22072
22073    void onNewUserCreated(final int userId) {
22074        synchronized(mPackages) {
22075            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
22076            // If permission review for legacy apps is required, we represent
22077            // dagerous permissions for such apps as always granted runtime
22078            // permissions to keep per user flag state whether review is needed.
22079            // Hence, if a new user is added we have to propagate dangerous
22080            // permission grants for these legacy apps.
22081            if (mSettings.mPermissions.mPermissionReviewRequired) {
22082// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22083                mPermissionManager.updateAllPermissions(
22084                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22085                        mPermissionCallback);
22086            }
22087        }
22088    }
22089
22090    @Override
22091    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22092        mContext.enforceCallingOrSelfPermission(
22093                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22094                "Only package verification agents can read the verifier device identity");
22095
22096        synchronized (mPackages) {
22097            return mSettings.getVerifierDeviceIdentityLPw();
22098        }
22099    }
22100
22101    @Override
22102    public void setPermissionEnforced(String permission, boolean enforced) {
22103        // TODO: Now that we no longer change GID for storage, this should to away.
22104        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22105                "setPermissionEnforced");
22106        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22107            synchronized (mPackages) {
22108                if (mSettings.mReadExternalStorageEnforced == null
22109                        || mSettings.mReadExternalStorageEnforced != enforced) {
22110                    mSettings.mReadExternalStorageEnforced =
22111                            enforced ? Boolean.TRUE : Boolean.FALSE;
22112                    mSettings.writeLPr();
22113                }
22114            }
22115            // kill any non-foreground processes so we restart them and
22116            // grant/revoke the GID.
22117            final IActivityManager am = ActivityManager.getService();
22118            if (am != null) {
22119                final long token = Binder.clearCallingIdentity();
22120                try {
22121                    am.killProcessesBelowForeground("setPermissionEnforcement");
22122                } catch (RemoteException e) {
22123                } finally {
22124                    Binder.restoreCallingIdentity(token);
22125                }
22126            }
22127        } else {
22128            throw new IllegalArgumentException("No selective enforcement for " + permission);
22129        }
22130    }
22131
22132    @Override
22133    @Deprecated
22134    public boolean isPermissionEnforced(String permission) {
22135        // allow instant applications
22136        return true;
22137    }
22138
22139    @Override
22140    public boolean isStorageLow() {
22141        // allow instant applications
22142        final long token = Binder.clearCallingIdentity();
22143        try {
22144            final DeviceStorageMonitorInternal
22145                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22146            if (dsm != null) {
22147                return dsm.isMemoryLow();
22148            } else {
22149                return false;
22150            }
22151        } finally {
22152            Binder.restoreCallingIdentity(token);
22153        }
22154    }
22155
22156    @Override
22157    public IPackageInstaller getPackageInstaller() {
22158        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22159            return null;
22160        }
22161        return mInstallerService;
22162    }
22163
22164    private boolean userNeedsBadging(int userId) {
22165        int index = mUserNeedsBadging.indexOfKey(userId);
22166        if (index < 0) {
22167            final UserInfo userInfo;
22168            final long token = Binder.clearCallingIdentity();
22169            try {
22170                userInfo = sUserManager.getUserInfo(userId);
22171            } finally {
22172                Binder.restoreCallingIdentity(token);
22173            }
22174            final boolean b;
22175            if (userInfo != null && userInfo.isManagedProfile()) {
22176                b = true;
22177            } else {
22178                b = false;
22179            }
22180            mUserNeedsBadging.put(userId, b);
22181            return b;
22182        }
22183        return mUserNeedsBadging.valueAt(index);
22184    }
22185
22186    @Override
22187    public KeySet getKeySetByAlias(String packageName, String alias) {
22188        if (packageName == null || alias == null) {
22189            return null;
22190        }
22191        synchronized(mPackages) {
22192            final PackageParser.Package pkg = mPackages.get(packageName);
22193            if (pkg == null) {
22194                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22195                throw new IllegalArgumentException("Unknown package: " + packageName);
22196            }
22197            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22198            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22199                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22200                throw new IllegalArgumentException("Unknown package: " + packageName);
22201            }
22202            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22203            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22204        }
22205    }
22206
22207    @Override
22208    public KeySet getSigningKeySet(String packageName) {
22209        if (packageName == null) {
22210            return null;
22211        }
22212        synchronized(mPackages) {
22213            final int callingUid = Binder.getCallingUid();
22214            final int callingUserId = UserHandle.getUserId(callingUid);
22215            final PackageParser.Package pkg = mPackages.get(packageName);
22216            if (pkg == null) {
22217                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22218                throw new IllegalArgumentException("Unknown package: " + packageName);
22219            }
22220            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22221            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22222                // filter and pretend the package doesn't exist
22223                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22224                        + ", uid:" + callingUid);
22225                throw new IllegalArgumentException("Unknown package: " + packageName);
22226            }
22227            if (pkg.applicationInfo.uid != callingUid
22228                    && Process.SYSTEM_UID != callingUid) {
22229                throw new SecurityException("May not access signing KeySet of other apps.");
22230            }
22231            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22232            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22233        }
22234    }
22235
22236    @Override
22237    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22238        final int callingUid = Binder.getCallingUid();
22239        if (getInstantAppPackageName(callingUid) != null) {
22240            return false;
22241        }
22242        if (packageName == null || ks == null) {
22243            return false;
22244        }
22245        synchronized(mPackages) {
22246            final PackageParser.Package pkg = mPackages.get(packageName);
22247            if (pkg == null
22248                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22249                            UserHandle.getUserId(callingUid))) {
22250                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22251                throw new IllegalArgumentException("Unknown package: " + packageName);
22252            }
22253            IBinder ksh = ks.getToken();
22254            if (ksh instanceof KeySetHandle) {
22255                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22256                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22257            }
22258            return false;
22259        }
22260    }
22261
22262    @Override
22263    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22264        final int callingUid = Binder.getCallingUid();
22265        if (getInstantAppPackageName(callingUid) != null) {
22266            return false;
22267        }
22268        if (packageName == null || ks == null) {
22269            return false;
22270        }
22271        synchronized(mPackages) {
22272            final PackageParser.Package pkg = mPackages.get(packageName);
22273            if (pkg == null
22274                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22275                            UserHandle.getUserId(callingUid))) {
22276                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22277                throw new IllegalArgumentException("Unknown package: " + packageName);
22278            }
22279            IBinder ksh = ks.getToken();
22280            if (ksh instanceof KeySetHandle) {
22281                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22282                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22283            }
22284            return false;
22285        }
22286    }
22287
22288    private void deletePackageIfUnusedLPr(final String packageName) {
22289        PackageSetting ps = mSettings.mPackages.get(packageName);
22290        if (ps == null) {
22291            return;
22292        }
22293        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22294            // TODO Implement atomic delete if package is unused
22295            // It is currently possible that the package will be deleted even if it is installed
22296            // after this method returns.
22297            mHandler.post(new Runnable() {
22298                public void run() {
22299                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22300                            0, PackageManager.DELETE_ALL_USERS);
22301                }
22302            });
22303        }
22304    }
22305
22306    /**
22307     * Check and throw if the given before/after packages would be considered a
22308     * downgrade.
22309     */
22310    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22311            throws PackageManagerException {
22312        if (after.versionCode < before.mVersionCode) {
22313            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22314                    "Update version code " + after.versionCode + " is older than current "
22315                    + before.mVersionCode);
22316        } else if (after.versionCode == before.mVersionCode) {
22317            if (after.baseRevisionCode < before.baseRevisionCode) {
22318                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22319                        "Update base revision code " + after.baseRevisionCode
22320                        + " is older than current " + before.baseRevisionCode);
22321            }
22322
22323            if (!ArrayUtils.isEmpty(after.splitNames)) {
22324                for (int i = 0; i < after.splitNames.length; i++) {
22325                    final String splitName = after.splitNames[i];
22326                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22327                    if (j != -1) {
22328                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22329                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22330                                    "Update split " + splitName + " revision code "
22331                                    + after.splitRevisionCodes[i] + " is older than current "
22332                                    + before.splitRevisionCodes[j]);
22333                        }
22334                    }
22335                }
22336            }
22337        }
22338    }
22339
22340    private static class MoveCallbacks extends Handler {
22341        private static final int MSG_CREATED = 1;
22342        private static final int MSG_STATUS_CHANGED = 2;
22343
22344        private final RemoteCallbackList<IPackageMoveObserver>
22345                mCallbacks = new RemoteCallbackList<>();
22346
22347        private final SparseIntArray mLastStatus = new SparseIntArray();
22348
22349        public MoveCallbacks(Looper looper) {
22350            super(looper);
22351        }
22352
22353        public void register(IPackageMoveObserver callback) {
22354            mCallbacks.register(callback);
22355        }
22356
22357        public void unregister(IPackageMoveObserver callback) {
22358            mCallbacks.unregister(callback);
22359        }
22360
22361        @Override
22362        public void handleMessage(Message msg) {
22363            final SomeArgs args = (SomeArgs) msg.obj;
22364            final int n = mCallbacks.beginBroadcast();
22365            for (int i = 0; i < n; i++) {
22366                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22367                try {
22368                    invokeCallback(callback, msg.what, args);
22369                } catch (RemoteException ignored) {
22370                }
22371            }
22372            mCallbacks.finishBroadcast();
22373            args.recycle();
22374        }
22375
22376        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22377                throws RemoteException {
22378            switch (what) {
22379                case MSG_CREATED: {
22380                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22381                    break;
22382                }
22383                case MSG_STATUS_CHANGED: {
22384                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22385                    break;
22386                }
22387            }
22388        }
22389
22390        private void notifyCreated(int moveId, Bundle extras) {
22391            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22392
22393            final SomeArgs args = SomeArgs.obtain();
22394            args.argi1 = moveId;
22395            args.arg2 = extras;
22396            obtainMessage(MSG_CREATED, args).sendToTarget();
22397        }
22398
22399        private void notifyStatusChanged(int moveId, int status) {
22400            notifyStatusChanged(moveId, status, -1);
22401        }
22402
22403        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22404            Slog.v(TAG, "Move " + moveId + " status " + status);
22405
22406            final SomeArgs args = SomeArgs.obtain();
22407            args.argi1 = moveId;
22408            args.argi2 = status;
22409            args.arg3 = estMillis;
22410            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22411
22412            synchronized (mLastStatus) {
22413                mLastStatus.put(moveId, status);
22414            }
22415        }
22416    }
22417
22418    private final static class OnPermissionChangeListeners extends Handler {
22419        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22420
22421        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22422                new RemoteCallbackList<>();
22423
22424        public OnPermissionChangeListeners(Looper looper) {
22425            super(looper);
22426        }
22427
22428        @Override
22429        public void handleMessage(Message msg) {
22430            switch (msg.what) {
22431                case MSG_ON_PERMISSIONS_CHANGED: {
22432                    final int uid = msg.arg1;
22433                    handleOnPermissionsChanged(uid);
22434                } break;
22435            }
22436        }
22437
22438        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22439            mPermissionListeners.register(listener);
22440
22441        }
22442
22443        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22444            mPermissionListeners.unregister(listener);
22445        }
22446
22447        public void onPermissionsChanged(int uid) {
22448            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22449                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22450            }
22451        }
22452
22453        private void handleOnPermissionsChanged(int uid) {
22454            final int count = mPermissionListeners.beginBroadcast();
22455            try {
22456                for (int i = 0; i < count; i++) {
22457                    IOnPermissionsChangeListener callback = mPermissionListeners
22458                            .getBroadcastItem(i);
22459                    try {
22460                        callback.onPermissionsChanged(uid);
22461                    } catch (RemoteException e) {
22462                        Log.e(TAG, "Permission listener is dead", e);
22463                    }
22464                }
22465            } finally {
22466                mPermissionListeners.finishBroadcast();
22467            }
22468        }
22469    }
22470
22471    private class PackageManagerNative extends IPackageManagerNative.Stub {
22472        @Override
22473        public String[] getNamesForUids(int[] uids) throws RemoteException {
22474            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22475            // massage results so they can be parsed by the native binder
22476            for (int i = results.length - 1; i >= 0; --i) {
22477                if (results[i] == null) {
22478                    results[i] = "";
22479                }
22480            }
22481            return results;
22482        }
22483
22484        // NB: this differentiates between preloads and sideloads
22485        @Override
22486        public String getInstallerForPackage(String packageName) throws RemoteException {
22487            final String installerName = getInstallerPackageName(packageName);
22488            if (!TextUtils.isEmpty(installerName)) {
22489                return installerName;
22490            }
22491            // differentiate between preload and sideload
22492            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22493            ApplicationInfo appInfo = getApplicationInfo(packageName,
22494                                    /*flags*/ 0,
22495                                    /*userId*/ callingUser);
22496            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22497                return "preload";
22498            }
22499            return "";
22500        }
22501
22502        @Override
22503        public int getVersionCodeForPackage(String packageName) throws RemoteException {
22504            try {
22505                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22506                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22507                if (pInfo != null) {
22508                    return pInfo.versionCode;
22509                }
22510            } catch (Exception e) {
22511            }
22512            return 0;
22513        }
22514    }
22515
22516    private class PackageManagerInternalImpl extends PackageManagerInternal {
22517        @Override
22518        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22519                int flagValues, int userId) {
22520            PackageManagerService.this.updatePermissionFlags(
22521                    permName, packageName, flagMask, flagValues, userId);
22522        }
22523
22524        @Override
22525        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22526            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22527        }
22528
22529        @Override
22530        public boolean isInstantApp(String packageName, int userId) {
22531            return PackageManagerService.this.isInstantApp(packageName, userId);
22532        }
22533
22534        @Override
22535        public String getInstantAppPackageName(int uid) {
22536            return PackageManagerService.this.getInstantAppPackageName(uid);
22537        }
22538
22539        @Override
22540        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
22541            synchronized (mPackages) {
22542                return PackageManagerService.this.filterAppAccessLPr(
22543                        (PackageSetting) pkg.mExtras, callingUid, userId);
22544            }
22545        }
22546
22547        @Override
22548        public PackageParser.Package getPackage(String packageName) {
22549            synchronized (mPackages) {
22550                packageName = resolveInternalPackageNameLPr(
22551                        packageName, PackageManager.VERSION_CODE_HIGHEST);
22552                return mPackages.get(packageName);
22553            }
22554        }
22555
22556        @Override
22557        public PackageParser.Package getDisabledPackage(String packageName) {
22558            synchronized (mPackages) {
22559                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
22560                return (ps != null) ? ps.pkg : null;
22561            }
22562        }
22563
22564        @Override
22565        public String getKnownPackageName(int knownPackage, int userId) {
22566            switch(knownPackage) {
22567                case PackageManagerInternal.PACKAGE_BROWSER:
22568                    return getDefaultBrowserPackageName(userId);
22569                case PackageManagerInternal.PACKAGE_INSTALLER:
22570                    return mRequiredInstallerPackage;
22571                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
22572                    return mSetupWizardPackage;
22573                case PackageManagerInternal.PACKAGE_SYSTEM:
22574                    return "android";
22575                case PackageManagerInternal.PACKAGE_VERIFIER:
22576                    return mRequiredVerifierPackage;
22577            }
22578            return null;
22579        }
22580
22581        @Override
22582        public boolean isResolveActivityComponent(ComponentInfo component) {
22583            return mResolveActivity.packageName.equals(component.packageName)
22584                    && mResolveActivity.name.equals(component.name);
22585        }
22586
22587        @Override
22588        public void setLocationPackagesProvider(PackagesProvider provider) {
22589            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
22590        }
22591
22592        @Override
22593        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22594            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
22595        }
22596
22597        @Override
22598        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22599            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
22600        }
22601
22602        @Override
22603        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22604            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
22605        }
22606
22607        @Override
22608        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22609            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
22610        }
22611
22612        @Override
22613        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22614            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
22615        }
22616
22617        @Override
22618        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22619            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
22620        }
22621
22622        @Override
22623        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22624            synchronized (mPackages) {
22625                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22626            }
22627            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
22628        }
22629
22630        @Override
22631        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22632            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
22633                    packageName, userId);
22634        }
22635
22636        @Override
22637        public void setKeepUninstalledPackages(final List<String> packageList) {
22638            Preconditions.checkNotNull(packageList);
22639            List<String> removedFromList = null;
22640            synchronized (mPackages) {
22641                if (mKeepUninstalledPackages != null) {
22642                    final int packagesCount = mKeepUninstalledPackages.size();
22643                    for (int i = 0; i < packagesCount; i++) {
22644                        String oldPackage = mKeepUninstalledPackages.get(i);
22645                        if (packageList != null && packageList.contains(oldPackage)) {
22646                            continue;
22647                        }
22648                        if (removedFromList == null) {
22649                            removedFromList = new ArrayList<>();
22650                        }
22651                        removedFromList.add(oldPackage);
22652                    }
22653                }
22654                mKeepUninstalledPackages = new ArrayList<>(packageList);
22655                if (removedFromList != null) {
22656                    final int removedCount = removedFromList.size();
22657                    for (int i = 0; i < removedCount; i++) {
22658                        deletePackageIfUnusedLPr(removedFromList.get(i));
22659                    }
22660                }
22661            }
22662        }
22663
22664        @Override
22665        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22666            synchronized (mPackages) {
22667                return mPermissionManager.isPermissionsReviewRequired(
22668                        mPackages.get(packageName), userId);
22669            }
22670        }
22671
22672        @Override
22673        public PackageInfo getPackageInfo(
22674                String packageName, int flags, int filterCallingUid, int userId) {
22675            return PackageManagerService.this
22676                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
22677                            flags, filterCallingUid, userId);
22678        }
22679
22680        @Override
22681        public ApplicationInfo getApplicationInfo(
22682                String packageName, int flags, int filterCallingUid, int userId) {
22683            return PackageManagerService.this
22684                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
22685        }
22686
22687        @Override
22688        public ActivityInfo getActivityInfo(
22689                ComponentName component, int flags, int filterCallingUid, int userId) {
22690            return PackageManagerService.this
22691                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
22692        }
22693
22694        @Override
22695        public List<ResolveInfo> queryIntentActivities(
22696                Intent intent, int flags, int filterCallingUid, int userId) {
22697            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22698            return PackageManagerService.this
22699                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
22700                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
22701        }
22702
22703        @Override
22704        public List<ResolveInfo> queryIntentServices(
22705                Intent intent, int flags, int callingUid, int userId) {
22706            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22707            return PackageManagerService.this
22708                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
22709                            false);
22710        }
22711
22712        @Override
22713        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22714                int userId) {
22715            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22716        }
22717
22718        @Override
22719        public void setDeviceAndProfileOwnerPackages(
22720                int deviceOwnerUserId, String deviceOwnerPackage,
22721                SparseArray<String> profileOwnerPackages) {
22722            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22723                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22724        }
22725
22726        @Override
22727        public boolean isPackageDataProtected(int userId, String packageName) {
22728            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22729        }
22730
22731        @Override
22732        public boolean isPackageEphemeral(int userId, String packageName) {
22733            synchronized (mPackages) {
22734                final PackageSetting ps = mSettings.mPackages.get(packageName);
22735                return ps != null ? ps.getInstantApp(userId) : false;
22736            }
22737        }
22738
22739        @Override
22740        public boolean wasPackageEverLaunched(String packageName, int userId) {
22741            synchronized (mPackages) {
22742                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22743            }
22744        }
22745
22746        @Override
22747        public void grantRuntimePermission(String packageName, String permName, int userId,
22748                boolean overridePolicy) {
22749            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
22750                    permName, packageName, overridePolicy, getCallingUid(), userId,
22751                    mPermissionCallback);
22752        }
22753
22754        @Override
22755        public void revokeRuntimePermission(String packageName, String permName, int userId,
22756                boolean overridePolicy) {
22757            mPermissionManager.revokeRuntimePermission(
22758                    permName, packageName, overridePolicy, getCallingUid(), userId,
22759                    mPermissionCallback);
22760        }
22761
22762        @Override
22763        public String getNameForUid(int uid) {
22764            return PackageManagerService.this.getNameForUid(uid);
22765        }
22766
22767        @Override
22768        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22769                Intent origIntent, String resolvedType, String callingPackage,
22770                Bundle verificationBundle, int userId) {
22771            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22772                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
22773                    userId);
22774        }
22775
22776        @Override
22777        public void grantEphemeralAccess(int userId, Intent intent,
22778                int targetAppId, int ephemeralAppId) {
22779            synchronized (mPackages) {
22780                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22781                        targetAppId, ephemeralAppId);
22782            }
22783        }
22784
22785        @Override
22786        public boolean isInstantAppInstallerComponent(ComponentName component) {
22787            synchronized (mPackages) {
22788                return mInstantAppInstallerActivity != null
22789                        && mInstantAppInstallerActivity.getComponentName().equals(component);
22790            }
22791        }
22792
22793        @Override
22794        public void pruneInstantApps() {
22795            mInstantAppRegistry.pruneInstantApps();
22796        }
22797
22798        @Override
22799        public String getSetupWizardPackageName() {
22800            return mSetupWizardPackage;
22801        }
22802
22803        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22804            if (policy != null) {
22805                mExternalSourcesPolicy = policy;
22806            }
22807        }
22808
22809        @Override
22810        public boolean isPackagePersistent(String packageName) {
22811            synchronized (mPackages) {
22812                PackageParser.Package pkg = mPackages.get(packageName);
22813                return pkg != null
22814                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22815                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22816                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22817                        : false;
22818            }
22819        }
22820
22821        @Override
22822        public boolean isLegacySystemApp(Package pkg) {
22823            synchronized (mPackages) {
22824                final PackageSetting ps = (PackageSetting) pkg.mExtras;
22825                return mPromoteSystemApps
22826                        && ps.isSystem()
22827                        && mExistingSystemPackages.contains(ps.name);
22828            }
22829        }
22830
22831        @Override
22832        public List<PackageInfo> getOverlayPackages(int userId) {
22833            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22834            synchronized (mPackages) {
22835                for (PackageParser.Package p : mPackages.values()) {
22836                    if (p.mOverlayTarget != null) {
22837                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22838                        if (pkg != null) {
22839                            overlayPackages.add(pkg);
22840                        }
22841                    }
22842                }
22843            }
22844            return overlayPackages;
22845        }
22846
22847        @Override
22848        public List<String> getTargetPackageNames(int userId) {
22849            List<String> targetPackages = new ArrayList<>();
22850            synchronized (mPackages) {
22851                for (PackageParser.Package p : mPackages.values()) {
22852                    if (p.mOverlayTarget == null) {
22853                        targetPackages.add(p.packageName);
22854                    }
22855                }
22856            }
22857            return targetPackages;
22858        }
22859
22860        @Override
22861        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
22862                @Nullable List<String> overlayPackageNames) {
22863            synchronized (mPackages) {
22864                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
22865                    Slog.e(TAG, "failed to find package " + targetPackageName);
22866                    return false;
22867                }
22868                ArrayList<String> overlayPaths = null;
22869                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
22870                    final int N = overlayPackageNames.size();
22871                    overlayPaths = new ArrayList<>(N);
22872                    for (int i = 0; i < N; i++) {
22873                        final String packageName = overlayPackageNames.get(i);
22874                        final PackageParser.Package pkg = mPackages.get(packageName);
22875                        if (pkg == null) {
22876                            Slog.e(TAG, "failed to find package " + packageName);
22877                            return false;
22878                        }
22879                        overlayPaths.add(pkg.baseCodePath);
22880                    }
22881                }
22882
22883                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
22884                ps.setOverlayPaths(overlayPaths, userId);
22885                return true;
22886            }
22887        }
22888
22889        @Override
22890        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
22891                int flags, int userId, boolean resolveForStart) {
22892            return resolveIntentInternal(
22893                    intent, resolvedType, flags, userId, resolveForStart);
22894        }
22895
22896        @Override
22897        public ResolveInfo resolveService(Intent intent, String resolvedType,
22898                int flags, int userId, int callingUid) {
22899            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
22900        }
22901
22902        @Override
22903        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
22904            return PackageManagerService.this.resolveContentProviderInternal(
22905                    name, flags, userId);
22906        }
22907
22908        @Override
22909        public void addIsolatedUid(int isolatedUid, int ownerUid) {
22910            synchronized (mPackages) {
22911                mIsolatedOwners.put(isolatedUid, ownerUid);
22912            }
22913        }
22914
22915        @Override
22916        public void removeIsolatedUid(int isolatedUid) {
22917            synchronized (mPackages) {
22918                mIsolatedOwners.delete(isolatedUid);
22919            }
22920        }
22921
22922        @Override
22923        public int getUidTargetSdkVersion(int uid) {
22924            synchronized (mPackages) {
22925                return getUidTargetSdkVersionLockedLPr(uid);
22926            }
22927        }
22928
22929        @Override
22930        public boolean canAccessInstantApps(int callingUid, int userId) {
22931            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
22932        }
22933
22934        @Override
22935        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
22936            synchronized (mPackages) {
22937                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
22938            }
22939        }
22940
22941        @Override
22942        public void notifyPackageUse(String packageName, int reason) {
22943            synchronized (mPackages) {
22944                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
22945            }
22946        }
22947    }
22948
22949    @Override
22950    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22951        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22952        synchronized (mPackages) {
22953            final long identity = Binder.clearCallingIdentity();
22954            try {
22955                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
22956                        packageNames, userId);
22957            } finally {
22958                Binder.restoreCallingIdentity(identity);
22959            }
22960        }
22961    }
22962
22963    @Override
22964    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22965        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
22966        synchronized (mPackages) {
22967            final long identity = Binder.clearCallingIdentity();
22968            try {
22969                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
22970                        packageNames, userId);
22971            } finally {
22972                Binder.restoreCallingIdentity(identity);
22973            }
22974        }
22975    }
22976
22977    private static void enforceSystemOrPhoneCaller(String tag) {
22978        int callingUid = Binder.getCallingUid();
22979        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22980            throw new SecurityException(
22981                    "Cannot call " + tag + " from UID " + callingUid);
22982        }
22983    }
22984
22985    boolean isHistoricalPackageUsageAvailable() {
22986        return mPackageUsage.isHistoricalPackageUsageAvailable();
22987    }
22988
22989    /**
22990     * Return a <b>copy</b> of the collection of packages known to the package manager.
22991     * @return A copy of the values of mPackages.
22992     */
22993    Collection<PackageParser.Package> getPackages() {
22994        synchronized (mPackages) {
22995            return new ArrayList<>(mPackages.values());
22996        }
22997    }
22998
22999    /**
23000     * Logs process start information (including base APK hash) to the security log.
23001     * @hide
23002     */
23003    @Override
23004    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23005            String apkFile, int pid) {
23006        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23007            return;
23008        }
23009        if (!SecurityLog.isLoggingEnabled()) {
23010            return;
23011        }
23012        Bundle data = new Bundle();
23013        data.putLong("startTimestamp", System.currentTimeMillis());
23014        data.putString("processName", processName);
23015        data.putInt("uid", uid);
23016        data.putString("seinfo", seinfo);
23017        data.putString("apkFile", apkFile);
23018        data.putInt("pid", pid);
23019        Message msg = mProcessLoggingHandler.obtainMessage(
23020                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23021        msg.setData(data);
23022        mProcessLoggingHandler.sendMessage(msg);
23023    }
23024
23025    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23026        return mCompilerStats.getPackageStats(pkgName);
23027    }
23028
23029    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23030        return getOrCreateCompilerPackageStats(pkg.packageName);
23031    }
23032
23033    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23034        return mCompilerStats.getOrCreatePackageStats(pkgName);
23035    }
23036
23037    public void deleteCompilerPackageStats(String pkgName) {
23038        mCompilerStats.deletePackageStats(pkgName);
23039    }
23040
23041    @Override
23042    public int getInstallReason(String packageName, int userId) {
23043        final int callingUid = Binder.getCallingUid();
23044        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23045                true /* requireFullPermission */, false /* checkShell */,
23046                "get install reason");
23047        synchronized (mPackages) {
23048            final PackageSetting ps = mSettings.mPackages.get(packageName);
23049            if (filterAppAccessLPr(ps, callingUid, userId)) {
23050                return PackageManager.INSTALL_REASON_UNKNOWN;
23051            }
23052            if (ps != null) {
23053                return ps.getInstallReason(userId);
23054            }
23055        }
23056        return PackageManager.INSTALL_REASON_UNKNOWN;
23057    }
23058
23059    @Override
23060    public boolean canRequestPackageInstalls(String packageName, int userId) {
23061        return canRequestPackageInstallsInternal(packageName, 0, userId,
23062                true /* throwIfPermNotDeclared*/);
23063    }
23064
23065    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23066            boolean throwIfPermNotDeclared) {
23067        int callingUid = Binder.getCallingUid();
23068        int uid = getPackageUid(packageName, 0, userId);
23069        if (callingUid != uid && callingUid != Process.ROOT_UID
23070                && callingUid != Process.SYSTEM_UID) {
23071            throw new SecurityException(
23072                    "Caller uid " + callingUid + " does not own package " + packageName);
23073        }
23074        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23075        if (info == null) {
23076            return false;
23077        }
23078        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23079            return false;
23080        }
23081        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23082        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23083        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23084            if (throwIfPermNotDeclared) {
23085                throw new SecurityException("Need to declare " + appOpPermission
23086                        + " to call this api");
23087            } else {
23088                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23089                return false;
23090            }
23091        }
23092        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23093            return false;
23094        }
23095        if (mExternalSourcesPolicy != null) {
23096            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23097            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23098                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23099            }
23100        }
23101        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23102    }
23103
23104    @Override
23105    public ComponentName getInstantAppResolverSettingsComponent() {
23106        return mInstantAppResolverSettingsComponent;
23107    }
23108
23109    @Override
23110    public ComponentName getInstantAppInstallerComponent() {
23111        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23112            return null;
23113        }
23114        return mInstantAppInstallerActivity == null
23115                ? null : mInstantAppInstallerActivity.getComponentName();
23116    }
23117
23118    @Override
23119    public String getInstantAppAndroidId(String packageName, int userId) {
23120        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23121                "getInstantAppAndroidId");
23122        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23123                true /* requireFullPermission */, false /* checkShell */,
23124                "getInstantAppAndroidId");
23125        // Make sure the target is an Instant App.
23126        if (!isInstantApp(packageName, userId)) {
23127            return null;
23128        }
23129        synchronized (mPackages) {
23130            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23131        }
23132    }
23133
23134    boolean canHaveOatDir(String packageName) {
23135        synchronized (mPackages) {
23136            PackageParser.Package p = mPackages.get(packageName);
23137            if (p == null) {
23138                return false;
23139            }
23140            return p.canHaveOatDir();
23141        }
23142    }
23143
23144    private String getOatDir(PackageParser.Package pkg) {
23145        if (!pkg.canHaveOatDir()) {
23146            return null;
23147        }
23148        File codePath = new File(pkg.codePath);
23149        if (codePath.isDirectory()) {
23150            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23151        }
23152        return null;
23153    }
23154
23155    void deleteOatArtifactsOfPackage(String packageName) {
23156        final String[] instructionSets;
23157        final List<String> codePaths;
23158        final String oatDir;
23159        final PackageParser.Package pkg;
23160        synchronized (mPackages) {
23161            pkg = mPackages.get(packageName);
23162        }
23163        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23164        codePaths = pkg.getAllCodePaths();
23165        oatDir = getOatDir(pkg);
23166
23167        for (String codePath : codePaths) {
23168            for (String isa : instructionSets) {
23169                try {
23170                    mInstaller.deleteOdex(codePath, isa, oatDir);
23171                } catch (InstallerException e) {
23172                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23173                }
23174            }
23175        }
23176    }
23177
23178    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23179        Set<String> unusedPackages = new HashSet<>();
23180        long currentTimeInMillis = System.currentTimeMillis();
23181        synchronized (mPackages) {
23182            for (PackageParser.Package pkg : mPackages.values()) {
23183                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23184                if (ps == null) {
23185                    continue;
23186                }
23187                PackageDexUsage.PackageUseInfo packageUseInfo =
23188                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23189                if (PackageManagerServiceUtils
23190                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23191                                downgradeTimeThresholdMillis, packageUseInfo,
23192                                pkg.getLatestPackageUseTimeInMills(),
23193                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23194                    unusedPackages.add(pkg.packageName);
23195                }
23196            }
23197        }
23198        return unusedPackages;
23199    }
23200}
23201
23202interface PackageSender {
23203    void sendPackageBroadcast(final String action, final String pkg,
23204        final Bundle extras, final int flags, final String targetPkg,
23205        final IIntentReceiver finishedReceiver, final int[] userIds);
23206    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23207        boolean includeStopped, int appId, int... userIds);
23208}
23209