PackageManagerService.java revision 45f8b29ce0ca9f80c586850c4be3a1e552bc6c2f
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.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
87import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
103import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
104import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
105import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
106import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
107import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
108import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
109import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
110import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
111import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
114
115import android.Manifest;
116import android.annotation.IntDef;
117import android.annotation.NonNull;
118import android.annotation.Nullable;
119import android.app.ActivityManager;
120import android.app.AppOpsManager;
121import android.app.IActivityManager;
122import android.app.ResourcesManager;
123import android.app.admin.IDevicePolicyManager;
124import android.app.admin.SecurityLog;
125import android.app.backup.IBackupManager;
126import android.content.BroadcastReceiver;
127import android.content.ComponentName;
128import android.content.ContentResolver;
129import android.content.Context;
130import android.content.IIntentReceiver;
131import android.content.Intent;
132import android.content.IntentFilter;
133import android.content.IntentSender;
134import android.content.IntentSender.SendIntentException;
135import android.content.ServiceConnection;
136import android.content.pm.ActivityInfo;
137import android.content.pm.ApplicationInfo;
138import android.content.pm.AppsQueryHelper;
139import android.content.pm.AuxiliaryResolveInfo;
140import android.content.pm.ChangedPackages;
141import android.content.pm.ComponentInfo;
142import android.content.pm.FallbackCategoryProvider;
143import android.content.pm.FeatureInfo;
144import android.content.pm.IDexModuleRegisterCallback;
145import android.content.pm.IOnPermissionsChangeListener;
146import android.content.pm.IPackageDataObserver;
147import android.content.pm.IPackageDeleteObserver;
148import android.content.pm.IPackageDeleteObserver2;
149import android.content.pm.IPackageInstallObserver2;
150import android.content.pm.IPackageInstaller;
151import android.content.pm.IPackageManager;
152import android.content.pm.IPackageManagerNative;
153import android.content.pm.IPackageMoveObserver;
154import android.content.pm.IPackageStatsObserver;
155import android.content.pm.InstantAppInfo;
156import android.content.pm.InstantAppRequest;
157import android.content.pm.InstantAppResolveInfo;
158import android.content.pm.InstrumentationInfo;
159import android.content.pm.IntentFilterVerificationInfo;
160import android.content.pm.KeySet;
161import android.content.pm.PackageCleanItem;
162import android.content.pm.PackageInfo;
163import android.content.pm.PackageInfoLite;
164import android.content.pm.PackageInstaller;
165import android.content.pm.PackageManager;
166import android.content.pm.PackageManagerInternal;
167import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
168import android.content.pm.PackageManager.PackageInfoFlags;
169import android.content.pm.PackageParser;
170import android.content.pm.PackageParser.ActivityIntentInfo;
171import android.content.pm.PackageParser.Package;
172import android.content.pm.PackageParser.PackageLite;
173import android.content.pm.PackageParser.PackageParserException;
174import android.content.pm.PackageParser.ParseFlags;
175import android.content.pm.PackageStats;
176import android.content.pm.PackageUserState;
177import android.content.pm.ParceledListSlice;
178import android.content.pm.PermissionGroupInfo;
179import android.content.pm.PermissionInfo;
180import android.content.pm.ProviderInfo;
181import android.content.pm.ResolveInfo;
182import android.content.pm.ServiceInfo;
183import android.content.pm.SharedLibraryInfo;
184import android.content.pm.Signature;
185import android.content.pm.UserInfo;
186import android.content.pm.VerifierDeviceIdentity;
187import android.content.pm.VerifierInfo;
188import android.content.pm.VersionedPackage;
189import android.content.pm.dex.IArtManager;
190import android.content.res.Resources;
191import android.database.ContentObserver;
192import android.graphics.Bitmap;
193import android.hardware.display.DisplayManager;
194import android.net.Uri;
195import android.os.Binder;
196import android.os.Build;
197import android.os.Bundle;
198import android.os.Debug;
199import android.os.Environment;
200import android.os.Environment.UserEnvironment;
201import android.os.FileUtils;
202import android.os.Handler;
203import android.os.IBinder;
204import android.os.Looper;
205import android.os.Message;
206import android.os.Parcel;
207import android.os.ParcelFileDescriptor;
208import android.os.PatternMatcher;
209import android.os.Process;
210import android.os.RemoteCallbackList;
211import android.os.RemoteException;
212import android.os.ResultReceiver;
213import android.os.SELinux;
214import android.os.ServiceManager;
215import android.os.ShellCallback;
216import android.os.SystemClock;
217import android.os.SystemProperties;
218import android.os.Trace;
219import android.os.UserHandle;
220import android.os.UserManager;
221import android.os.UserManagerInternal;
222import android.os.storage.IStorageManager;
223import android.os.storage.StorageEventListener;
224import android.os.storage.StorageManager;
225import android.os.storage.StorageManagerInternal;
226import android.os.storage.VolumeInfo;
227import android.os.storage.VolumeRecord;
228import android.provider.Settings.Global;
229import android.provider.Settings.Secure;
230import android.security.KeyStore;
231import android.security.SystemKeyStore;
232import android.service.pm.PackageServiceDumpProto;
233import android.system.ErrnoException;
234import android.system.Os;
235import android.text.TextUtils;
236import android.text.format.DateUtils;
237import android.util.ArrayMap;
238import android.util.ArraySet;
239import android.util.Base64;
240import android.util.DisplayMetrics;
241import android.util.EventLog;
242import android.util.ExceptionUtils;
243import android.util.Log;
244import android.util.LogPrinter;
245import android.util.MathUtils;
246import android.util.PackageUtils;
247import android.util.Pair;
248import android.util.PrintStreamPrinter;
249import android.util.Slog;
250import android.util.SparseArray;
251import android.util.SparseBooleanArray;
252import android.util.SparseIntArray;
253import android.util.TimingsTraceLog;
254import android.util.Xml;
255import android.util.jar.StrictJarFile;
256import android.util.proto.ProtoOutputStream;
257import android.view.Display;
258
259import com.android.internal.R;
260import com.android.internal.annotations.GuardedBy;
261import com.android.internal.app.IMediaContainerService;
262import com.android.internal.app.ResolverActivity;
263import com.android.internal.content.NativeLibraryHelper;
264import com.android.internal.content.PackageHelper;
265import com.android.internal.logging.MetricsLogger;
266import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
267import com.android.internal.os.IParcelFileDescriptorFactory;
268import com.android.internal.os.SomeArgs;
269import com.android.internal.os.Zygote;
270import com.android.internal.telephony.CarrierAppUtils;
271import com.android.internal.util.ArrayUtils;
272import com.android.internal.util.ConcurrentUtils;
273import com.android.internal.util.DumpUtils;
274import com.android.internal.util.FastXmlSerializer;
275import com.android.internal.util.IndentingPrintWriter;
276import com.android.internal.util.Preconditions;
277import com.android.internal.util.XmlUtils;
278import com.android.server.AttributeCache;
279import com.android.server.DeviceIdleController;
280import com.android.server.EventLogTags;
281import com.android.server.FgThread;
282import com.android.server.IntentResolver;
283import com.android.server.LocalServices;
284import com.android.server.LockGuard;
285import com.android.server.ServiceThread;
286import com.android.server.SystemConfig;
287import com.android.server.SystemServerInitThreadPool;
288import com.android.server.Watchdog;
289import com.android.server.net.NetworkPolicyManagerInternal;
290import com.android.server.pm.Installer.InstallerException;
291import com.android.server.pm.Settings.DatabaseVersion;
292import com.android.server.pm.Settings.VersionInfo;
293import com.android.server.pm.dex.ArtManagerService;
294import com.android.server.pm.dex.DexLogger;
295import com.android.server.pm.dex.DexManager;
296import com.android.server.pm.dex.DexoptOptions;
297import com.android.server.pm.dex.PackageDexUsage;
298import com.android.server.pm.permission.BasePermission;
299import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
300import com.android.server.pm.permission.PermissionManagerService;
301import com.android.server.pm.permission.PermissionManagerInternal;
302import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
303import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
304import com.android.server.pm.permission.PermissionsState;
305import com.android.server.pm.permission.PermissionsState.PermissionState;
306import com.android.server.storage.DeviceStorageMonitorInternal;
307
308import dalvik.system.CloseGuard;
309import dalvik.system.VMRuntime;
310
311import libcore.io.IoUtils;
312
313import org.xmlpull.v1.XmlPullParser;
314import org.xmlpull.v1.XmlPullParserException;
315import org.xmlpull.v1.XmlSerializer;
316
317import java.io.BufferedOutputStream;
318import java.io.ByteArrayInputStream;
319import java.io.ByteArrayOutputStream;
320import java.io.File;
321import java.io.FileDescriptor;
322import java.io.FileInputStream;
323import java.io.FileOutputStream;
324import java.io.FilenameFilter;
325import java.io.IOException;
326import java.io.PrintWriter;
327import java.lang.annotation.Retention;
328import java.lang.annotation.RetentionPolicy;
329import java.nio.charset.StandardCharsets;
330import java.security.DigestInputStream;
331import java.security.MessageDigest;
332import java.security.NoSuchAlgorithmException;
333import java.security.PublicKey;
334import java.security.SecureRandom;
335import java.security.cert.Certificate;
336import java.security.cert.CertificateException;
337import java.util.ArrayList;
338import java.util.Arrays;
339import java.util.Collection;
340import java.util.Collections;
341import java.util.Comparator;
342import java.util.HashMap;
343import java.util.HashSet;
344import java.util.Iterator;
345import java.util.LinkedHashSet;
346import java.util.List;
347import java.util.Map;
348import java.util.Objects;
349import java.util.Set;
350import java.util.concurrent.CountDownLatch;
351import java.util.concurrent.Future;
352import java.util.concurrent.TimeUnit;
353import java.util.concurrent.atomic.AtomicBoolean;
354import java.util.concurrent.atomic.AtomicInteger;
355
356/**
357 * Keep track of all those APKs everywhere.
358 * <p>
359 * Internally there are two important locks:
360 * <ul>
361 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
362 * and other related state. It is a fine-grained lock that should only be held
363 * momentarily, as it's one of the most contended locks in the system.
364 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
365 * operations typically involve heavy lifting of application data on disk. Since
366 * {@code installd} is single-threaded, and it's operations can often be slow,
367 * this lock should never be acquired while already holding {@link #mPackages}.
368 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
369 * holding {@link #mInstallLock}.
370 * </ul>
371 * Many internal methods rely on the caller to hold the appropriate locks, and
372 * this contract is expressed through method name suffixes:
373 * <ul>
374 * <li>fooLI(): the caller must hold {@link #mInstallLock}
375 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
376 * being modified must be frozen
377 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
378 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
379 * </ul>
380 * <p>
381 * Because this class is very central to the platform's security; please run all
382 * CTS and unit tests whenever making modifications:
383 *
384 * <pre>
385 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
386 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
387 * </pre>
388 */
389public class PackageManagerService extends IPackageManager.Stub
390        implements PackageSender {
391    static final String TAG = "PackageManager";
392    public static final boolean DEBUG_SETTINGS = false;
393    static final boolean DEBUG_PREFERRED = false;
394    static final boolean DEBUG_UPGRADE = false;
395    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
396    private static final boolean DEBUG_BACKUP = false;
397    public static final boolean DEBUG_INSTALL = false;
398    public static final boolean DEBUG_REMOVE = false;
399    private static final boolean DEBUG_BROADCASTS = false;
400    private static final boolean DEBUG_SHOW_INFO = false;
401    private static final boolean DEBUG_PACKAGE_INFO = false;
402    private static final boolean DEBUG_INTENT_MATCHING = false;
403    public static final boolean DEBUG_PACKAGE_SCANNING = false;
404    private static final boolean DEBUG_VERIFY = false;
405    private static final boolean DEBUG_FILTERS = false;
406    public static final boolean DEBUG_PERMISSIONS = false;
407    private static final boolean DEBUG_SHARED_LIBRARIES = false;
408    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
409
410    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
411    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
412    // user, but by default initialize to this.
413    public static final boolean DEBUG_DEXOPT = false;
414
415    private static final boolean DEBUG_ABI_SELECTION = false;
416    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
417    private static final boolean DEBUG_TRIAGED_MISSING = false;
418    private static final boolean DEBUG_APP_DATA = false;
419
420    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
421    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
422
423    private static final boolean HIDE_EPHEMERAL_APIS = false;
424
425    private static final boolean ENABLE_FREE_CACHE_V2 =
426            SystemProperties.getBoolean("fw.free_cache_v2", true);
427
428    private static final int RADIO_UID = Process.PHONE_UID;
429    private static final int LOG_UID = Process.LOG_UID;
430    private static final int NFC_UID = Process.NFC_UID;
431    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
432    private static final int SHELL_UID = Process.SHELL_UID;
433
434    // Suffix used during package installation when copying/moving
435    // package apks to install directory.
436    private static final String INSTALL_PACKAGE_SUFFIX = "-";
437
438    static final int SCAN_NO_DEX = 1<<0;
439    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
440    static final int SCAN_NEW_INSTALL = 1<<2;
441    static final int SCAN_UPDATE_TIME = 1<<3;
442    static final int SCAN_BOOTING = 1<<4;
443    static final int SCAN_TRUSTED_OVERLAY = 1<<5;
444    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
445    static final int SCAN_REQUIRE_KNOWN = 1<<7;
446    static final int SCAN_MOVE = 1<<8;
447    static final int SCAN_INITIAL = 1<<9;
448    static final int SCAN_CHECK_ONLY = 1<<10;
449    static final int SCAN_DONT_KILL_APP = 1<<11;
450    static final int SCAN_IGNORE_FROZEN = 1<<12;
451    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
452    static final int SCAN_AS_INSTANT_APP = 1<<14;
453    static final int SCAN_AS_FULL_APP = 1<<15;
454    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
455    static final int SCAN_AS_SYSTEM = 1<<17;
456    static final int SCAN_AS_PRIVILEGED = 1<<18;
457    static final int SCAN_AS_OEM = 1<<19;
458    static final int SCAN_AS_VENDOR = 1<<20;
459
460    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
461            SCAN_NO_DEX,
462            SCAN_UPDATE_SIGNATURE,
463            SCAN_NEW_INSTALL,
464            SCAN_UPDATE_TIME,
465            SCAN_BOOTING,
466            SCAN_TRUSTED_OVERLAY,
467            SCAN_DELETE_DATA_ON_FAILURES,
468            SCAN_REQUIRE_KNOWN,
469            SCAN_MOVE,
470            SCAN_INITIAL,
471            SCAN_CHECK_ONLY,
472            SCAN_DONT_KILL_APP,
473            SCAN_IGNORE_FROZEN,
474            SCAN_FIRST_BOOT_OR_UPGRADE,
475            SCAN_AS_INSTANT_APP,
476            SCAN_AS_FULL_APP,
477            SCAN_AS_VIRTUAL_PRELOAD,
478    })
479    @Retention(RetentionPolicy.SOURCE)
480    public @interface ScanFlags {}
481
482    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
483    /** Extension of the compressed packages */
484    public final static String COMPRESSED_EXTENSION = ".gz";
485    /** Suffix of stub packages on the system partition */
486    public final static String STUB_SUFFIX = "-Stub";
487
488    private static final int[] EMPTY_INT_ARRAY = new int[0];
489
490    private static final int TYPE_UNKNOWN = 0;
491    private static final int TYPE_ACTIVITY = 1;
492    private static final int TYPE_RECEIVER = 2;
493    private static final int TYPE_SERVICE = 3;
494    private static final int TYPE_PROVIDER = 4;
495    @IntDef(prefix = { "TYPE_" }, value = {
496            TYPE_UNKNOWN,
497            TYPE_ACTIVITY,
498            TYPE_RECEIVER,
499            TYPE_SERVICE,
500            TYPE_PROVIDER,
501    })
502    @Retention(RetentionPolicy.SOURCE)
503    public @interface ComponentType {}
504
505    /**
506     * Timeout (in milliseconds) after which the watchdog should declare that
507     * our handler thread is wedged.  The usual default for such things is one
508     * minute but we sometimes do very lengthy I/O operations on this thread,
509     * such as installing multi-gigabyte applications, so ours needs to be longer.
510     */
511    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
512
513    /**
514     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
515     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
516     * settings entry if available, otherwise we use the hardcoded default.  If it's been
517     * more than this long since the last fstrim, we force one during the boot sequence.
518     *
519     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
520     * one gets run at the next available charging+idle time.  This final mandatory
521     * no-fstrim check kicks in only of the other scheduling criteria is never met.
522     */
523    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
524
525    /**
526     * Whether verification is enabled by default.
527     */
528    private static final boolean DEFAULT_VERIFY_ENABLE = true;
529
530    /**
531     * The default maximum time to wait for the verification agent to return in
532     * milliseconds.
533     */
534    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
535
536    /**
537     * The default response for package verification timeout.
538     *
539     * This can be either PackageManager.VERIFICATION_ALLOW or
540     * PackageManager.VERIFICATION_REJECT.
541     */
542    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
543
544    public static final String PLATFORM_PACKAGE_NAME = "android";
545
546    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
547
548    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
549            DEFAULT_CONTAINER_PACKAGE,
550            "com.android.defcontainer.DefaultContainerService");
551
552    private static final String KILL_APP_REASON_GIDS_CHANGED =
553            "permission grant or revoke changed gids";
554
555    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
556            "permissions revoked";
557
558    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
559
560    private static final String PACKAGE_SCHEME = "package";
561
562    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
563
564    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
565
566    /** Canonical intent used to identify what counts as a "web browser" app */
567    private static final Intent sBrowserIntent;
568    static {
569        sBrowserIntent = new Intent();
570        sBrowserIntent.setAction(Intent.ACTION_VIEW);
571        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
572        sBrowserIntent.setData(Uri.parse("http:"));
573    }
574
575    /**
576     * The set of all protected actions [i.e. those actions for which a high priority
577     * intent filter is disallowed].
578     */
579    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
580    static {
581        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
582        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
583        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
584        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
585    }
586
587    // Compilation reasons.
588    public static final int REASON_FIRST_BOOT = 0;
589    public static final int REASON_BOOT = 1;
590    public static final int REASON_INSTALL = 2;
591    public static final int REASON_BACKGROUND_DEXOPT = 3;
592    public static final int REASON_AB_OTA = 4;
593    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
594    public static final int REASON_SHARED = 6;
595
596    public static final int REASON_LAST = REASON_SHARED;
597
598    /**
599     * Version number for the package parser cache. Increment this whenever the format or
600     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
601     */
602    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
603
604    /**
605     * Whether the package parser cache is enabled.
606     */
607    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
608
609    final ServiceThread mHandlerThread;
610
611    final PackageHandler mHandler;
612
613    private final ProcessLoggingHandler mProcessLoggingHandler;
614
615    /**
616     * Messages for {@link #mHandler} that need to wait for system ready before
617     * being dispatched.
618     */
619    private ArrayList<Message> mPostSystemReadyMessages;
620
621    final int mSdkVersion = Build.VERSION.SDK_INT;
622
623    final Context mContext;
624    final boolean mFactoryTest;
625    final boolean mOnlyCore;
626    final DisplayMetrics mMetrics;
627    final int mDefParseFlags;
628    final String[] mSeparateProcesses;
629    final boolean mIsUpgrade;
630    final boolean mIsPreNUpgrade;
631    final boolean mIsPreNMR1Upgrade;
632
633    // Have we told the Activity Manager to whitelist the default container service by uid yet?
634    @GuardedBy("mPackages")
635    boolean mDefaultContainerWhitelisted = false;
636
637    @GuardedBy("mPackages")
638    private boolean mDexOptDialogShown;
639
640    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
641    // LOCK HELD.  Can be called with mInstallLock held.
642    @GuardedBy("mInstallLock")
643    final Installer mInstaller;
644
645    /** Directory where installed third-party apps stored */
646    final File mAppInstallDir;
647
648    /**
649     * Directory to which applications installed internally have their
650     * 32 bit native libraries copied.
651     */
652    private File mAppLib32InstallDir;
653
654    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
655    // apps.
656    final File mDrmAppPrivateInstallDir;
657
658    // ----------------------------------------------------------------
659
660    // Lock for state used when installing and doing other long running
661    // operations.  Methods that must be called with this lock held have
662    // the suffix "LI".
663    final Object mInstallLock = new Object();
664
665    // ----------------------------------------------------------------
666
667    // Keys are String (package name), values are Package.  This also serves
668    // as the lock for the global state.  Methods that must be called with
669    // this lock held have the prefix "LP".
670    @GuardedBy("mPackages")
671    final ArrayMap<String, PackageParser.Package> mPackages =
672            new ArrayMap<String, PackageParser.Package>();
673
674    final ArrayMap<String, Set<String>> mKnownCodebase =
675            new ArrayMap<String, Set<String>>();
676
677    // Keys are isolated uids and values are the uid of the application
678    // that created the isolated proccess.
679    @GuardedBy("mPackages")
680    final SparseIntArray mIsolatedOwners = new SparseIntArray();
681
682    /**
683     * Tracks new system packages [received in an OTA] that we expect to
684     * find updated user-installed versions. Keys are package name, values
685     * are package location.
686     */
687    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
688    /**
689     * Tracks high priority intent filters for protected actions. During boot, certain
690     * filter actions are protected and should never be allowed to have a high priority
691     * intent filter for them. However, there is one, and only one exception -- the
692     * setup wizard. It must be able to define a high priority intent filter for these
693     * actions to ensure there are no escapes from the wizard. We need to delay processing
694     * of these during boot as we need to look at all of the system packages in order
695     * to know which component is the setup wizard.
696     */
697    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
698    /**
699     * Whether or not processing protected filters should be deferred.
700     */
701    private boolean mDeferProtectedFilters = true;
702
703    /**
704     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
705     */
706    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
707    /**
708     * Whether or not system app permissions should be promoted from install to runtime.
709     */
710    boolean mPromoteSystemApps;
711
712    @GuardedBy("mPackages")
713    final Settings mSettings;
714
715    /**
716     * Set of package names that are currently "frozen", which means active
717     * surgery is being done on the code/data for that package. The platform
718     * will refuse to launch frozen packages to avoid race conditions.
719     *
720     * @see PackageFreezer
721     */
722    @GuardedBy("mPackages")
723    final ArraySet<String> mFrozenPackages = new ArraySet<>();
724
725    final ProtectedPackages mProtectedPackages;
726
727    @GuardedBy("mLoadedVolumes")
728    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
729
730    boolean mFirstBoot;
731
732    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
733
734    @GuardedBy("mAvailableFeatures")
735    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
736
737    // If mac_permissions.xml was found for seinfo labeling.
738    boolean mFoundPolicyFile;
739
740    private final InstantAppRegistry mInstantAppRegistry;
741
742    @GuardedBy("mPackages")
743    int mChangedPackagesSequenceNumber;
744    /**
745     * List of changed [installed, removed or updated] packages.
746     * mapping from user id -> sequence number -> package name
747     */
748    @GuardedBy("mPackages")
749    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
750    /**
751     * The sequence number of the last change to a package.
752     * mapping from user id -> package name -> sequence number
753     */
754    @GuardedBy("mPackages")
755    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
756
757    class PackageParserCallback implements PackageParser.Callback {
758        @Override public final boolean hasFeature(String feature) {
759            return PackageManagerService.this.hasSystemFeature(feature, 0);
760        }
761
762        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
763                Collection<PackageParser.Package> allPackages, String targetPackageName) {
764            List<PackageParser.Package> overlayPackages = null;
765            for (PackageParser.Package p : allPackages) {
766                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
767                    if (overlayPackages == null) {
768                        overlayPackages = new ArrayList<PackageParser.Package>();
769                    }
770                    overlayPackages.add(p);
771                }
772            }
773            if (overlayPackages != null) {
774                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
775                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
776                        return p1.mOverlayPriority - p2.mOverlayPriority;
777                    }
778                };
779                Collections.sort(overlayPackages, cmp);
780            }
781            return overlayPackages;
782        }
783
784        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
785                String targetPackageName, String targetPath) {
786            if ("android".equals(targetPackageName)) {
787                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
788                // native AssetManager.
789                return null;
790            }
791            List<PackageParser.Package> overlayPackages =
792                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
793            if (overlayPackages == null || overlayPackages.isEmpty()) {
794                return null;
795            }
796            List<String> overlayPathList = null;
797            for (PackageParser.Package overlayPackage : overlayPackages) {
798                if (targetPath == null) {
799                    if (overlayPathList == null) {
800                        overlayPathList = new ArrayList<String>();
801                    }
802                    overlayPathList.add(overlayPackage.baseCodePath);
803                    continue;
804                }
805
806                try {
807                    // Creates idmaps for system to parse correctly the Android manifest of the
808                    // target package.
809                    //
810                    // OverlayManagerService will update each of them with a correct gid from its
811                    // target package app id.
812                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
813                            UserHandle.getSharedAppGid(
814                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
815                    if (overlayPathList == null) {
816                        overlayPathList = new ArrayList<String>();
817                    }
818                    overlayPathList.add(overlayPackage.baseCodePath);
819                } catch (InstallerException e) {
820                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
821                            overlayPackage.baseCodePath);
822                }
823            }
824            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
825        }
826
827        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
828            synchronized (mPackages) {
829                return getStaticOverlayPathsLocked(
830                        mPackages.values(), targetPackageName, targetPath);
831            }
832        }
833
834        @Override public final String[] getOverlayApks(String targetPackageName) {
835            return getStaticOverlayPaths(targetPackageName, null);
836        }
837
838        @Override public final String[] getOverlayPaths(String targetPackageName,
839                String targetPath) {
840            return getStaticOverlayPaths(targetPackageName, targetPath);
841        }
842    }
843
844    class ParallelPackageParserCallback extends PackageParserCallback {
845        List<PackageParser.Package> mOverlayPackages = null;
846
847        void findStaticOverlayPackages() {
848            synchronized (mPackages) {
849                for (PackageParser.Package p : mPackages.values()) {
850                    if (p.mIsStaticOverlay) {
851                        if (mOverlayPackages == null) {
852                            mOverlayPackages = new ArrayList<PackageParser.Package>();
853                        }
854                        mOverlayPackages.add(p);
855                    }
856                }
857            }
858        }
859
860        @Override
861        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
862            // We can trust mOverlayPackages without holding mPackages because package uninstall
863            // can't happen while running parallel parsing.
864            // Moreover holding mPackages on each parsing thread causes dead-lock.
865            return mOverlayPackages == null ? null :
866                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
867        }
868    }
869
870    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
871    final ParallelPackageParserCallback mParallelPackageParserCallback =
872            new ParallelPackageParserCallback();
873
874    public static final class SharedLibraryEntry {
875        public final @Nullable String path;
876        public final @Nullable String apk;
877        public final @NonNull SharedLibraryInfo info;
878
879        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
880                String declaringPackageName, int declaringPackageVersionCode) {
881            path = _path;
882            apk = _apk;
883            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
884                    declaringPackageName, declaringPackageVersionCode), null);
885        }
886    }
887
888    // Currently known shared libraries.
889    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
890    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
891            new ArrayMap<>();
892
893    // All available activities, for your resolving pleasure.
894    final ActivityIntentResolver mActivities =
895            new ActivityIntentResolver();
896
897    // All available receivers, for your resolving pleasure.
898    final ActivityIntentResolver mReceivers =
899            new ActivityIntentResolver();
900
901    // All available services, for your resolving pleasure.
902    final ServiceIntentResolver mServices = new ServiceIntentResolver();
903
904    // All available providers, for your resolving pleasure.
905    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
906
907    // Mapping from provider base names (first directory in content URI codePath)
908    // to the provider information.
909    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
910            new ArrayMap<String, PackageParser.Provider>();
911
912    // Mapping from instrumentation class names to info about them.
913    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
914            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
915
916    // Packages whose data we have transfered into another package, thus
917    // should no longer exist.
918    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
919
920    // Broadcast actions that are only available to the system.
921    @GuardedBy("mProtectedBroadcasts")
922    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
923
924    /** List of packages waiting for verification. */
925    final SparseArray<PackageVerificationState> mPendingVerification
926            = new SparseArray<PackageVerificationState>();
927
928    final PackageInstallerService mInstallerService;
929
930    final ArtManagerService mArtManagerService;
931
932    private final PackageDexOptimizer mPackageDexOptimizer;
933    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
934    // is used by other apps).
935    private final DexManager mDexManager;
936
937    private AtomicInteger mNextMoveId = new AtomicInteger();
938    private final MoveCallbacks mMoveCallbacks;
939
940    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
941
942    // Cache of users who need badging.
943    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
944
945    /** Token for keys in mPendingVerification. */
946    private int mPendingVerificationToken = 0;
947
948    volatile boolean mSystemReady;
949    volatile boolean mSafeMode;
950    volatile boolean mHasSystemUidErrors;
951    private volatile boolean mEphemeralAppsDisabled;
952
953    ApplicationInfo mAndroidApplication;
954    final ActivityInfo mResolveActivity = new ActivityInfo();
955    final ResolveInfo mResolveInfo = new ResolveInfo();
956    ComponentName mResolveComponentName;
957    PackageParser.Package mPlatformPackage;
958    ComponentName mCustomResolverComponentName;
959
960    boolean mResolverReplaced = false;
961
962    private final @Nullable ComponentName mIntentFilterVerifierComponent;
963    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
964
965    private int mIntentFilterVerificationToken = 0;
966
967    /** The service connection to the ephemeral resolver */
968    final EphemeralResolverConnection mInstantAppResolverConnection;
969    /** Component used to show resolver settings for Instant Apps */
970    final ComponentName mInstantAppResolverSettingsComponent;
971
972    /** Activity used to install instant applications */
973    ActivityInfo mInstantAppInstallerActivity;
974    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
975
976    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
977            = new SparseArray<IntentFilterVerificationState>();
978
979    // TODO remove this and go through mPermissonManager directly
980    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
981    private final PermissionManagerInternal mPermissionManager;
982
983    // List of packages names to keep cached, even if they are uninstalled for all users
984    private List<String> mKeepUninstalledPackages;
985
986    private UserManagerInternal mUserManagerInternal;
987
988    private DeviceIdleController.LocalService mDeviceIdleController;
989
990    private File mCacheDir;
991
992    private Future<?> mPrepareAppDataFuture;
993
994    private static class IFVerificationParams {
995        PackageParser.Package pkg;
996        boolean replacing;
997        int userId;
998        int verifierUid;
999
1000        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1001                int _userId, int _verifierUid) {
1002            pkg = _pkg;
1003            replacing = _replacing;
1004            userId = _userId;
1005            replacing = _replacing;
1006            verifierUid = _verifierUid;
1007        }
1008    }
1009
1010    private interface IntentFilterVerifier<T extends IntentFilter> {
1011        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1012                                               T filter, String packageName);
1013        void startVerifications(int userId);
1014        void receiveVerificationResponse(int verificationId);
1015    }
1016
1017    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1018        private Context mContext;
1019        private ComponentName mIntentFilterVerifierComponent;
1020        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1021
1022        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1023            mContext = context;
1024            mIntentFilterVerifierComponent = verifierComponent;
1025        }
1026
1027        private String getDefaultScheme() {
1028            return IntentFilter.SCHEME_HTTPS;
1029        }
1030
1031        @Override
1032        public void startVerifications(int userId) {
1033            // Launch verifications requests
1034            int count = mCurrentIntentFilterVerifications.size();
1035            for (int n=0; n<count; n++) {
1036                int verificationId = mCurrentIntentFilterVerifications.get(n);
1037                final IntentFilterVerificationState ivs =
1038                        mIntentFilterVerificationStates.get(verificationId);
1039
1040                String packageName = ivs.getPackageName();
1041
1042                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1043                final int filterCount = filters.size();
1044                ArraySet<String> domainsSet = new ArraySet<>();
1045                for (int m=0; m<filterCount; m++) {
1046                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1047                    domainsSet.addAll(filter.getHostsList());
1048                }
1049                synchronized (mPackages) {
1050                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1051                            packageName, domainsSet) != null) {
1052                        scheduleWriteSettingsLocked();
1053                    }
1054                }
1055                sendVerificationRequest(verificationId, ivs);
1056            }
1057            mCurrentIntentFilterVerifications.clear();
1058        }
1059
1060        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1061            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1062            verificationIntent.putExtra(
1063                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1064                    verificationId);
1065            verificationIntent.putExtra(
1066                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1067                    getDefaultScheme());
1068            verificationIntent.putExtra(
1069                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1070                    ivs.getHostsString());
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1073                    ivs.getPackageName());
1074            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1075            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1076
1077            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1078            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1079                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1080                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1081
1082            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1083            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1084                    "Sending IntentFilter verification broadcast");
1085        }
1086
1087        public void receiveVerificationResponse(int verificationId) {
1088            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1089
1090            final boolean verified = ivs.isVerified();
1091
1092            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1093            final int count = filters.size();
1094            if (DEBUG_DOMAIN_VERIFICATION) {
1095                Slog.i(TAG, "Received verification response " + verificationId
1096                        + " for " + count + " filters, verified=" + verified);
1097            }
1098            for (int n=0; n<count; n++) {
1099                PackageParser.ActivityIntentInfo filter = filters.get(n);
1100                filter.setVerified(verified);
1101
1102                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1103                        + " verified with result:" + verified + " and hosts:"
1104                        + ivs.getHostsString());
1105            }
1106
1107            mIntentFilterVerificationStates.remove(verificationId);
1108
1109            final String packageName = ivs.getPackageName();
1110            IntentFilterVerificationInfo ivi = null;
1111
1112            synchronized (mPackages) {
1113                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1114            }
1115            if (ivi == null) {
1116                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1117                        + verificationId + " packageName:" + packageName);
1118                return;
1119            }
1120            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1121                    "Updating IntentFilterVerificationInfo for package " + packageName
1122                            +" verificationId:" + verificationId);
1123
1124            synchronized (mPackages) {
1125                if (verified) {
1126                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1127                } else {
1128                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1129                }
1130                scheduleWriteSettingsLocked();
1131
1132                final int userId = ivs.getUserId();
1133                if (userId != UserHandle.USER_ALL) {
1134                    final int userStatus =
1135                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1136
1137                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1138                    boolean needUpdate = false;
1139
1140                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1141                    // already been set by the User thru the Disambiguation dialog
1142                    switch (userStatus) {
1143                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1144                            if (verified) {
1145                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1146                            } else {
1147                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1148                            }
1149                            needUpdate = true;
1150                            break;
1151
1152                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1153                            if (verified) {
1154                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1155                                needUpdate = true;
1156                            }
1157                            break;
1158
1159                        default:
1160                            // Nothing to do
1161                    }
1162
1163                    if (needUpdate) {
1164                        mSettings.updateIntentFilterVerificationStatusLPw(
1165                                packageName, updatedStatus, userId);
1166                        scheduleWritePackageRestrictionsLocked(userId);
1167                    }
1168                }
1169            }
1170        }
1171
1172        @Override
1173        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1174                    ActivityIntentInfo filter, String packageName) {
1175            if (!hasValidDomains(filter)) {
1176                return false;
1177            }
1178            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1179            if (ivs == null) {
1180                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1181                        packageName);
1182            }
1183            if (DEBUG_DOMAIN_VERIFICATION) {
1184                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1185            }
1186            ivs.addFilter(filter);
1187            return true;
1188        }
1189
1190        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1191                int userId, int verificationId, String packageName) {
1192            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1193                    verifierUid, userId, packageName);
1194            ivs.setPendingState();
1195            synchronized (mPackages) {
1196                mIntentFilterVerificationStates.append(verificationId, ivs);
1197                mCurrentIntentFilterVerifications.add(verificationId);
1198            }
1199            return ivs;
1200        }
1201    }
1202
1203    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1204        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1205                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1206                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1207    }
1208
1209    // Set of pending broadcasts for aggregating enable/disable of components.
1210    static class PendingPackageBroadcasts {
1211        // for each user id, a map of <package name -> components within that package>
1212        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1213
1214        public PendingPackageBroadcasts() {
1215            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1216        }
1217
1218        public ArrayList<String> get(int userId, String packageName) {
1219            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1220            return packages.get(packageName);
1221        }
1222
1223        public void put(int userId, String packageName, ArrayList<String> components) {
1224            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1225            packages.put(packageName, components);
1226        }
1227
1228        public void remove(int userId, String packageName) {
1229            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1230            if (packages != null) {
1231                packages.remove(packageName);
1232            }
1233        }
1234
1235        public void remove(int userId) {
1236            mUidMap.remove(userId);
1237        }
1238
1239        public int userIdCount() {
1240            return mUidMap.size();
1241        }
1242
1243        public int userIdAt(int n) {
1244            return mUidMap.keyAt(n);
1245        }
1246
1247        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1248            return mUidMap.get(userId);
1249        }
1250
1251        public int size() {
1252            // total number of pending broadcast entries across all userIds
1253            int num = 0;
1254            for (int i = 0; i< mUidMap.size(); i++) {
1255                num += mUidMap.valueAt(i).size();
1256            }
1257            return num;
1258        }
1259
1260        public void clear() {
1261            mUidMap.clear();
1262        }
1263
1264        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1265            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1266            if (map == null) {
1267                map = new ArrayMap<String, ArrayList<String>>();
1268                mUidMap.put(userId, map);
1269            }
1270            return map;
1271        }
1272    }
1273    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1274
1275    // Service Connection to remote media container service to copy
1276    // package uri's from external media onto secure containers
1277    // or internal storage.
1278    private IMediaContainerService mContainerService = null;
1279
1280    static final int SEND_PENDING_BROADCAST = 1;
1281    static final int MCS_BOUND = 3;
1282    static final int END_COPY = 4;
1283    static final int INIT_COPY = 5;
1284    static final int MCS_UNBIND = 6;
1285    static final int START_CLEANING_PACKAGE = 7;
1286    static final int FIND_INSTALL_LOC = 8;
1287    static final int POST_INSTALL = 9;
1288    static final int MCS_RECONNECT = 10;
1289    static final int MCS_GIVE_UP = 11;
1290    static final int WRITE_SETTINGS = 13;
1291    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1292    static final int PACKAGE_VERIFIED = 15;
1293    static final int CHECK_PENDING_VERIFICATION = 16;
1294    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1295    static final int INTENT_FILTER_VERIFIED = 18;
1296    static final int WRITE_PACKAGE_LIST = 19;
1297    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1298
1299    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1300
1301    // Delay time in millisecs
1302    static final int BROADCAST_DELAY = 10 * 1000;
1303
1304    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1305            2 * 60 * 60 * 1000L; /* two hours */
1306
1307    static UserManagerService sUserManager;
1308
1309    // Stores a list of users whose package restrictions file needs to be updated
1310    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1311
1312    final private DefaultContainerConnection mDefContainerConn =
1313            new DefaultContainerConnection();
1314    class DefaultContainerConnection implements ServiceConnection {
1315        public void onServiceConnected(ComponentName name, IBinder service) {
1316            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1317            final IMediaContainerService imcs = IMediaContainerService.Stub
1318                    .asInterface(Binder.allowBlocking(service));
1319            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1320        }
1321
1322        public void onServiceDisconnected(ComponentName name) {
1323            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1324        }
1325    }
1326
1327    // Recordkeeping of restore-after-install operations that are currently in flight
1328    // between the Package Manager and the Backup Manager
1329    static class PostInstallData {
1330        public InstallArgs args;
1331        public PackageInstalledInfo res;
1332
1333        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1334            args = _a;
1335            res = _r;
1336        }
1337    }
1338
1339    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1340    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1341
1342    // XML tags for backup/restore of various bits of state
1343    private static final String TAG_PREFERRED_BACKUP = "pa";
1344    private static final String TAG_DEFAULT_APPS = "da";
1345    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1346
1347    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1348    private static final String TAG_ALL_GRANTS = "rt-grants";
1349    private static final String TAG_GRANT = "grant";
1350    private static final String ATTR_PACKAGE_NAME = "pkg";
1351
1352    private static final String TAG_PERMISSION = "perm";
1353    private static final String ATTR_PERMISSION_NAME = "name";
1354    private static final String ATTR_IS_GRANTED = "g";
1355    private static final String ATTR_USER_SET = "set";
1356    private static final String ATTR_USER_FIXED = "fixed";
1357    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1358
1359    // System/policy permission grants are not backed up
1360    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1361            FLAG_PERMISSION_POLICY_FIXED
1362            | FLAG_PERMISSION_SYSTEM_FIXED
1363            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1364
1365    // And we back up these user-adjusted states
1366    private static final int USER_RUNTIME_GRANT_MASK =
1367            FLAG_PERMISSION_USER_SET
1368            | FLAG_PERMISSION_USER_FIXED
1369            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1370
1371    final @Nullable String mRequiredVerifierPackage;
1372    final @NonNull String mRequiredInstallerPackage;
1373    final @NonNull String mRequiredUninstallerPackage;
1374    final @Nullable String mSetupWizardPackage;
1375    final @Nullable String mStorageManagerPackage;
1376    final @NonNull String mServicesSystemSharedLibraryPackageName;
1377    final @NonNull String mSharedSystemSharedLibraryPackageName;
1378
1379    private final PackageUsage mPackageUsage = new PackageUsage();
1380    private final CompilerStats mCompilerStats = new CompilerStats();
1381
1382    class PackageHandler extends Handler {
1383        private boolean mBound = false;
1384        final ArrayList<HandlerParams> mPendingInstalls =
1385            new ArrayList<HandlerParams>();
1386
1387        private boolean connectToService() {
1388            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1389                    " DefaultContainerService");
1390            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1391            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1392            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1393                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1394                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1395                mBound = true;
1396                return true;
1397            }
1398            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1399            return false;
1400        }
1401
1402        private void disconnectService() {
1403            mContainerService = null;
1404            mBound = false;
1405            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406            mContext.unbindService(mDefContainerConn);
1407            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1408        }
1409
1410        PackageHandler(Looper looper) {
1411            super(looper);
1412        }
1413
1414        public void handleMessage(Message msg) {
1415            try {
1416                doHandleMessage(msg);
1417            } finally {
1418                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1419            }
1420        }
1421
1422        void doHandleMessage(Message msg) {
1423            switch (msg.what) {
1424                case INIT_COPY: {
1425                    HandlerParams params = (HandlerParams) msg.obj;
1426                    int idx = mPendingInstalls.size();
1427                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1428                    // If a bind was already initiated we dont really
1429                    // need to do anything. The pending install
1430                    // will be processed later on.
1431                    if (!mBound) {
1432                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1433                                System.identityHashCode(mHandler));
1434                        // If this is the only one pending we might
1435                        // have to bind to the service again.
1436                        if (!connectToService()) {
1437                            Slog.e(TAG, "Failed to bind to media container service");
1438                            params.serviceError();
1439                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1440                                    System.identityHashCode(mHandler));
1441                            if (params.traceMethod != null) {
1442                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1443                                        params.traceCookie);
1444                            }
1445                            return;
1446                        } else {
1447                            // Once we bind to the service, the first
1448                            // pending request will be processed.
1449                            mPendingInstalls.add(idx, params);
1450                        }
1451                    } else {
1452                        mPendingInstalls.add(idx, params);
1453                        // Already bound to the service. Just make
1454                        // sure we trigger off processing the first request.
1455                        if (idx == 0) {
1456                            mHandler.sendEmptyMessage(MCS_BOUND);
1457                        }
1458                    }
1459                    break;
1460                }
1461                case MCS_BOUND: {
1462                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1463                    if (msg.obj != null) {
1464                        mContainerService = (IMediaContainerService) msg.obj;
1465                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1466                                System.identityHashCode(mHandler));
1467                    }
1468                    if (mContainerService == null) {
1469                        if (!mBound) {
1470                            // Something seriously wrong since we are not bound and we are not
1471                            // waiting for connection. Bail out.
1472                            Slog.e(TAG, "Cannot bind to media container service");
1473                            for (HandlerParams params : mPendingInstalls) {
1474                                // Indicate service bind error
1475                                params.serviceError();
1476                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1477                                        System.identityHashCode(params));
1478                                if (params.traceMethod != null) {
1479                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1480                                            params.traceMethod, params.traceCookie);
1481                                }
1482                                return;
1483                            }
1484                            mPendingInstalls.clear();
1485                        } else {
1486                            Slog.w(TAG, "Waiting to connect to media container service");
1487                        }
1488                    } else if (mPendingInstalls.size() > 0) {
1489                        HandlerParams params = mPendingInstalls.get(0);
1490                        if (params != null) {
1491                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1492                                    System.identityHashCode(params));
1493                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1494                            if (params.startCopy()) {
1495                                // We are done...  look for more work or to
1496                                // go idle.
1497                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1498                                        "Checking for more work or unbind...");
1499                                // Delete pending install
1500                                if (mPendingInstalls.size() > 0) {
1501                                    mPendingInstalls.remove(0);
1502                                }
1503                                if (mPendingInstalls.size() == 0) {
1504                                    if (mBound) {
1505                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1506                                                "Posting delayed MCS_UNBIND");
1507                                        removeMessages(MCS_UNBIND);
1508                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1509                                        // Unbind after a little delay, to avoid
1510                                        // continual thrashing.
1511                                        sendMessageDelayed(ubmsg, 10000);
1512                                    }
1513                                } else {
1514                                    // There are more pending requests in queue.
1515                                    // Just post MCS_BOUND message to trigger processing
1516                                    // of next pending install.
1517                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1518                                            "Posting MCS_BOUND for next work");
1519                                    mHandler.sendEmptyMessage(MCS_BOUND);
1520                                }
1521                            }
1522                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1523                        }
1524                    } else {
1525                        // Should never happen ideally.
1526                        Slog.w(TAG, "Empty queue");
1527                    }
1528                    break;
1529                }
1530                case MCS_RECONNECT: {
1531                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1532                    if (mPendingInstalls.size() > 0) {
1533                        if (mBound) {
1534                            disconnectService();
1535                        }
1536                        if (!connectToService()) {
1537                            Slog.e(TAG, "Failed to bind to media container service");
1538                            for (HandlerParams params : mPendingInstalls) {
1539                                // Indicate service bind error
1540                                params.serviceError();
1541                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1542                                        System.identityHashCode(params));
1543                            }
1544                            mPendingInstalls.clear();
1545                        }
1546                    }
1547                    break;
1548                }
1549                case MCS_UNBIND: {
1550                    // If there is no actual work left, then time to unbind.
1551                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1552
1553                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1554                        if (mBound) {
1555                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1556
1557                            disconnectService();
1558                        }
1559                    } else if (mPendingInstalls.size() > 0) {
1560                        // There are more pending requests in queue.
1561                        // Just post MCS_BOUND message to trigger processing
1562                        // of next pending install.
1563                        mHandler.sendEmptyMessage(MCS_BOUND);
1564                    }
1565
1566                    break;
1567                }
1568                case MCS_GIVE_UP: {
1569                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1570                    HandlerParams params = mPendingInstalls.remove(0);
1571                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1572                            System.identityHashCode(params));
1573                    break;
1574                }
1575                case SEND_PENDING_BROADCAST: {
1576                    String packages[];
1577                    ArrayList<String> components[];
1578                    int size = 0;
1579                    int uids[];
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1581                    synchronized (mPackages) {
1582                        if (mPendingBroadcasts == null) {
1583                            return;
1584                        }
1585                        size = mPendingBroadcasts.size();
1586                        if (size <= 0) {
1587                            // Nothing to be done. Just return
1588                            return;
1589                        }
1590                        packages = new String[size];
1591                        components = new ArrayList[size];
1592                        uids = new int[size];
1593                        int i = 0;  // filling out the above arrays
1594
1595                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1596                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1597                            Iterator<Map.Entry<String, ArrayList<String>>> it
1598                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1599                                            .entrySet().iterator();
1600                            while (it.hasNext() && i < size) {
1601                                Map.Entry<String, ArrayList<String>> ent = it.next();
1602                                packages[i] = ent.getKey();
1603                                components[i] = ent.getValue();
1604                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1605                                uids[i] = (ps != null)
1606                                        ? UserHandle.getUid(packageUserId, ps.appId)
1607                                        : -1;
1608                                i++;
1609                            }
1610                        }
1611                        size = i;
1612                        mPendingBroadcasts.clear();
1613                    }
1614                    // Send broadcasts
1615                    for (int i = 0; i < size; i++) {
1616                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1617                    }
1618                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1619                    break;
1620                }
1621                case START_CLEANING_PACKAGE: {
1622                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1623                    final String packageName = (String)msg.obj;
1624                    final int userId = msg.arg1;
1625                    final boolean andCode = msg.arg2 != 0;
1626                    synchronized (mPackages) {
1627                        if (userId == UserHandle.USER_ALL) {
1628                            int[] users = sUserManager.getUserIds();
1629                            for (int user : users) {
1630                                mSettings.addPackageToCleanLPw(
1631                                        new PackageCleanItem(user, packageName, andCode));
1632                            }
1633                        } else {
1634                            mSettings.addPackageToCleanLPw(
1635                                    new PackageCleanItem(userId, packageName, andCode));
1636                        }
1637                    }
1638                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1639                    startCleaningPackages();
1640                } break;
1641                case POST_INSTALL: {
1642                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1643
1644                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1645                    final boolean didRestore = (msg.arg2 != 0);
1646                    mRunningInstalls.delete(msg.arg1);
1647
1648                    if (data != null) {
1649                        InstallArgs args = data.args;
1650                        PackageInstalledInfo parentRes = data.res;
1651
1652                        final boolean grantPermissions = (args.installFlags
1653                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1654                        final boolean killApp = (args.installFlags
1655                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1656                        final boolean virtualPreload = ((args.installFlags
1657                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1658                        final String[] grantedPermissions = args.installGrantPermissions;
1659
1660                        // Handle the parent package
1661                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1662                                virtualPreload, grantedPermissions, didRestore,
1663                                args.installerPackageName, args.observer);
1664
1665                        // Handle the child packages
1666                        final int childCount = (parentRes.addedChildPackages != null)
1667                                ? parentRes.addedChildPackages.size() : 0;
1668                        for (int i = 0; i < childCount; i++) {
1669                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1670                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1671                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1672                                    args.installerPackageName, args.observer);
1673                        }
1674
1675                        // Log tracing if needed
1676                        if (args.traceMethod != null) {
1677                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1678                                    args.traceCookie);
1679                        }
1680                    } else {
1681                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1682                    }
1683
1684                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1685                } break;
1686                case WRITE_SETTINGS: {
1687                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1688                    synchronized (mPackages) {
1689                        removeMessages(WRITE_SETTINGS);
1690                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1691                        mSettings.writeLPr();
1692                        mDirtyUsers.clear();
1693                    }
1694                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1695                } break;
1696                case WRITE_PACKAGE_RESTRICTIONS: {
1697                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1698                    synchronized (mPackages) {
1699                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1700                        for (int userId : mDirtyUsers) {
1701                            mSettings.writePackageRestrictionsLPr(userId);
1702                        }
1703                        mDirtyUsers.clear();
1704                    }
1705                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1706                } break;
1707                case WRITE_PACKAGE_LIST: {
1708                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1709                    synchronized (mPackages) {
1710                        removeMessages(WRITE_PACKAGE_LIST);
1711                        mSettings.writePackageListLPr(msg.arg1);
1712                    }
1713                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1714                } break;
1715                case CHECK_PENDING_VERIFICATION: {
1716                    final int verificationId = msg.arg1;
1717                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1718
1719                    if ((state != null) && !state.timeoutExtended()) {
1720                        final InstallArgs args = state.getInstallArgs();
1721                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1722
1723                        Slog.i(TAG, "Verification timed out for " + originUri);
1724                        mPendingVerification.remove(verificationId);
1725
1726                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1727
1728                        final UserHandle user = args.getUser();
1729                        if (getDefaultVerificationResponse(user)
1730                                == PackageManager.VERIFICATION_ALLOW) {
1731                            Slog.i(TAG, "Continuing with installation of " + originUri);
1732                            state.setVerifierResponse(Binder.getCallingUid(),
1733                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1734                            broadcastPackageVerified(verificationId, originUri,
1735                                    PackageManager.VERIFICATION_ALLOW, user);
1736                            try {
1737                                ret = args.copyApk(mContainerService, true);
1738                            } catch (RemoteException e) {
1739                                Slog.e(TAG, "Could not contact the ContainerService");
1740                            }
1741                        } else {
1742                            broadcastPackageVerified(verificationId, originUri,
1743                                    PackageManager.VERIFICATION_REJECT, user);
1744                        }
1745
1746                        Trace.asyncTraceEnd(
1747                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1748
1749                        processPendingInstall(args, ret);
1750                        mHandler.sendEmptyMessage(MCS_UNBIND);
1751                    }
1752                    break;
1753                }
1754                case PACKAGE_VERIFIED: {
1755                    final int verificationId = msg.arg1;
1756
1757                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1758                    if (state == null) {
1759                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1760                        break;
1761                    }
1762
1763                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1764
1765                    state.setVerifierResponse(response.callerUid, response.code);
1766
1767                    if (state.isVerificationComplete()) {
1768                        mPendingVerification.remove(verificationId);
1769
1770                        final InstallArgs args = state.getInstallArgs();
1771                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1772
1773                        int ret;
1774                        if (state.isInstallAllowed()) {
1775                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1776                            broadcastPackageVerified(verificationId, originUri,
1777                                    response.code, state.getInstallArgs().getUser());
1778                            try {
1779                                ret = args.copyApk(mContainerService, true);
1780                            } catch (RemoteException e) {
1781                                Slog.e(TAG, "Could not contact the ContainerService");
1782                            }
1783                        } else {
1784                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1785                        }
1786
1787                        Trace.asyncTraceEnd(
1788                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1789
1790                        processPendingInstall(args, ret);
1791                        mHandler.sendEmptyMessage(MCS_UNBIND);
1792                    }
1793
1794                    break;
1795                }
1796                case START_INTENT_FILTER_VERIFICATIONS: {
1797                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1798                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1799                            params.replacing, params.pkg);
1800                    break;
1801                }
1802                case INTENT_FILTER_VERIFIED: {
1803                    final int verificationId = msg.arg1;
1804
1805                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1806                            verificationId);
1807                    if (state == null) {
1808                        Slog.w(TAG, "Invalid IntentFilter verification token "
1809                                + verificationId + " received");
1810                        break;
1811                    }
1812
1813                    final int userId = state.getUserId();
1814
1815                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1816                            "Processing IntentFilter verification with token:"
1817                            + verificationId + " and userId:" + userId);
1818
1819                    final IntentFilterVerificationResponse response =
1820                            (IntentFilterVerificationResponse) msg.obj;
1821
1822                    state.setVerifierResponse(response.callerUid, response.code);
1823
1824                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1825                            "IntentFilter verification with token:" + verificationId
1826                            + " and userId:" + userId
1827                            + " is settings verifier response with response code:"
1828                            + response.code);
1829
1830                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1831                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1832                                + response.getFailedDomainsString());
1833                    }
1834
1835                    if (state.isVerificationComplete()) {
1836                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1837                    } else {
1838                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1839                                "IntentFilter verification with token:" + verificationId
1840                                + " was not said to be complete");
1841                    }
1842
1843                    break;
1844                }
1845                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1846                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1847                            mInstantAppResolverConnection,
1848                            (InstantAppRequest) msg.obj,
1849                            mInstantAppInstallerActivity,
1850                            mHandler);
1851                }
1852            }
1853        }
1854    }
1855
1856    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1857        @Override
1858        public void onGidsChanged(int appId, int userId) {
1859            mHandler.post(new Runnable() {
1860                @Override
1861                public void run() {
1862                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1863                }
1864            });
1865        }
1866        @Override
1867        public void onPermissionGranted(int uid, int userId) {
1868            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1869
1870            // Not critical; if this is lost, the application has to request again.
1871            synchronized (mPackages) {
1872                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1873            }
1874        }
1875        @Override
1876        public void onInstallPermissionGranted() {
1877            synchronized (mPackages) {
1878                scheduleWriteSettingsLocked();
1879            }
1880        }
1881        @Override
1882        public void onPermissionRevoked(int uid, int userId) {
1883            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1884
1885            synchronized (mPackages) {
1886                // Critical; after this call the application should never have the permission
1887                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1888            }
1889
1890            final int appId = UserHandle.getAppId(uid);
1891            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1892        }
1893        @Override
1894        public void onInstallPermissionRevoked() {
1895            synchronized (mPackages) {
1896                scheduleWriteSettingsLocked();
1897            }
1898        }
1899        @Override
1900        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1901            synchronized (mPackages) {
1902                for (int userId : updatedUserIds) {
1903                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1904                }
1905            }
1906        }
1907        @Override
1908        public void onInstallPermissionUpdated() {
1909            synchronized (mPackages) {
1910                scheduleWriteSettingsLocked();
1911            }
1912        }
1913        @Override
1914        public void onPermissionRemoved() {
1915            synchronized (mPackages) {
1916                mSettings.writeLPr();
1917            }
1918        }
1919    };
1920
1921    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1922            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1923            boolean launchedForRestore, String installerPackage,
1924            IPackageInstallObserver2 installObserver) {
1925        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1926            // Send the removed broadcasts
1927            if (res.removedInfo != null) {
1928                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1929            }
1930
1931            // Now that we successfully installed the package, grant runtime
1932            // permissions if requested before broadcasting the install. Also
1933            // for legacy apps in permission review mode we clear the permission
1934            // review flag which is used to emulate runtime permissions for
1935            // legacy apps.
1936            if (grantPermissions) {
1937                final int callingUid = Binder.getCallingUid();
1938                mPermissionManager.grantRequestedRuntimePermissions(
1939                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1940                        mPermissionCallback);
1941            }
1942
1943            final boolean update = res.removedInfo != null
1944                    && res.removedInfo.removedPackage != null;
1945            final String installerPackageName =
1946                    res.installerPackageName != null
1947                            ? res.installerPackageName
1948                            : res.removedInfo != null
1949                                    ? res.removedInfo.installerPackageName
1950                                    : null;
1951
1952            // If this is the first time we have child packages for a disabled privileged
1953            // app that had no children, we grant requested runtime permissions to the new
1954            // children if the parent on the system image had them already granted.
1955            if (res.pkg.parentPackage != null) {
1956                final int callingUid = Binder.getCallingUid();
1957                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1958                        res.pkg, callingUid, mPermissionCallback);
1959            }
1960
1961            synchronized (mPackages) {
1962                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1963            }
1964
1965            final String packageName = res.pkg.applicationInfo.packageName;
1966
1967            // Determine the set of users who are adding this package for
1968            // the first time vs. those who are seeing an update.
1969            int[] firstUsers = EMPTY_INT_ARRAY;
1970            int[] updateUsers = EMPTY_INT_ARRAY;
1971            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1972            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1973            for (int newUser : res.newUsers) {
1974                if (ps.getInstantApp(newUser)) {
1975                    continue;
1976                }
1977                if (allNewUsers) {
1978                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1979                    continue;
1980                }
1981                boolean isNew = true;
1982                for (int origUser : res.origUsers) {
1983                    if (origUser == newUser) {
1984                        isNew = false;
1985                        break;
1986                    }
1987                }
1988                if (isNew) {
1989                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1990                } else {
1991                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1992                }
1993            }
1994
1995            // Send installed broadcasts if the package is not a static shared lib.
1996            if (res.pkg.staticSharedLibName == null) {
1997                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1998
1999                // Send added for users that see the package for the first time
2000                // sendPackageAddedForNewUsers also deals with system apps
2001                int appId = UserHandle.getAppId(res.uid);
2002                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2003                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2004                        virtualPreload /*startReceiver*/, appId, firstUsers);
2005
2006                // Send added for users that don't see the package for the first time
2007                Bundle extras = new Bundle(1);
2008                extras.putInt(Intent.EXTRA_UID, res.uid);
2009                if (update) {
2010                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2011                }
2012                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2013                        extras, 0 /*flags*/,
2014                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2015                if (installerPackageName != null) {
2016                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2017                            extras, 0 /*flags*/,
2018                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2019                }
2020
2021                // Send replaced for users that don't see the package for the first time
2022                if (update) {
2023                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2024                            packageName, extras, 0 /*flags*/,
2025                            null /*targetPackage*/, null /*finishedReceiver*/,
2026                            updateUsers);
2027                    if (installerPackageName != null) {
2028                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2029                                extras, 0 /*flags*/,
2030                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2031                    }
2032                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2033                            null /*package*/, null /*extras*/, 0 /*flags*/,
2034                            packageName /*targetPackage*/,
2035                            null /*finishedReceiver*/, updateUsers);
2036                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2037                    // First-install and we did a restore, so we're responsible for the
2038                    // first-launch broadcast.
2039                    if (DEBUG_BACKUP) {
2040                        Slog.i(TAG, "Post-restore of " + packageName
2041                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2042                    }
2043                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2044                }
2045
2046                // Send broadcast package appeared if forward locked/external for all users
2047                // treat asec-hosted packages like removable media on upgrade
2048                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2049                    if (DEBUG_INSTALL) {
2050                        Slog.i(TAG, "upgrading pkg " + res.pkg
2051                                + " is ASEC-hosted -> AVAILABLE");
2052                    }
2053                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2054                    ArrayList<String> pkgList = new ArrayList<>(1);
2055                    pkgList.add(packageName);
2056                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2057                }
2058            }
2059
2060            // Work that needs to happen on first install within each user
2061            if (firstUsers != null && firstUsers.length > 0) {
2062                synchronized (mPackages) {
2063                    for (int userId : firstUsers) {
2064                        // If this app is a browser and it's newly-installed for some
2065                        // users, clear any default-browser state in those users. The
2066                        // app's nature doesn't depend on the user, so we can just check
2067                        // its browser nature in any user and generalize.
2068                        if (packageIsBrowser(packageName, userId)) {
2069                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2070                        }
2071
2072                        // We may also need to apply pending (restored) runtime
2073                        // permission grants within these users.
2074                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2075                    }
2076                }
2077            }
2078
2079            // Log current value of "unknown sources" setting
2080            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2081                    getUnknownSourcesSettings());
2082
2083            // Remove the replaced package's older resources safely now
2084            // We delete after a gc for applications  on sdcard.
2085            if (res.removedInfo != null && res.removedInfo.args != null) {
2086                Runtime.getRuntime().gc();
2087                synchronized (mInstallLock) {
2088                    res.removedInfo.args.doPostDeleteLI(true);
2089                }
2090            } else {
2091                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2092                // and not block here.
2093                VMRuntime.getRuntime().requestConcurrentGC();
2094            }
2095
2096            // Notify DexManager that the package was installed for new users.
2097            // The updated users should already be indexed and the package code paths
2098            // should not change.
2099            // Don't notify the manager for ephemeral apps as they are not expected to
2100            // survive long enough to benefit of background optimizations.
2101            for (int userId : firstUsers) {
2102                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2103                // There's a race currently where some install events may interleave with an uninstall.
2104                // This can lead to package info being null (b/36642664).
2105                if (info != null) {
2106                    mDexManager.notifyPackageInstalled(info, userId);
2107                }
2108            }
2109        }
2110
2111        // If someone is watching installs - notify them
2112        if (installObserver != null) {
2113            try {
2114                Bundle extras = extrasForInstallResult(res);
2115                installObserver.onPackageInstalled(res.name, res.returnCode,
2116                        res.returnMsg, extras);
2117            } catch (RemoteException e) {
2118                Slog.i(TAG, "Observer no longer exists.");
2119            }
2120        }
2121    }
2122
2123    private StorageEventListener mStorageListener = new StorageEventListener() {
2124        @Override
2125        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2126            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2127                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2128                    final String volumeUuid = vol.getFsUuid();
2129
2130                    // Clean up any users or apps that were removed or recreated
2131                    // while this volume was missing
2132                    sUserManager.reconcileUsers(volumeUuid);
2133                    reconcileApps(volumeUuid);
2134
2135                    // Clean up any install sessions that expired or were
2136                    // cancelled while this volume was missing
2137                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2138
2139                    loadPrivatePackages(vol);
2140
2141                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2142                    unloadPrivatePackages(vol);
2143                }
2144            }
2145        }
2146
2147        @Override
2148        public void onVolumeForgotten(String fsUuid) {
2149            if (TextUtils.isEmpty(fsUuid)) {
2150                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2151                return;
2152            }
2153
2154            // Remove any apps installed on the forgotten volume
2155            synchronized (mPackages) {
2156                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2157                for (PackageSetting ps : packages) {
2158                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2159                    deletePackageVersioned(new VersionedPackage(ps.name,
2160                            PackageManager.VERSION_CODE_HIGHEST),
2161                            new LegacyPackageDeleteObserver(null).getBinder(),
2162                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2163                    // Try very hard to release any references to this package
2164                    // so we don't risk the system server being killed due to
2165                    // open FDs
2166                    AttributeCache.instance().removePackage(ps.name);
2167                }
2168
2169                mSettings.onVolumeForgotten(fsUuid);
2170                mSettings.writeLPr();
2171            }
2172        }
2173    };
2174
2175    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2176        Bundle extras = null;
2177        switch (res.returnCode) {
2178            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2179                extras = new Bundle();
2180                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2181                        res.origPermission);
2182                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2183                        res.origPackage);
2184                break;
2185            }
2186            case PackageManager.INSTALL_SUCCEEDED: {
2187                extras = new Bundle();
2188                extras.putBoolean(Intent.EXTRA_REPLACING,
2189                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2190                break;
2191            }
2192        }
2193        return extras;
2194    }
2195
2196    void scheduleWriteSettingsLocked() {
2197        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2198            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2199        }
2200    }
2201
2202    void scheduleWritePackageListLocked(int userId) {
2203        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2204            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2205            msg.arg1 = userId;
2206            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2207        }
2208    }
2209
2210    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2211        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2212        scheduleWritePackageRestrictionsLocked(userId);
2213    }
2214
2215    void scheduleWritePackageRestrictionsLocked(int userId) {
2216        final int[] userIds = (userId == UserHandle.USER_ALL)
2217                ? sUserManager.getUserIds() : new int[]{userId};
2218        for (int nextUserId : userIds) {
2219            if (!sUserManager.exists(nextUserId)) return;
2220            mDirtyUsers.add(nextUserId);
2221            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2222                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2223            }
2224        }
2225    }
2226
2227    public static PackageManagerService main(Context context, Installer installer,
2228            boolean factoryTest, boolean onlyCore) {
2229        // Self-check for initial settings.
2230        PackageManagerServiceCompilerMapping.checkProperties();
2231
2232        PackageManagerService m = new PackageManagerService(context, installer,
2233                factoryTest, onlyCore);
2234        m.enableSystemUserPackages();
2235        ServiceManager.addService("package", m);
2236        final PackageManagerNative pmn = m.new PackageManagerNative();
2237        ServiceManager.addService("package_native", pmn);
2238        return m;
2239    }
2240
2241    private void enableSystemUserPackages() {
2242        if (!UserManager.isSplitSystemUser()) {
2243            return;
2244        }
2245        // For system user, enable apps based on the following conditions:
2246        // - app is whitelisted or belong to one of these groups:
2247        //   -- system app which has no launcher icons
2248        //   -- system app which has INTERACT_ACROSS_USERS permission
2249        //   -- system IME app
2250        // - app is not in the blacklist
2251        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2252        Set<String> enableApps = new ArraySet<>();
2253        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2254                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2255                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2256        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2257        enableApps.addAll(wlApps);
2258        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2259                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2260        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2261        enableApps.removeAll(blApps);
2262        Log.i(TAG, "Applications installed for system user: " + enableApps);
2263        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2264                UserHandle.SYSTEM);
2265        final int allAppsSize = allAps.size();
2266        synchronized (mPackages) {
2267            for (int i = 0; i < allAppsSize; i++) {
2268                String pName = allAps.get(i);
2269                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2270                // Should not happen, but we shouldn't be failing if it does
2271                if (pkgSetting == null) {
2272                    continue;
2273                }
2274                boolean install = enableApps.contains(pName);
2275                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2276                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2277                            + " for system user");
2278                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2279                }
2280            }
2281            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2282        }
2283    }
2284
2285    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2286        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2287                Context.DISPLAY_SERVICE);
2288        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2289    }
2290
2291    /**
2292     * Requests that files preopted on a secondary system partition be copied to the data partition
2293     * if possible.  Note that the actual copying of the files is accomplished by init for security
2294     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2295     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2296     */
2297    private static void requestCopyPreoptedFiles() {
2298        final int WAIT_TIME_MS = 100;
2299        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2300        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2301            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2302            // We will wait for up to 100 seconds.
2303            final long timeStart = SystemClock.uptimeMillis();
2304            final long timeEnd = timeStart + 100 * 1000;
2305            long timeNow = timeStart;
2306            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2307                try {
2308                    Thread.sleep(WAIT_TIME_MS);
2309                } catch (InterruptedException e) {
2310                    // Do nothing
2311                }
2312                timeNow = SystemClock.uptimeMillis();
2313                if (timeNow > timeEnd) {
2314                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2315                    Slog.wtf(TAG, "cppreopt did not finish!");
2316                    break;
2317                }
2318            }
2319
2320            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2321        }
2322    }
2323
2324    public PackageManagerService(Context context, Installer installer,
2325            boolean factoryTest, boolean onlyCore) {
2326        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2327        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2328        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2329                SystemClock.uptimeMillis());
2330
2331        if (mSdkVersion <= 0) {
2332            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2333        }
2334
2335        mContext = context;
2336
2337        mFactoryTest = factoryTest;
2338        mOnlyCore = onlyCore;
2339        mMetrics = new DisplayMetrics();
2340        mInstaller = installer;
2341
2342        // Create sub-components that provide services / data. Order here is important.
2343        synchronized (mInstallLock) {
2344        synchronized (mPackages) {
2345            // Expose private service for system components to use.
2346            LocalServices.addService(
2347                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2348            sUserManager = new UserManagerService(context, this,
2349                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2350            mPermissionManager = PermissionManagerService.create(context,
2351                    new DefaultPermissionGrantedCallback() {
2352                        @Override
2353                        public void onDefaultRuntimePermissionsGranted(int userId) {
2354                            synchronized(mPackages) {
2355                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2356                            }
2357                        }
2358                    }, mPackages /*externalLock*/);
2359            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2360            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2361        }
2362        }
2363        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2364                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2365        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2366                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2367        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2368                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2369        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2370                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2371        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2372                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2373        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2374                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2375
2376        String separateProcesses = SystemProperties.get("debug.separate_processes");
2377        if (separateProcesses != null && separateProcesses.length() > 0) {
2378            if ("*".equals(separateProcesses)) {
2379                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2380                mSeparateProcesses = null;
2381                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2382            } else {
2383                mDefParseFlags = 0;
2384                mSeparateProcesses = separateProcesses.split(",");
2385                Slog.w(TAG, "Running with debug.separate_processes: "
2386                        + separateProcesses);
2387            }
2388        } else {
2389            mDefParseFlags = 0;
2390            mSeparateProcesses = null;
2391        }
2392
2393        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2394                "*dexopt*");
2395        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2396                installer, mInstallLock);
2397        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2398                dexManagerListener);
2399        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2400
2401        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2402                FgThread.get().getLooper());
2403
2404        getDefaultDisplayMetrics(context, mMetrics);
2405
2406        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2407        SystemConfig systemConfig = SystemConfig.getInstance();
2408        mAvailableFeatures = systemConfig.getAvailableFeatures();
2409        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2410
2411        mProtectedPackages = new ProtectedPackages(mContext);
2412
2413        synchronized (mInstallLock) {
2414        // writer
2415        synchronized (mPackages) {
2416            mHandlerThread = new ServiceThread(TAG,
2417                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2418            mHandlerThread.start();
2419            mHandler = new PackageHandler(mHandlerThread.getLooper());
2420            mProcessLoggingHandler = new ProcessLoggingHandler();
2421            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2422            mInstantAppRegistry = new InstantAppRegistry(this);
2423
2424            File dataDir = Environment.getDataDirectory();
2425            mAppInstallDir = new File(dataDir, "app");
2426            mAppLib32InstallDir = new File(dataDir, "app-lib");
2427            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2428
2429            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2430            final int builtInLibCount = libConfig.size();
2431            for (int i = 0; i < builtInLibCount; i++) {
2432                String name = libConfig.keyAt(i);
2433                String path = libConfig.valueAt(i);
2434                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2435                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2436            }
2437
2438            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2439
2440            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2441            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2442            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2443
2444            // Clean up orphaned packages for which the code path doesn't exist
2445            // and they are an update to a system app - caused by bug/32321269
2446            final int packageSettingCount = mSettings.mPackages.size();
2447            for (int i = packageSettingCount - 1; i >= 0; i--) {
2448                PackageSetting ps = mSettings.mPackages.valueAt(i);
2449                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2450                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2451                    mSettings.mPackages.removeAt(i);
2452                    mSettings.enableSystemPackageLPw(ps.name);
2453                }
2454            }
2455
2456            if (mFirstBoot) {
2457                requestCopyPreoptedFiles();
2458            }
2459
2460            String customResolverActivity = Resources.getSystem().getString(
2461                    R.string.config_customResolverActivity);
2462            if (TextUtils.isEmpty(customResolverActivity)) {
2463                customResolverActivity = null;
2464            } else {
2465                mCustomResolverComponentName = ComponentName.unflattenFromString(
2466                        customResolverActivity);
2467            }
2468
2469            long startTime = SystemClock.uptimeMillis();
2470
2471            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2472                    startTime);
2473
2474            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2475            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2476
2477            if (bootClassPath == null) {
2478                Slog.w(TAG, "No BOOTCLASSPATH found!");
2479            }
2480
2481            if (systemServerClassPath == null) {
2482                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2483            }
2484
2485            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2486
2487            final VersionInfo ver = mSettings.getInternalVersion();
2488            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2489            if (mIsUpgrade) {
2490                logCriticalInfo(Log.INFO,
2491                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2492            }
2493
2494            // when upgrading from pre-M, promote system app permissions from install to runtime
2495            mPromoteSystemApps =
2496                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2497
2498            // When upgrading from pre-N, we need to handle package extraction like first boot,
2499            // as there is no profiling data available.
2500            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2501
2502            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2503
2504            // save off the names of pre-existing system packages prior to scanning; we don't
2505            // want to automatically grant runtime permissions for new system apps
2506            if (mPromoteSystemApps) {
2507                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2508                while (pkgSettingIter.hasNext()) {
2509                    PackageSetting ps = pkgSettingIter.next();
2510                    if (isSystemApp(ps)) {
2511                        mExistingSystemPackages.add(ps.name);
2512                    }
2513                }
2514            }
2515
2516            mCacheDir = preparePackageParserCache(mIsUpgrade);
2517
2518            // Set flag to monitor and not change apk file paths when
2519            // scanning install directories.
2520            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2521
2522            if (mIsUpgrade || mFirstBoot) {
2523                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2524            }
2525
2526            // Collect vendor overlay packages. (Do this before scanning any apps.)
2527            // For security and version matching reason, only consider
2528            // overlay packages if they reside in the right directory.
2529            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2530                    mDefParseFlags
2531                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2532                    scanFlags
2533                    | SCAN_AS_SYSTEM
2534                    | SCAN_TRUSTED_OVERLAY,
2535                    0);
2536
2537            mParallelPackageParserCallback.findStaticOverlayPackages();
2538
2539            // Find base frameworks (resource packages without code).
2540            scanDirTracedLI(frameworkDir,
2541                    mDefParseFlags
2542                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2543                    scanFlags
2544                    | SCAN_NO_DEX
2545                    | SCAN_AS_SYSTEM
2546                    | SCAN_AS_PRIVILEGED,
2547                    0);
2548
2549            // Collected privileged system packages.
2550            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2551            scanDirTracedLI(privilegedAppDir,
2552                    mDefParseFlags
2553                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2554                    scanFlags
2555                    | SCAN_AS_SYSTEM
2556                    | SCAN_AS_PRIVILEGED,
2557                    0);
2558
2559            // Collect ordinary system packages.
2560            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2561            scanDirTracedLI(systemAppDir,
2562                    mDefParseFlags
2563                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2564                    scanFlags
2565                    | SCAN_AS_SYSTEM,
2566                    0);
2567
2568            // Collected privileged vendor packages.
2569                File privilegedVendorAppDir = new File(Environment.getVendorDirectory(),
2570                        "priv-app");
2571            try {
2572                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2573            } catch (IOException e) {
2574                // failed to look up canonical path, continue with original one
2575            }
2576            scanDirTracedLI(privilegedVendorAppDir,
2577                    mDefParseFlags
2578                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2579                    scanFlags
2580                    | SCAN_AS_SYSTEM
2581                    | SCAN_AS_VENDOR
2582                    | SCAN_AS_PRIVILEGED,
2583                    0);
2584
2585            // Collect ordinary vendor packages.
2586            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2587            try {
2588                vendorAppDir = vendorAppDir.getCanonicalFile();
2589            } catch (IOException e) {
2590                // failed to look up canonical path, continue with original one
2591            }
2592            scanDirTracedLI(vendorAppDir,
2593                    mDefParseFlags
2594                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2595                    scanFlags
2596                    | SCAN_AS_SYSTEM
2597                    | SCAN_AS_VENDOR,
2598                    0);
2599
2600            // Collect all OEM packages.
2601            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2602            scanDirTracedLI(oemAppDir,
2603                    mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2605                    scanFlags
2606                    | SCAN_AS_SYSTEM
2607                    | SCAN_AS_OEM,
2608                    0);
2609
2610            // Prune any system packages that no longer exist.
2611            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2612            // Stub packages must either be replaced with full versions in the /data
2613            // partition or be disabled.
2614            final List<String> stubSystemApps = new ArrayList<>();
2615            if (!mOnlyCore) {
2616                // do this first before mucking with mPackages for the "expecting better" case
2617                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2618                while (pkgIterator.hasNext()) {
2619                    final PackageParser.Package pkg = pkgIterator.next();
2620                    if (pkg.isStub) {
2621                        stubSystemApps.add(pkg.packageName);
2622                    }
2623                }
2624
2625                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2626                while (psit.hasNext()) {
2627                    PackageSetting ps = psit.next();
2628
2629                    /*
2630                     * If this is not a system app, it can't be a
2631                     * disable system app.
2632                     */
2633                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2634                        continue;
2635                    }
2636
2637                    /*
2638                     * If the package is scanned, it's not erased.
2639                     */
2640                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2641                    if (scannedPkg != null) {
2642                        /*
2643                         * If the system app is both scanned and in the
2644                         * disabled packages list, then it must have been
2645                         * added via OTA. Remove it from the currently
2646                         * scanned package so the previously user-installed
2647                         * application can be scanned.
2648                         */
2649                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2650                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2651                                    + ps.name + "; removing system app.  Last known codePath="
2652                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2653                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2654                                    + scannedPkg.mVersionCode);
2655                            removePackageLI(scannedPkg, true);
2656                            mExpectingBetter.put(ps.name, ps.codePath);
2657                        }
2658
2659                        continue;
2660                    }
2661
2662                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2663                        psit.remove();
2664                        logCriticalInfo(Log.WARN, "System package " + ps.name
2665                                + " no longer exists; it's data will be wiped");
2666                        // Actual deletion of code and data will be handled by later
2667                        // reconciliation step
2668                    } else {
2669                        // we still have a disabled system package, but, it still might have
2670                        // been removed. check the code path still exists and check there's
2671                        // still a package. the latter can happen if an OTA keeps the same
2672                        // code path, but, changes the package name.
2673                        final PackageSetting disabledPs =
2674                                mSettings.getDisabledSystemPkgLPr(ps.name);
2675                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2676                                || disabledPs.pkg == null) {
2677                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2678                        }
2679                    }
2680                }
2681            }
2682
2683            //look for any incomplete package installations
2684            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2685            for (int i = 0; i < deletePkgsList.size(); i++) {
2686                // Actual deletion of code and data will be handled by later
2687                // reconciliation step
2688                final String packageName = deletePkgsList.get(i).name;
2689                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2690                synchronized (mPackages) {
2691                    mSettings.removePackageLPw(packageName);
2692                }
2693            }
2694
2695            //delete tmp files
2696            deleteTempPackageFiles();
2697
2698            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2699
2700            // Remove any shared userIDs that have no associated packages
2701            mSettings.pruneSharedUsersLPw();
2702            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2703            final int systemPackagesCount = mPackages.size();
2704            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2705                    + " ms, packageCount: " + systemPackagesCount
2706                    + " , timePerPackage: "
2707                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2708                    + " , cached: " + cachedSystemApps);
2709            if (mIsUpgrade && systemPackagesCount > 0) {
2710                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2711                        ((int) systemScanTime) / systemPackagesCount);
2712            }
2713            if (!mOnlyCore) {
2714                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2715                        SystemClock.uptimeMillis());
2716                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2717
2718                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2719                        | PackageParser.PARSE_FORWARD_LOCK,
2720                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2721
2722                // Remove disable package settings for updated system apps that were
2723                // removed via an OTA. If the update is no longer present, remove the
2724                // app completely. Otherwise, revoke their system privileges.
2725                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2726                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2727                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2728
2729                    final String msg;
2730                    if (deletedPkg == null) {
2731                        // should have found an update, but, we didn't; remove everything
2732                        msg = "Updated system package " + deletedAppName
2733                                + " no longer exists; removing its data";
2734                        // Actual deletion of code and data will be handled by later
2735                        // reconciliation step
2736                    } else {
2737                        // found an update; revoke system privileges
2738                        msg = "Updated system package + " + deletedAppName
2739                                + " no longer exists; revoking system privileges";
2740
2741                        // Don't do anything if a stub is removed from the system image. If
2742                        // we were to remove the uncompressed version from the /data partition,
2743                        // this is where it'd be done.
2744
2745                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2746                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2747                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2748                    }
2749                    logCriticalInfo(Log.WARN, msg);
2750                }
2751
2752                /*
2753                 * Make sure all system apps that we expected to appear on
2754                 * the userdata partition actually showed up. If they never
2755                 * appeared, crawl back and revive the system version.
2756                 */
2757                for (int i = 0; i < mExpectingBetter.size(); i++) {
2758                    final String packageName = mExpectingBetter.keyAt(i);
2759                    if (!mPackages.containsKey(packageName)) {
2760                        final File scanFile = mExpectingBetter.valueAt(i);
2761
2762                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2763                                + " but never showed up; reverting to system");
2764
2765                        final @ParseFlags int reparseFlags;
2766                        final @ScanFlags int rescanFlags;
2767                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2768                            reparseFlags =
2769                                    mDefParseFlags |
2770                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2771                            rescanFlags =
2772                                    scanFlags
2773                                    | SCAN_AS_SYSTEM
2774                                    | SCAN_AS_PRIVILEGED;
2775                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2776                            reparseFlags =
2777                                    mDefParseFlags |
2778                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2779                            rescanFlags =
2780                                    scanFlags
2781                                    | SCAN_AS_SYSTEM;
2782                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) {
2783                            reparseFlags =
2784                                    mDefParseFlags |
2785                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2786                            rescanFlags =
2787                                    scanFlags
2788                                    | SCAN_AS_SYSTEM
2789                                    | SCAN_AS_VENDOR
2790                                    | SCAN_AS_PRIVILEGED;
2791                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2792                            reparseFlags =
2793                                    mDefParseFlags |
2794                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2795                            rescanFlags =
2796                                    scanFlags
2797                                    | SCAN_AS_SYSTEM
2798                                    | SCAN_AS_VENDOR;
2799                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2800                            reparseFlags =
2801                                    mDefParseFlags |
2802                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2803                            rescanFlags =
2804                                    scanFlags
2805                                    | SCAN_AS_SYSTEM
2806                                    | SCAN_AS_OEM;
2807                        } else {
2808                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2809                            continue;
2810                        }
2811
2812                        mSettings.enableSystemPackageLPw(packageName);
2813
2814                        try {
2815                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2816                        } catch (PackageManagerException e) {
2817                            Slog.e(TAG, "Failed to parse original system package: "
2818                                    + e.getMessage());
2819                        }
2820                    }
2821                }
2822
2823                // Uncompress and install any stubbed system applications.
2824                // This must be done last to ensure all stubs are replaced or disabled.
2825                decompressSystemApplications(stubSystemApps, scanFlags);
2826
2827                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2828                                - cachedSystemApps;
2829
2830                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2831                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2832                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2833                        + " ms, packageCount: " + dataPackagesCount
2834                        + " , timePerPackage: "
2835                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2836                        + " , cached: " + cachedNonSystemApps);
2837                if (mIsUpgrade && dataPackagesCount > 0) {
2838                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2839                            ((int) dataScanTime) / dataPackagesCount);
2840                }
2841            }
2842            mExpectingBetter.clear();
2843
2844            // Resolve the storage manager.
2845            mStorageManagerPackage = getStorageManagerPackageName();
2846
2847            // Resolve protected action filters. Only the setup wizard is allowed to
2848            // have a high priority filter for these actions.
2849            mSetupWizardPackage = getSetupWizardPackageName();
2850            if (mProtectedFilters.size() > 0) {
2851                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2852                    Slog.i(TAG, "No setup wizard;"
2853                        + " All protected intents capped to priority 0");
2854                }
2855                for (ActivityIntentInfo filter : mProtectedFilters) {
2856                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2857                        if (DEBUG_FILTERS) {
2858                            Slog.i(TAG, "Found setup wizard;"
2859                                + " allow priority " + filter.getPriority() + ";"
2860                                + " package: " + filter.activity.info.packageName
2861                                + " activity: " + filter.activity.className
2862                                + " priority: " + filter.getPriority());
2863                        }
2864                        // skip setup wizard; allow it to keep the high priority filter
2865                        continue;
2866                    }
2867                    if (DEBUG_FILTERS) {
2868                        Slog.i(TAG, "Protected action; cap priority to 0;"
2869                                + " package: " + filter.activity.info.packageName
2870                                + " activity: " + filter.activity.className
2871                                + " origPrio: " + filter.getPriority());
2872                    }
2873                    filter.setPriority(0);
2874                }
2875            }
2876            mDeferProtectedFilters = false;
2877            mProtectedFilters.clear();
2878
2879            // Now that we know all of the shared libraries, update all clients to have
2880            // the correct library paths.
2881            updateAllSharedLibrariesLPw(null);
2882
2883            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2884                // NOTE: We ignore potential failures here during a system scan (like
2885                // the rest of the commands above) because there's precious little we
2886                // can do about it. A settings error is reported, though.
2887                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2888            }
2889
2890            // Now that we know all the packages we are keeping,
2891            // read and update their last usage times.
2892            mPackageUsage.read(mPackages);
2893            mCompilerStats.read();
2894
2895            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2896                    SystemClock.uptimeMillis());
2897            Slog.i(TAG, "Time to scan packages: "
2898                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2899                    + " seconds");
2900
2901            // If the platform SDK has changed since the last time we booted,
2902            // we need to re-grant app permission to catch any new ones that
2903            // appear.  This is really a hack, and means that apps can in some
2904            // cases get permissions that the user didn't initially explicitly
2905            // allow...  it would be nice to have some better way to handle
2906            // this situation.
2907            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2908            if (sdkUpdated) {
2909                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2910                        + mSdkVersion + "; regranting permissions for internal storage");
2911            }
2912            mPermissionManager.updateAllPermissions(
2913                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2914                    mPermissionCallback);
2915            ver.sdkVersion = mSdkVersion;
2916
2917            // If this is the first boot or an update from pre-M, and it is a normal
2918            // boot, then we need to initialize the default preferred apps across
2919            // all defined users.
2920            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2921                for (UserInfo user : sUserManager.getUsers(true)) {
2922                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2923                    applyFactoryDefaultBrowserLPw(user.id);
2924                    primeDomainVerificationsLPw(user.id);
2925                }
2926            }
2927
2928            // Prepare storage for system user really early during boot,
2929            // since core system apps like SettingsProvider and SystemUI
2930            // can't wait for user to start
2931            final int storageFlags;
2932            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2933                storageFlags = StorageManager.FLAG_STORAGE_DE;
2934            } else {
2935                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2936            }
2937            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2938                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2939                    true /* onlyCoreApps */);
2940            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2941                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2942                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2943                traceLog.traceBegin("AppDataFixup");
2944                try {
2945                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2946                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2947                } catch (InstallerException e) {
2948                    Slog.w(TAG, "Trouble fixing GIDs", e);
2949                }
2950                traceLog.traceEnd();
2951
2952                traceLog.traceBegin("AppDataPrepare");
2953                if (deferPackages == null || deferPackages.isEmpty()) {
2954                    return;
2955                }
2956                int count = 0;
2957                for (String pkgName : deferPackages) {
2958                    PackageParser.Package pkg = null;
2959                    synchronized (mPackages) {
2960                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2961                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2962                            pkg = ps.pkg;
2963                        }
2964                    }
2965                    if (pkg != null) {
2966                        synchronized (mInstallLock) {
2967                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2968                                    true /* maybeMigrateAppData */);
2969                        }
2970                        count++;
2971                    }
2972                }
2973                traceLog.traceEnd();
2974                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2975            }, "prepareAppData");
2976
2977            // If this is first boot after an OTA, and a normal boot, then
2978            // we need to clear code cache directories.
2979            // Note that we do *not* clear the application profiles. These remain valid
2980            // across OTAs and are used to drive profile verification (post OTA) and
2981            // profile compilation (without waiting to collect a fresh set of profiles).
2982            if (mIsUpgrade && !onlyCore) {
2983                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2984                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2985                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2986                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2987                        // No apps are running this early, so no need to freeze
2988                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2989                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2990                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2991                    }
2992                }
2993                ver.fingerprint = Build.FINGERPRINT;
2994            }
2995
2996            checkDefaultBrowser();
2997
2998            // clear only after permissions and other defaults have been updated
2999            mExistingSystemPackages.clear();
3000            mPromoteSystemApps = false;
3001
3002            // All the changes are done during package scanning.
3003            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3004
3005            // can downgrade to reader
3006            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3007            mSettings.writeLPr();
3008            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3009            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3010                    SystemClock.uptimeMillis());
3011
3012            if (!mOnlyCore) {
3013                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3014                mRequiredInstallerPackage = getRequiredInstallerLPr();
3015                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3016                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3017                if (mIntentFilterVerifierComponent != null) {
3018                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3019                            mIntentFilterVerifierComponent);
3020                } else {
3021                    mIntentFilterVerifier = null;
3022                }
3023                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3024                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3025                        SharedLibraryInfo.VERSION_UNDEFINED);
3026                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3027                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3028                        SharedLibraryInfo.VERSION_UNDEFINED);
3029            } else {
3030                mRequiredVerifierPackage = null;
3031                mRequiredInstallerPackage = null;
3032                mRequiredUninstallerPackage = null;
3033                mIntentFilterVerifierComponent = null;
3034                mIntentFilterVerifier = null;
3035                mServicesSystemSharedLibraryPackageName = null;
3036                mSharedSystemSharedLibraryPackageName = null;
3037            }
3038
3039            mInstallerService = new PackageInstallerService(context, this);
3040            mArtManagerService = new ArtManagerService(this);
3041            final Pair<ComponentName, String> instantAppResolverComponent =
3042                    getInstantAppResolverLPr();
3043            if (instantAppResolverComponent != null) {
3044                if (DEBUG_EPHEMERAL) {
3045                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3046                }
3047                mInstantAppResolverConnection = new EphemeralResolverConnection(
3048                        mContext, instantAppResolverComponent.first,
3049                        instantAppResolverComponent.second);
3050                mInstantAppResolverSettingsComponent =
3051                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3052            } else {
3053                mInstantAppResolverConnection = null;
3054                mInstantAppResolverSettingsComponent = null;
3055            }
3056            updateInstantAppInstallerLocked(null);
3057
3058            // Read and update the usage of dex files.
3059            // Do this at the end of PM init so that all the packages have their
3060            // data directory reconciled.
3061            // At this point we know the code paths of the packages, so we can validate
3062            // the disk file and build the internal cache.
3063            // The usage file is expected to be small so loading and verifying it
3064            // should take a fairly small time compare to the other activities (e.g. package
3065            // scanning).
3066            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3067            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3068            for (int userId : currentUserIds) {
3069                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3070            }
3071            mDexManager.load(userPackages);
3072            if (mIsUpgrade) {
3073                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3074                        (int) (SystemClock.uptimeMillis() - startTime));
3075            }
3076        } // synchronized (mPackages)
3077        } // synchronized (mInstallLock)
3078
3079        // Now after opening every single application zip, make sure they
3080        // are all flushed.  Not really needed, but keeps things nice and
3081        // tidy.
3082        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3083        Runtime.getRuntime().gc();
3084        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3085
3086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3087        FallbackCategoryProvider.loadFallbacks();
3088        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3089
3090        // The initial scanning above does many calls into installd while
3091        // holding the mPackages lock, but we're mostly interested in yelling
3092        // once we have a booted system.
3093        mInstaller.setWarnIfHeld(mPackages);
3094
3095        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3096    }
3097
3098    /**
3099     * Uncompress and install stub applications.
3100     * <p>In order to save space on the system partition, some applications are shipped in a
3101     * compressed form. In addition the compressed bits for the full application, the
3102     * system image contains a tiny stub comprised of only the Android manifest.
3103     * <p>During the first boot, attempt to uncompress and install the full application. If
3104     * the application can't be installed for any reason, disable the stub and prevent
3105     * uncompressing the full application during future boots.
3106     * <p>In order to forcefully attempt an installation of a full application, go to app
3107     * settings and enable the application.
3108     */
3109    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3110        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3111            final String pkgName = stubSystemApps.get(i);
3112            // skip if the system package is already disabled
3113            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3114                stubSystemApps.remove(i);
3115                continue;
3116            }
3117            // skip if the package isn't installed (?!); this should never happen
3118            final PackageParser.Package pkg = mPackages.get(pkgName);
3119            if (pkg == null) {
3120                stubSystemApps.remove(i);
3121                continue;
3122            }
3123            // skip if the package has been disabled by the user
3124            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3125            if (ps != null) {
3126                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3127                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3128                    stubSystemApps.remove(i);
3129                    continue;
3130                }
3131            }
3132
3133            if (DEBUG_COMPRESSION) {
3134                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3135            }
3136
3137            // uncompress the binary to its eventual destination on /data
3138            final File scanFile = decompressPackage(pkg);
3139            if (scanFile == null) {
3140                continue;
3141            }
3142
3143            // install the package to replace the stub on /system
3144            try {
3145                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3146                removePackageLI(pkg, true /*chatty*/);
3147                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3148                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3149                        UserHandle.USER_SYSTEM, "android");
3150                stubSystemApps.remove(i);
3151                continue;
3152            } catch (PackageManagerException e) {
3153                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3154            }
3155
3156            // any failed attempt to install the package will be cleaned up later
3157        }
3158
3159        // disable any stub still left; these failed to install the full application
3160        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3161            final String pkgName = stubSystemApps.get(i);
3162            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3163            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3164                    UserHandle.USER_SYSTEM, "android");
3165            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3166        }
3167    }
3168
3169    /**
3170     * Decompresses the given package on the system image onto
3171     * the /data partition.
3172     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3173     */
3174    private File decompressPackage(PackageParser.Package pkg) {
3175        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3176        if (compressedFiles == null || compressedFiles.length == 0) {
3177            if (DEBUG_COMPRESSION) {
3178                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3179            }
3180            return null;
3181        }
3182        final File dstCodePath =
3183                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3184        int ret = PackageManager.INSTALL_SUCCEEDED;
3185        try {
3186            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3187            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3188            for (File srcFile : compressedFiles) {
3189                final String srcFileName = srcFile.getName();
3190                final String dstFileName = srcFileName.substring(
3191                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3192                final File dstFile = new File(dstCodePath, dstFileName);
3193                ret = decompressFile(srcFile, dstFile);
3194                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3195                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3196                            + "; pkg: " + pkg.packageName
3197                            + ", file: " + dstFileName);
3198                    break;
3199                }
3200            }
3201        } catch (ErrnoException e) {
3202            logCriticalInfo(Log.ERROR, "Failed to decompress"
3203                    + "; pkg: " + pkg.packageName
3204                    + ", err: " + e.errno);
3205        }
3206        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3207            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3208            NativeLibraryHelper.Handle handle = null;
3209            try {
3210                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3211                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3212                        null /*abiOverride*/);
3213            } catch (IOException e) {
3214                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3215                        + "; pkg: " + pkg.packageName);
3216                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3217            } finally {
3218                IoUtils.closeQuietly(handle);
3219            }
3220        }
3221        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3222            if (dstCodePath == null || !dstCodePath.exists()) {
3223                return null;
3224            }
3225            removeCodePathLI(dstCodePath);
3226            return null;
3227        }
3228
3229        return dstCodePath;
3230    }
3231
3232    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3233        // we're only interested in updating the installer appliction when 1) it's not
3234        // already set or 2) the modified package is the installer
3235        if (mInstantAppInstallerActivity != null
3236                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3237                        .equals(modifiedPackage)) {
3238            return;
3239        }
3240        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3241    }
3242
3243    private static File preparePackageParserCache(boolean isUpgrade) {
3244        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3245            return null;
3246        }
3247
3248        // Disable package parsing on eng builds to allow for faster incremental development.
3249        if (Build.IS_ENG) {
3250            return null;
3251        }
3252
3253        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3254            Slog.i(TAG, "Disabling package parser cache due to system property.");
3255            return null;
3256        }
3257
3258        // The base directory for the package parser cache lives under /data/system/.
3259        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3260                "package_cache");
3261        if (cacheBaseDir == null) {
3262            return null;
3263        }
3264
3265        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3266        // This also serves to "GC" unused entries when the package cache version changes (which
3267        // can only happen during upgrades).
3268        if (isUpgrade) {
3269            FileUtils.deleteContents(cacheBaseDir);
3270        }
3271
3272
3273        // Return the versioned package cache directory. This is something like
3274        // "/data/system/package_cache/1"
3275        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3276
3277        // The following is a workaround to aid development on non-numbered userdebug
3278        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3279        // the system partition is newer.
3280        //
3281        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3282        // that starts with "eng." to signify that this is an engineering build and not
3283        // destined for release.
3284        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3285            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3286
3287            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3288            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3289            // in general and should not be used for production changes. In this specific case,
3290            // we know that they will work.
3291            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3292            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3293                FileUtils.deleteContents(cacheBaseDir);
3294                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3295            }
3296        }
3297
3298        return cacheDir;
3299    }
3300
3301    @Override
3302    public boolean isFirstBoot() {
3303        // allow instant applications
3304        return mFirstBoot;
3305    }
3306
3307    @Override
3308    public boolean isOnlyCoreApps() {
3309        // allow instant applications
3310        return mOnlyCore;
3311    }
3312
3313    @Override
3314    public boolean isUpgrade() {
3315        // allow instant applications
3316        // The system property allows testing ota flow when upgraded to the same image.
3317        return mIsUpgrade || SystemProperties.getBoolean(
3318                "persist.pm.mock-upgrade", false /* default */);
3319    }
3320
3321    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3322        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3323
3324        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3325                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3326                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3327        if (matches.size() == 1) {
3328            return matches.get(0).getComponentInfo().packageName;
3329        } else if (matches.size() == 0) {
3330            Log.e(TAG, "There should probably be a verifier, but, none were found");
3331            return null;
3332        }
3333        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3334    }
3335
3336    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3337        synchronized (mPackages) {
3338            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3339            if (libraryEntry == null) {
3340                throw new IllegalStateException("Missing required shared library:" + name);
3341            }
3342            return libraryEntry.apk;
3343        }
3344    }
3345
3346    private @NonNull String getRequiredInstallerLPr() {
3347        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3348        intent.addCategory(Intent.CATEGORY_DEFAULT);
3349        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3350
3351        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3352                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3353                UserHandle.USER_SYSTEM);
3354        if (matches.size() == 1) {
3355            ResolveInfo resolveInfo = matches.get(0);
3356            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3357                throw new RuntimeException("The installer must be a privileged app");
3358            }
3359            return matches.get(0).getComponentInfo().packageName;
3360        } else {
3361            throw new RuntimeException("There must be exactly one installer; found " + matches);
3362        }
3363    }
3364
3365    private @NonNull String getRequiredUninstallerLPr() {
3366        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3367        intent.addCategory(Intent.CATEGORY_DEFAULT);
3368        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3369
3370        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3371                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3372                UserHandle.USER_SYSTEM);
3373        if (resolveInfo == null ||
3374                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3375            throw new RuntimeException("There must be exactly one uninstaller; found "
3376                    + resolveInfo);
3377        }
3378        return resolveInfo.getComponentInfo().packageName;
3379    }
3380
3381    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3382        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3383
3384        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3385                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3386                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3387        ResolveInfo best = null;
3388        final int N = matches.size();
3389        for (int i = 0; i < N; i++) {
3390            final ResolveInfo cur = matches.get(i);
3391            final String packageName = cur.getComponentInfo().packageName;
3392            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3393                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3394                continue;
3395            }
3396
3397            if (best == null || cur.priority > best.priority) {
3398                best = cur;
3399            }
3400        }
3401
3402        if (best != null) {
3403            return best.getComponentInfo().getComponentName();
3404        }
3405        Slog.w(TAG, "Intent filter verifier not found");
3406        return null;
3407    }
3408
3409    @Override
3410    public @Nullable ComponentName getInstantAppResolverComponent() {
3411        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3412            return null;
3413        }
3414        synchronized (mPackages) {
3415            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3416            if (instantAppResolver == null) {
3417                return null;
3418            }
3419            return instantAppResolver.first;
3420        }
3421    }
3422
3423    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3424        final String[] packageArray =
3425                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3426        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3427            if (DEBUG_EPHEMERAL) {
3428                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3429            }
3430            return null;
3431        }
3432
3433        final int callingUid = Binder.getCallingUid();
3434        final int resolveFlags =
3435                MATCH_DIRECT_BOOT_AWARE
3436                | MATCH_DIRECT_BOOT_UNAWARE
3437                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3438        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3439        final Intent resolverIntent = new Intent(actionName);
3440        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3441                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3442        // temporarily look for the old action
3443        if (resolvers.size() == 0) {
3444            if (DEBUG_EPHEMERAL) {
3445                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3446            }
3447            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3448            resolverIntent.setAction(actionName);
3449            resolvers = queryIntentServicesInternal(resolverIntent, null,
3450                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3451        }
3452        final int N = resolvers.size();
3453        if (N == 0) {
3454            if (DEBUG_EPHEMERAL) {
3455                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3456            }
3457            return null;
3458        }
3459
3460        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3461        for (int i = 0; i < N; i++) {
3462            final ResolveInfo info = resolvers.get(i);
3463
3464            if (info.serviceInfo == null) {
3465                continue;
3466            }
3467
3468            final String packageName = info.serviceInfo.packageName;
3469            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3470                if (DEBUG_EPHEMERAL) {
3471                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3472                            + " pkg: " + packageName + ", info:" + info);
3473                }
3474                continue;
3475            }
3476
3477            if (DEBUG_EPHEMERAL) {
3478                Slog.v(TAG, "Ephemeral resolver found;"
3479                        + " pkg: " + packageName + ", info:" + info);
3480            }
3481            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3482        }
3483        if (DEBUG_EPHEMERAL) {
3484            Slog.v(TAG, "Ephemeral resolver NOT found");
3485        }
3486        return null;
3487    }
3488
3489    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3490        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3491        intent.addCategory(Intent.CATEGORY_DEFAULT);
3492        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3493
3494        final int resolveFlags =
3495                MATCH_DIRECT_BOOT_AWARE
3496                | MATCH_DIRECT_BOOT_UNAWARE
3497                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3498        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3499                resolveFlags, UserHandle.USER_SYSTEM);
3500        // temporarily look for the old action
3501        if (matches.isEmpty()) {
3502            if (DEBUG_EPHEMERAL) {
3503                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3504            }
3505            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3506            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3507                    resolveFlags, UserHandle.USER_SYSTEM);
3508        }
3509        Iterator<ResolveInfo> iter = matches.iterator();
3510        while (iter.hasNext()) {
3511            final ResolveInfo rInfo = iter.next();
3512            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3513            if (ps != null) {
3514                final PermissionsState permissionsState = ps.getPermissionsState();
3515                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3516                    continue;
3517                }
3518            }
3519            iter.remove();
3520        }
3521        if (matches.size() == 0) {
3522            return null;
3523        } else if (matches.size() == 1) {
3524            return (ActivityInfo) matches.get(0).getComponentInfo();
3525        } else {
3526            throw new RuntimeException(
3527                    "There must be at most one ephemeral installer; found " + matches);
3528        }
3529    }
3530
3531    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3532            @NonNull ComponentName resolver) {
3533        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3534                .addCategory(Intent.CATEGORY_DEFAULT)
3535                .setPackage(resolver.getPackageName());
3536        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3537        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3538                UserHandle.USER_SYSTEM);
3539        // temporarily look for the old action
3540        if (matches.isEmpty()) {
3541            if (DEBUG_EPHEMERAL) {
3542                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3543            }
3544            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3545            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3546                    UserHandle.USER_SYSTEM);
3547        }
3548        if (matches.isEmpty()) {
3549            return null;
3550        }
3551        return matches.get(0).getComponentInfo().getComponentName();
3552    }
3553
3554    private void primeDomainVerificationsLPw(int userId) {
3555        if (DEBUG_DOMAIN_VERIFICATION) {
3556            Slog.d(TAG, "Priming domain verifications in user " + userId);
3557        }
3558
3559        SystemConfig systemConfig = SystemConfig.getInstance();
3560        ArraySet<String> packages = systemConfig.getLinkedApps();
3561
3562        for (String packageName : packages) {
3563            PackageParser.Package pkg = mPackages.get(packageName);
3564            if (pkg != null) {
3565                if (!pkg.isSystem()) {
3566                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3567                    continue;
3568                }
3569
3570                ArraySet<String> domains = null;
3571                for (PackageParser.Activity a : pkg.activities) {
3572                    for (ActivityIntentInfo filter : a.intents) {
3573                        if (hasValidDomains(filter)) {
3574                            if (domains == null) {
3575                                domains = new ArraySet<String>();
3576                            }
3577                            domains.addAll(filter.getHostsList());
3578                        }
3579                    }
3580                }
3581
3582                if (domains != null && domains.size() > 0) {
3583                    if (DEBUG_DOMAIN_VERIFICATION) {
3584                        Slog.v(TAG, "      + " + packageName);
3585                    }
3586                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3587                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3588                    // and then 'always' in the per-user state actually used for intent resolution.
3589                    final IntentFilterVerificationInfo ivi;
3590                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3591                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3592                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3593                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3594                } else {
3595                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3596                            + "' does not handle web links");
3597                }
3598            } else {
3599                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3600            }
3601        }
3602
3603        scheduleWritePackageRestrictionsLocked(userId);
3604        scheduleWriteSettingsLocked();
3605    }
3606
3607    private void applyFactoryDefaultBrowserLPw(int userId) {
3608        // The default browser app's package name is stored in a string resource,
3609        // with a product-specific overlay used for vendor customization.
3610        String browserPkg = mContext.getResources().getString(
3611                com.android.internal.R.string.default_browser);
3612        if (!TextUtils.isEmpty(browserPkg)) {
3613            // non-empty string => required to be a known package
3614            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3615            if (ps == null) {
3616                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3617                browserPkg = null;
3618            } else {
3619                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3620            }
3621        }
3622
3623        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3624        // default.  If there's more than one, just leave everything alone.
3625        if (browserPkg == null) {
3626            calculateDefaultBrowserLPw(userId);
3627        }
3628    }
3629
3630    private void calculateDefaultBrowserLPw(int userId) {
3631        List<String> allBrowsers = resolveAllBrowserApps(userId);
3632        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3633        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3634    }
3635
3636    private List<String> resolveAllBrowserApps(int userId) {
3637        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3638        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3639                PackageManager.MATCH_ALL, userId);
3640
3641        final int count = list.size();
3642        List<String> result = new ArrayList<String>(count);
3643        for (int i=0; i<count; i++) {
3644            ResolveInfo info = list.get(i);
3645            if (info.activityInfo == null
3646                    || !info.handleAllWebDataURI
3647                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3648                    || result.contains(info.activityInfo.packageName)) {
3649                continue;
3650            }
3651            result.add(info.activityInfo.packageName);
3652        }
3653
3654        return result;
3655    }
3656
3657    private boolean packageIsBrowser(String packageName, int userId) {
3658        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3659                PackageManager.MATCH_ALL, userId);
3660        final int N = list.size();
3661        for (int i = 0; i < N; i++) {
3662            ResolveInfo info = list.get(i);
3663            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3664                return true;
3665            }
3666        }
3667        return false;
3668    }
3669
3670    private void checkDefaultBrowser() {
3671        final int myUserId = UserHandle.myUserId();
3672        final String packageName = getDefaultBrowserPackageName(myUserId);
3673        if (packageName != null) {
3674            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3675            if (info == null) {
3676                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3677                synchronized (mPackages) {
3678                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3679                }
3680            }
3681        }
3682    }
3683
3684    @Override
3685    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3686            throws RemoteException {
3687        try {
3688            return super.onTransact(code, data, reply, flags);
3689        } catch (RuntimeException e) {
3690            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3691                Slog.wtf(TAG, "Package Manager Crash", e);
3692            }
3693            throw e;
3694        }
3695    }
3696
3697    static int[] appendInts(int[] cur, int[] add) {
3698        if (add == null) return cur;
3699        if (cur == null) return add;
3700        final int N = add.length;
3701        for (int i=0; i<N; i++) {
3702            cur = appendInt(cur, add[i]);
3703        }
3704        return cur;
3705    }
3706
3707    /**
3708     * Returns whether or not a full application can see an instant application.
3709     * <p>
3710     * Currently, there are three cases in which this can occur:
3711     * <ol>
3712     * <li>The calling application is a "special" process. Special processes
3713     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3714     * <li>The calling application has the permission
3715     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3716     * <li>The calling application is the default launcher on the
3717     *     system partition.</li>
3718     * </ol>
3719     */
3720    private boolean canViewInstantApps(int callingUid, int userId) {
3721        if (callingUid < Process.FIRST_APPLICATION_UID) {
3722            return true;
3723        }
3724        if (mContext.checkCallingOrSelfPermission(
3725                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3726            return true;
3727        }
3728        if (mContext.checkCallingOrSelfPermission(
3729                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3730            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3731            if (homeComponent != null
3732                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3733                return true;
3734            }
3735        }
3736        return false;
3737    }
3738
3739    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3740        if (!sUserManager.exists(userId)) return null;
3741        if (ps == null) {
3742            return null;
3743        }
3744        PackageParser.Package p = ps.pkg;
3745        if (p == null) {
3746            return null;
3747        }
3748        final int callingUid = Binder.getCallingUid();
3749        // Filter out ephemeral app metadata:
3750        //   * The system/shell/root can see metadata for any app
3751        //   * An installed app can see metadata for 1) other installed apps
3752        //     and 2) ephemeral apps that have explicitly interacted with it
3753        //   * Ephemeral apps can only see their own data and exposed installed apps
3754        //   * Holding a signature permission allows seeing instant apps
3755        if (filterAppAccessLPr(ps, callingUid, userId)) {
3756            return null;
3757        }
3758
3759        final PermissionsState permissionsState = ps.getPermissionsState();
3760
3761        // Compute GIDs only if requested
3762        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3763                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3764        // Compute granted permissions only if package has requested permissions
3765        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3766                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3767        final PackageUserState state = ps.readUserState(userId);
3768
3769        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3770                && ps.isSystem()) {
3771            flags |= MATCH_ANY_USER;
3772        }
3773
3774        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3775                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3776
3777        if (packageInfo == null) {
3778            return null;
3779        }
3780
3781        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3782                resolveExternalPackageNameLPr(p);
3783
3784        return packageInfo;
3785    }
3786
3787    @Override
3788    public void checkPackageStartable(String packageName, int userId) {
3789        final int callingUid = Binder.getCallingUid();
3790        if (getInstantAppPackageName(callingUid) != null) {
3791            throw new SecurityException("Instant applications don't have access to this method");
3792        }
3793        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3794        synchronized (mPackages) {
3795            final PackageSetting ps = mSettings.mPackages.get(packageName);
3796            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3797                throw new SecurityException("Package " + packageName + " was not found!");
3798            }
3799
3800            if (!ps.getInstalled(userId)) {
3801                throw new SecurityException(
3802                        "Package " + packageName + " was not installed for user " + userId + "!");
3803            }
3804
3805            if (mSafeMode && !ps.isSystem()) {
3806                throw new SecurityException("Package " + packageName + " not a system app!");
3807            }
3808
3809            if (mFrozenPackages.contains(packageName)) {
3810                throw new SecurityException("Package " + packageName + " is currently frozen!");
3811            }
3812
3813            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3814                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3815            }
3816        }
3817    }
3818
3819    @Override
3820    public boolean isPackageAvailable(String packageName, int userId) {
3821        if (!sUserManager.exists(userId)) return false;
3822        final int callingUid = Binder.getCallingUid();
3823        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3824                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3825        synchronized (mPackages) {
3826            PackageParser.Package p = mPackages.get(packageName);
3827            if (p != null) {
3828                final PackageSetting ps = (PackageSetting) p.mExtras;
3829                if (filterAppAccessLPr(ps, callingUid, userId)) {
3830                    return false;
3831                }
3832                if (ps != null) {
3833                    final PackageUserState state = ps.readUserState(userId);
3834                    if (state != null) {
3835                        return PackageParser.isAvailable(state);
3836                    }
3837                }
3838            }
3839        }
3840        return false;
3841    }
3842
3843    @Override
3844    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3845        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3846                flags, Binder.getCallingUid(), userId);
3847    }
3848
3849    @Override
3850    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3851            int flags, int userId) {
3852        return getPackageInfoInternal(versionedPackage.getPackageName(),
3853                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3854    }
3855
3856    /**
3857     * Important: The provided filterCallingUid is used exclusively to filter out packages
3858     * that can be seen based on user state. It's typically the original caller uid prior
3859     * to clearing. Because it can only be provided by trusted code, it's value can be
3860     * trusted and will be used as-is; unlike userId which will be validated by this method.
3861     */
3862    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3863            int flags, int filterCallingUid, int userId) {
3864        if (!sUserManager.exists(userId)) return null;
3865        flags = updateFlagsForPackage(flags, userId, packageName);
3866        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3867                false /* requireFullPermission */, false /* checkShell */, "get package info");
3868
3869        // reader
3870        synchronized (mPackages) {
3871            // Normalize package name to handle renamed packages and static libs
3872            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3873
3874            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3875            if (matchFactoryOnly) {
3876                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3877                if (ps != null) {
3878                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3879                        return null;
3880                    }
3881                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3882                        return null;
3883                    }
3884                    return generatePackageInfo(ps, flags, userId);
3885                }
3886            }
3887
3888            PackageParser.Package p = mPackages.get(packageName);
3889            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3890                return null;
3891            }
3892            if (DEBUG_PACKAGE_INFO)
3893                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3894            if (p != null) {
3895                final PackageSetting ps = (PackageSetting) p.mExtras;
3896                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3897                    return null;
3898                }
3899                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3900                    return null;
3901                }
3902                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3903            }
3904            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3905                final PackageSetting ps = mSettings.mPackages.get(packageName);
3906                if (ps == null) return null;
3907                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3908                    return null;
3909                }
3910                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3911                    return null;
3912                }
3913                return generatePackageInfo(ps, flags, userId);
3914            }
3915        }
3916        return null;
3917    }
3918
3919    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3920        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3921            return true;
3922        }
3923        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3924            return true;
3925        }
3926        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3927            return true;
3928        }
3929        return false;
3930    }
3931
3932    private boolean isComponentVisibleToInstantApp(
3933            @Nullable ComponentName component, @ComponentType int type) {
3934        if (type == TYPE_ACTIVITY) {
3935            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3936            return activity != null
3937                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3938                    : false;
3939        } else if (type == TYPE_RECEIVER) {
3940            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3941            return activity != null
3942                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3943                    : false;
3944        } else if (type == TYPE_SERVICE) {
3945            final PackageParser.Service service = mServices.mServices.get(component);
3946            return service != null
3947                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3948                    : false;
3949        } else if (type == TYPE_PROVIDER) {
3950            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3951            return provider != null
3952                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3953                    : false;
3954        } else if (type == TYPE_UNKNOWN) {
3955            return isComponentVisibleToInstantApp(component);
3956        }
3957        return false;
3958    }
3959
3960    /**
3961     * Returns whether or not access to the application should be filtered.
3962     * <p>
3963     * Access may be limited based upon whether the calling or target applications
3964     * are instant applications.
3965     *
3966     * @see #canAccessInstantApps(int)
3967     */
3968    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3969            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3970        // if we're in an isolated process, get the real calling UID
3971        if (Process.isIsolated(callingUid)) {
3972            callingUid = mIsolatedOwners.get(callingUid);
3973        }
3974        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3975        final boolean callerIsInstantApp = instantAppPkgName != null;
3976        if (ps == null) {
3977            if (callerIsInstantApp) {
3978                // pretend the application exists, but, needs to be filtered
3979                return true;
3980            }
3981            return false;
3982        }
3983        // if the target and caller are the same application, don't filter
3984        if (isCallerSameApp(ps.name, callingUid)) {
3985            return false;
3986        }
3987        if (callerIsInstantApp) {
3988            // request for a specific component; if it hasn't been explicitly exposed, filter
3989            if (component != null) {
3990                return !isComponentVisibleToInstantApp(component, componentType);
3991            }
3992            // request for application; if no components have been explicitly exposed, filter
3993            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3994        }
3995        if (ps.getInstantApp(userId)) {
3996            // caller can see all components of all instant applications, don't filter
3997            if (canViewInstantApps(callingUid, userId)) {
3998                return false;
3999            }
4000            // request for a specific instant application component, filter
4001            if (component != null) {
4002                return true;
4003            }
4004            // request for an instant application; if the caller hasn't been granted access, filter
4005            return !mInstantAppRegistry.isInstantAccessGranted(
4006                    userId, UserHandle.getAppId(callingUid), ps.appId);
4007        }
4008        return false;
4009    }
4010
4011    /**
4012     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4013     */
4014    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4015        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4016    }
4017
4018    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4019            int flags) {
4020        // Callers can access only the libs they depend on, otherwise they need to explicitly
4021        // ask for the shared libraries given the caller is allowed to access all static libs.
4022        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4023            // System/shell/root get to see all static libs
4024            final int appId = UserHandle.getAppId(uid);
4025            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4026                    || appId == Process.ROOT_UID) {
4027                return false;
4028            }
4029        }
4030
4031        // No package means no static lib as it is always on internal storage
4032        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4033            return false;
4034        }
4035
4036        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4037                ps.pkg.staticSharedLibVersion);
4038        if (libEntry == null) {
4039            return false;
4040        }
4041
4042        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4043        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4044        if (uidPackageNames == null) {
4045            return true;
4046        }
4047
4048        for (String uidPackageName : uidPackageNames) {
4049            if (ps.name.equals(uidPackageName)) {
4050                return false;
4051            }
4052            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4053            if (uidPs != null) {
4054                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4055                        libEntry.info.getName());
4056                if (index < 0) {
4057                    continue;
4058                }
4059                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4060                    return false;
4061                }
4062            }
4063        }
4064        return true;
4065    }
4066
4067    @Override
4068    public String[] currentToCanonicalPackageNames(String[] names) {
4069        final int callingUid = Binder.getCallingUid();
4070        if (getInstantAppPackageName(callingUid) != null) {
4071            return names;
4072        }
4073        final String[] out = new String[names.length];
4074        // reader
4075        synchronized (mPackages) {
4076            final int callingUserId = UserHandle.getUserId(callingUid);
4077            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4078            for (int i=names.length-1; i>=0; i--) {
4079                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4080                boolean translateName = false;
4081                if (ps != null && ps.realName != null) {
4082                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4083                    translateName = !targetIsInstantApp
4084                            || canViewInstantApps
4085                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4086                                    UserHandle.getAppId(callingUid), ps.appId);
4087                }
4088                out[i] = translateName ? ps.realName : names[i];
4089            }
4090        }
4091        return out;
4092    }
4093
4094    @Override
4095    public String[] canonicalToCurrentPackageNames(String[] names) {
4096        final int callingUid = Binder.getCallingUid();
4097        if (getInstantAppPackageName(callingUid) != null) {
4098            return names;
4099        }
4100        final String[] out = new String[names.length];
4101        // reader
4102        synchronized (mPackages) {
4103            final int callingUserId = UserHandle.getUserId(callingUid);
4104            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4105            for (int i=names.length-1; i>=0; i--) {
4106                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4107                boolean translateName = false;
4108                if (cur != null) {
4109                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4110                    final boolean targetIsInstantApp =
4111                            ps != null && ps.getInstantApp(callingUserId);
4112                    translateName = !targetIsInstantApp
4113                            || canViewInstantApps
4114                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4115                                    UserHandle.getAppId(callingUid), ps.appId);
4116                }
4117                out[i] = translateName ? cur : names[i];
4118            }
4119        }
4120        return out;
4121    }
4122
4123    @Override
4124    public int getPackageUid(String packageName, int flags, int userId) {
4125        if (!sUserManager.exists(userId)) return -1;
4126        final int callingUid = Binder.getCallingUid();
4127        flags = updateFlagsForPackage(flags, userId, packageName);
4128        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4129                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4130
4131        // reader
4132        synchronized (mPackages) {
4133            final PackageParser.Package p = mPackages.get(packageName);
4134            if (p != null && p.isMatch(flags)) {
4135                PackageSetting ps = (PackageSetting) p.mExtras;
4136                if (filterAppAccessLPr(ps, callingUid, userId)) {
4137                    return -1;
4138                }
4139                return UserHandle.getUid(userId, p.applicationInfo.uid);
4140            }
4141            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4142                final PackageSetting ps = mSettings.mPackages.get(packageName);
4143                if (ps != null && ps.isMatch(flags)
4144                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4145                    return UserHandle.getUid(userId, ps.appId);
4146                }
4147            }
4148        }
4149
4150        return -1;
4151    }
4152
4153    @Override
4154    public int[] getPackageGids(String packageName, int flags, int userId) {
4155        if (!sUserManager.exists(userId)) return null;
4156        final int callingUid = Binder.getCallingUid();
4157        flags = updateFlagsForPackage(flags, userId, packageName);
4158        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4159                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4160
4161        // reader
4162        synchronized (mPackages) {
4163            final PackageParser.Package p = mPackages.get(packageName);
4164            if (p != null && p.isMatch(flags)) {
4165                PackageSetting ps = (PackageSetting) p.mExtras;
4166                if (filterAppAccessLPr(ps, callingUid, userId)) {
4167                    return null;
4168                }
4169                // TODO: Shouldn't this be checking for package installed state for userId and
4170                // return null?
4171                return ps.getPermissionsState().computeGids(userId);
4172            }
4173            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4174                final PackageSetting ps = mSettings.mPackages.get(packageName);
4175                if (ps != null && ps.isMatch(flags)
4176                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4177                    return ps.getPermissionsState().computeGids(userId);
4178                }
4179            }
4180        }
4181
4182        return null;
4183    }
4184
4185    @Override
4186    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4187        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4188    }
4189
4190    @Override
4191    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4192            int flags) {
4193        final List<PermissionInfo> permissionList =
4194                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4195        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4196    }
4197
4198    @Override
4199    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4200        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4201    }
4202
4203    @Override
4204    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4205        final List<PermissionGroupInfo> permissionList =
4206                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4207        return (permissionList == null)
4208                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4209    }
4210
4211    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4212            int filterCallingUid, int userId) {
4213        if (!sUserManager.exists(userId)) return null;
4214        PackageSetting ps = mSettings.mPackages.get(packageName);
4215        if (ps != null) {
4216            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4217                return null;
4218            }
4219            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4220                return null;
4221            }
4222            if (ps.pkg == null) {
4223                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4224                if (pInfo != null) {
4225                    return pInfo.applicationInfo;
4226                }
4227                return null;
4228            }
4229            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4230                    ps.readUserState(userId), userId);
4231            if (ai != null) {
4232                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4233            }
4234            return ai;
4235        }
4236        return null;
4237    }
4238
4239    @Override
4240    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4241        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4242    }
4243
4244    /**
4245     * Important: The provided filterCallingUid is used exclusively to filter out applications
4246     * that can be seen based on user state. It's typically the original caller uid prior
4247     * to clearing. Because it can only be provided by trusted code, it's value can be
4248     * trusted and will be used as-is; unlike userId which will be validated by this method.
4249     */
4250    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4251            int filterCallingUid, int userId) {
4252        if (!sUserManager.exists(userId)) return null;
4253        flags = updateFlagsForApplication(flags, userId, packageName);
4254        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4255                false /* requireFullPermission */, false /* checkShell */, "get application info");
4256
4257        // writer
4258        synchronized (mPackages) {
4259            // Normalize package name to handle renamed packages and static libs
4260            packageName = resolveInternalPackageNameLPr(packageName,
4261                    PackageManager.VERSION_CODE_HIGHEST);
4262
4263            PackageParser.Package p = mPackages.get(packageName);
4264            if (DEBUG_PACKAGE_INFO) Log.v(
4265                    TAG, "getApplicationInfo " + packageName
4266                    + ": " + p);
4267            if (p != null) {
4268                PackageSetting ps = mSettings.mPackages.get(packageName);
4269                if (ps == null) return null;
4270                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4271                    return null;
4272                }
4273                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4274                    return null;
4275                }
4276                // Note: isEnabledLP() does not apply here - always return info
4277                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4278                        p, flags, ps.readUserState(userId), userId);
4279                if (ai != null) {
4280                    ai.packageName = resolveExternalPackageNameLPr(p);
4281                }
4282                return ai;
4283            }
4284            if ("android".equals(packageName)||"system".equals(packageName)) {
4285                return mAndroidApplication;
4286            }
4287            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4288                // Already generates the external package name
4289                return generateApplicationInfoFromSettingsLPw(packageName,
4290                        flags, filterCallingUid, userId);
4291            }
4292        }
4293        return null;
4294    }
4295
4296    private String normalizePackageNameLPr(String packageName) {
4297        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4298        return normalizedPackageName != null ? normalizedPackageName : packageName;
4299    }
4300
4301    @Override
4302    public void deletePreloadsFileCache() {
4303        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4304            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4305        }
4306        File dir = Environment.getDataPreloadsFileCacheDirectory();
4307        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4308        FileUtils.deleteContents(dir);
4309    }
4310
4311    @Override
4312    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4313            final int storageFlags, final IPackageDataObserver observer) {
4314        mContext.enforceCallingOrSelfPermission(
4315                android.Manifest.permission.CLEAR_APP_CACHE, null);
4316        mHandler.post(() -> {
4317            boolean success = false;
4318            try {
4319                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4320                success = true;
4321            } catch (IOException e) {
4322                Slog.w(TAG, e);
4323            }
4324            if (observer != null) {
4325                try {
4326                    observer.onRemoveCompleted(null, success);
4327                } catch (RemoteException e) {
4328                    Slog.w(TAG, e);
4329                }
4330            }
4331        });
4332    }
4333
4334    @Override
4335    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4336            final int storageFlags, final IntentSender pi) {
4337        mContext.enforceCallingOrSelfPermission(
4338                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4339        mHandler.post(() -> {
4340            boolean success = false;
4341            try {
4342                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4343                success = true;
4344            } catch (IOException e) {
4345                Slog.w(TAG, e);
4346            }
4347            if (pi != null) {
4348                try {
4349                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4350                } catch (SendIntentException e) {
4351                    Slog.w(TAG, e);
4352                }
4353            }
4354        });
4355    }
4356
4357    /**
4358     * Blocking call to clear various types of cached data across the system
4359     * until the requested bytes are available.
4360     */
4361    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4362        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4363        final File file = storage.findPathForUuid(volumeUuid);
4364        if (file.getUsableSpace() >= bytes) return;
4365
4366        if (ENABLE_FREE_CACHE_V2) {
4367            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4368                    volumeUuid);
4369            final boolean aggressive = (storageFlags
4370                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4371            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4372
4373            // 1. Pre-flight to determine if we have any chance to succeed
4374            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4375            if (internalVolume && (aggressive || SystemProperties
4376                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4377                deletePreloadsFileCache();
4378                if (file.getUsableSpace() >= bytes) return;
4379            }
4380
4381            // 3. Consider parsed APK data (aggressive only)
4382            if (internalVolume && aggressive) {
4383                FileUtils.deleteContents(mCacheDir);
4384                if (file.getUsableSpace() >= bytes) return;
4385            }
4386
4387            // 4. Consider cached app data (above quotas)
4388            try {
4389                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4390                        Installer.FLAG_FREE_CACHE_V2);
4391            } catch (InstallerException ignored) {
4392            }
4393            if (file.getUsableSpace() >= bytes) return;
4394
4395            // 5. Consider shared libraries with refcount=0 and age>min cache period
4396            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4397                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4398                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4399                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4400                return;
4401            }
4402
4403            // 6. Consider dexopt output (aggressive only)
4404            // TODO: Implement
4405
4406            // 7. Consider installed instant apps unused longer than min cache period
4407            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4408                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4409                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4410                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4411                return;
4412            }
4413
4414            // 8. Consider cached app data (below quotas)
4415            try {
4416                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4417                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4418            } catch (InstallerException ignored) {
4419            }
4420            if (file.getUsableSpace() >= bytes) return;
4421
4422            // 9. Consider DropBox entries
4423            // TODO: Implement
4424
4425            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4426            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4427                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4428                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4429                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4430                return;
4431            }
4432        } else {
4433            try {
4434                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4435            } catch (InstallerException ignored) {
4436            }
4437            if (file.getUsableSpace() >= bytes) return;
4438        }
4439
4440        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4441    }
4442
4443    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4444            throws IOException {
4445        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4446        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4447
4448        List<VersionedPackage> packagesToDelete = null;
4449        final long now = System.currentTimeMillis();
4450
4451        synchronized (mPackages) {
4452            final int[] allUsers = sUserManager.getUserIds();
4453            final int libCount = mSharedLibraries.size();
4454            for (int i = 0; i < libCount; i++) {
4455                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4456                if (versionedLib == null) {
4457                    continue;
4458                }
4459                final int versionCount = versionedLib.size();
4460                for (int j = 0; j < versionCount; j++) {
4461                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4462                    // Skip packages that are not static shared libs.
4463                    if (!libInfo.isStatic()) {
4464                        break;
4465                    }
4466                    // Important: We skip static shared libs used for some user since
4467                    // in such a case we need to keep the APK on the device. The check for
4468                    // a lib being used for any user is performed by the uninstall call.
4469                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4470                    // Resolve the package name - we use synthetic package names internally
4471                    final String internalPackageName = resolveInternalPackageNameLPr(
4472                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4473                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4474                    // Skip unused static shared libs cached less than the min period
4475                    // to prevent pruning a lib needed by a subsequently installed package.
4476                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4477                        continue;
4478                    }
4479                    if (packagesToDelete == null) {
4480                        packagesToDelete = new ArrayList<>();
4481                    }
4482                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4483                            declaringPackage.getVersionCode()));
4484                }
4485            }
4486        }
4487
4488        if (packagesToDelete != null) {
4489            final int packageCount = packagesToDelete.size();
4490            for (int i = 0; i < packageCount; i++) {
4491                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4492                // Delete the package synchronously (will fail of the lib used for any user).
4493                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4494                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4495                                == PackageManager.DELETE_SUCCEEDED) {
4496                    if (volume.getUsableSpace() >= neededSpace) {
4497                        return true;
4498                    }
4499                }
4500            }
4501        }
4502
4503        return false;
4504    }
4505
4506    /**
4507     * Update given flags based on encryption status of current user.
4508     */
4509    private int updateFlags(int flags, int userId) {
4510        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4511                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4512            // Caller expressed an explicit opinion about what encryption
4513            // aware/unaware components they want to see, so fall through and
4514            // give them what they want
4515        } else {
4516            // Caller expressed no opinion, so match based on user state
4517            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4518                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4519            } else {
4520                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4521            }
4522        }
4523        return flags;
4524    }
4525
4526    private UserManagerInternal getUserManagerInternal() {
4527        if (mUserManagerInternal == null) {
4528            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4529        }
4530        return mUserManagerInternal;
4531    }
4532
4533    private DeviceIdleController.LocalService getDeviceIdleController() {
4534        if (mDeviceIdleController == null) {
4535            mDeviceIdleController =
4536                    LocalServices.getService(DeviceIdleController.LocalService.class);
4537        }
4538        return mDeviceIdleController;
4539    }
4540
4541    /**
4542     * Update given flags when being used to request {@link PackageInfo}.
4543     */
4544    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4545        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4546        boolean triaged = true;
4547        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4548                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4549            // Caller is asking for component details, so they'd better be
4550            // asking for specific encryption matching behavior, or be triaged
4551            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4552                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4553                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4554                triaged = false;
4555            }
4556        }
4557        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4558                | PackageManager.MATCH_SYSTEM_ONLY
4559                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4560            triaged = false;
4561        }
4562        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4563            mPermissionManager.enforceCrossUserPermission(
4564                    Binder.getCallingUid(), userId, false, false,
4565                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4566                    + Debug.getCallers(5));
4567        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4568                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4569            // If the caller wants all packages and has a restricted profile associated with it,
4570            // then match all users. This is to make sure that launchers that need to access work
4571            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4572            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4573            flags |= PackageManager.MATCH_ANY_USER;
4574        }
4575        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4576            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4577                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4578        }
4579        return updateFlags(flags, userId);
4580    }
4581
4582    /**
4583     * Update given flags when being used to request {@link ApplicationInfo}.
4584     */
4585    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4586        return updateFlagsForPackage(flags, userId, cookie);
4587    }
4588
4589    /**
4590     * Update given flags when being used to request {@link ComponentInfo}.
4591     */
4592    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4593        if (cookie instanceof Intent) {
4594            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4595                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4596            }
4597        }
4598
4599        boolean triaged = true;
4600        // Caller is asking for component details, so they'd better be
4601        // asking for specific encryption matching behavior, or be triaged
4602        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4603                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4604                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4605            triaged = false;
4606        }
4607        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4608            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4609                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4610        }
4611
4612        return updateFlags(flags, userId);
4613    }
4614
4615    /**
4616     * Update given intent when being used to request {@link ResolveInfo}.
4617     */
4618    private Intent updateIntentForResolve(Intent intent) {
4619        if (intent.getSelector() != null) {
4620            intent = intent.getSelector();
4621        }
4622        if (DEBUG_PREFERRED) {
4623            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4624        }
4625        return intent;
4626    }
4627
4628    /**
4629     * Update given flags when being used to request {@link ResolveInfo}.
4630     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4631     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4632     * flag set. However, this flag is only honoured in three circumstances:
4633     * <ul>
4634     * <li>when called from a system process</li>
4635     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4636     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4637     * action and a {@code android.intent.category.BROWSABLE} category</li>
4638     * </ul>
4639     */
4640    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4641        return updateFlagsForResolve(flags, userId, intent, callingUid,
4642                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4643    }
4644    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4645            boolean wantInstantApps) {
4646        return updateFlagsForResolve(flags, userId, intent, callingUid,
4647                wantInstantApps, false /*onlyExposedExplicitly*/);
4648    }
4649    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4650            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4651        // Safe mode means we shouldn't match any third-party components
4652        if (mSafeMode) {
4653            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4654        }
4655        if (getInstantAppPackageName(callingUid) != null) {
4656            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4657            if (onlyExposedExplicitly) {
4658                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4659            }
4660            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4661            flags |= PackageManager.MATCH_INSTANT;
4662        } else {
4663            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4664            final boolean allowMatchInstant =
4665                    (wantInstantApps
4666                            && Intent.ACTION_VIEW.equals(intent.getAction())
4667                            && hasWebURI(intent))
4668                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4669            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4670                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4671            if (!allowMatchInstant) {
4672                flags &= ~PackageManager.MATCH_INSTANT;
4673            }
4674        }
4675        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4676    }
4677
4678    @Override
4679    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4680        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4681    }
4682
4683    /**
4684     * Important: The provided filterCallingUid is used exclusively to filter out activities
4685     * that can be seen based on user state. It's typically the original caller uid prior
4686     * to clearing. Because it can only be provided by trusted code, it's value can be
4687     * trusted and will be used as-is; unlike userId which will be validated by this method.
4688     */
4689    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4690            int filterCallingUid, int userId) {
4691        if (!sUserManager.exists(userId)) return null;
4692        flags = updateFlagsForComponent(flags, userId, component);
4693        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4694                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4695        synchronized (mPackages) {
4696            PackageParser.Activity a = mActivities.mActivities.get(component);
4697
4698            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4699            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4700                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4701                if (ps == null) return null;
4702                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4703                    return null;
4704                }
4705                return PackageParser.generateActivityInfo(
4706                        a, flags, ps.readUserState(userId), userId);
4707            }
4708            if (mResolveComponentName.equals(component)) {
4709                return PackageParser.generateActivityInfo(
4710                        mResolveActivity, flags, new PackageUserState(), userId);
4711            }
4712        }
4713        return null;
4714    }
4715
4716    @Override
4717    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4718            String resolvedType) {
4719        synchronized (mPackages) {
4720            if (component.equals(mResolveComponentName)) {
4721                // The resolver supports EVERYTHING!
4722                return true;
4723            }
4724            final int callingUid = Binder.getCallingUid();
4725            final int callingUserId = UserHandle.getUserId(callingUid);
4726            PackageParser.Activity a = mActivities.mActivities.get(component);
4727            if (a == null) {
4728                return false;
4729            }
4730            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4731            if (ps == null) {
4732                return false;
4733            }
4734            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4735                return false;
4736            }
4737            for (int i=0; i<a.intents.size(); i++) {
4738                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4739                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4740                    return true;
4741                }
4742            }
4743            return false;
4744        }
4745    }
4746
4747    @Override
4748    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4749        if (!sUserManager.exists(userId)) return null;
4750        final int callingUid = Binder.getCallingUid();
4751        flags = updateFlagsForComponent(flags, userId, component);
4752        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4753                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4754        synchronized (mPackages) {
4755            PackageParser.Activity a = mReceivers.mActivities.get(component);
4756            if (DEBUG_PACKAGE_INFO) Log.v(
4757                TAG, "getReceiverInfo " + component + ": " + a);
4758            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4759                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4760                if (ps == null) return null;
4761                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4762                    return null;
4763                }
4764                return PackageParser.generateActivityInfo(
4765                        a, flags, ps.readUserState(userId), userId);
4766            }
4767        }
4768        return null;
4769    }
4770
4771    @Override
4772    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4773            int flags, int userId) {
4774        if (!sUserManager.exists(userId)) return null;
4775        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4776        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4777            return null;
4778        }
4779
4780        flags = updateFlagsForPackage(flags, userId, null);
4781
4782        final boolean canSeeStaticLibraries =
4783                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4784                        == PERMISSION_GRANTED
4785                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4786                        == PERMISSION_GRANTED
4787                || canRequestPackageInstallsInternal(packageName,
4788                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4789                        false  /* throwIfPermNotDeclared*/)
4790                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4791                        == PERMISSION_GRANTED;
4792
4793        synchronized (mPackages) {
4794            List<SharedLibraryInfo> result = null;
4795
4796            final int libCount = mSharedLibraries.size();
4797            for (int i = 0; i < libCount; i++) {
4798                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4799                if (versionedLib == null) {
4800                    continue;
4801                }
4802
4803                final int versionCount = versionedLib.size();
4804                for (int j = 0; j < versionCount; j++) {
4805                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4806                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4807                        break;
4808                    }
4809                    final long identity = Binder.clearCallingIdentity();
4810                    try {
4811                        PackageInfo packageInfo = getPackageInfoVersioned(
4812                                libInfo.getDeclaringPackage(), flags
4813                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4814                        if (packageInfo == null) {
4815                            continue;
4816                        }
4817                    } finally {
4818                        Binder.restoreCallingIdentity(identity);
4819                    }
4820
4821                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4822                            libInfo.getVersion(), libInfo.getType(),
4823                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4824                            flags, userId));
4825
4826                    if (result == null) {
4827                        result = new ArrayList<>();
4828                    }
4829                    result.add(resLibInfo);
4830                }
4831            }
4832
4833            return result != null ? new ParceledListSlice<>(result) : null;
4834        }
4835    }
4836
4837    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4838            SharedLibraryInfo libInfo, int flags, int userId) {
4839        List<VersionedPackage> versionedPackages = null;
4840        final int packageCount = mSettings.mPackages.size();
4841        for (int i = 0; i < packageCount; i++) {
4842            PackageSetting ps = mSettings.mPackages.valueAt(i);
4843
4844            if (ps == null) {
4845                continue;
4846            }
4847
4848            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4849                continue;
4850            }
4851
4852            final String libName = libInfo.getName();
4853            if (libInfo.isStatic()) {
4854                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4855                if (libIdx < 0) {
4856                    continue;
4857                }
4858                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4859                    continue;
4860                }
4861                if (versionedPackages == null) {
4862                    versionedPackages = new ArrayList<>();
4863                }
4864                // If the dependent is a static shared lib, use the public package name
4865                String dependentPackageName = ps.name;
4866                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4867                    dependentPackageName = ps.pkg.manifestPackageName;
4868                }
4869                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4870            } else if (ps.pkg != null) {
4871                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4872                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4873                    if (versionedPackages == null) {
4874                        versionedPackages = new ArrayList<>();
4875                    }
4876                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4877                }
4878            }
4879        }
4880
4881        return versionedPackages;
4882    }
4883
4884    @Override
4885    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4886        if (!sUserManager.exists(userId)) return null;
4887        final int callingUid = Binder.getCallingUid();
4888        flags = updateFlagsForComponent(flags, userId, component);
4889        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4890                false /* requireFullPermission */, false /* checkShell */, "get service info");
4891        synchronized (mPackages) {
4892            PackageParser.Service s = mServices.mServices.get(component);
4893            if (DEBUG_PACKAGE_INFO) Log.v(
4894                TAG, "getServiceInfo " + component + ": " + s);
4895            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4896                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4897                if (ps == null) return null;
4898                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4899                    return null;
4900                }
4901                return PackageParser.generateServiceInfo(
4902                        s, flags, ps.readUserState(userId), userId);
4903            }
4904        }
4905        return null;
4906    }
4907
4908    @Override
4909    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4910        if (!sUserManager.exists(userId)) return null;
4911        final int callingUid = Binder.getCallingUid();
4912        flags = updateFlagsForComponent(flags, userId, component);
4913        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4914                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4915        synchronized (mPackages) {
4916            PackageParser.Provider p = mProviders.mProviders.get(component);
4917            if (DEBUG_PACKAGE_INFO) Log.v(
4918                TAG, "getProviderInfo " + component + ": " + p);
4919            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4920                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4921                if (ps == null) return null;
4922                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4923                    return null;
4924                }
4925                return PackageParser.generateProviderInfo(
4926                        p, flags, ps.readUserState(userId), userId);
4927            }
4928        }
4929        return null;
4930    }
4931
4932    @Override
4933    public String[] getSystemSharedLibraryNames() {
4934        // allow instant applications
4935        synchronized (mPackages) {
4936            Set<String> libs = null;
4937            final int libCount = mSharedLibraries.size();
4938            for (int i = 0; i < libCount; i++) {
4939                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4940                if (versionedLib == null) {
4941                    continue;
4942                }
4943                final int versionCount = versionedLib.size();
4944                for (int j = 0; j < versionCount; j++) {
4945                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4946                    if (!libEntry.info.isStatic()) {
4947                        if (libs == null) {
4948                            libs = new ArraySet<>();
4949                        }
4950                        libs.add(libEntry.info.getName());
4951                        break;
4952                    }
4953                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4954                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4955                            UserHandle.getUserId(Binder.getCallingUid()),
4956                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4957                        if (libs == null) {
4958                            libs = new ArraySet<>();
4959                        }
4960                        libs.add(libEntry.info.getName());
4961                        break;
4962                    }
4963                }
4964            }
4965
4966            if (libs != null) {
4967                String[] libsArray = new String[libs.size()];
4968                libs.toArray(libsArray);
4969                return libsArray;
4970            }
4971
4972            return null;
4973        }
4974    }
4975
4976    @Override
4977    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4978        // allow instant applications
4979        synchronized (mPackages) {
4980            return mServicesSystemSharedLibraryPackageName;
4981        }
4982    }
4983
4984    @Override
4985    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4986        // allow instant applications
4987        synchronized (mPackages) {
4988            return mSharedSystemSharedLibraryPackageName;
4989        }
4990    }
4991
4992    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4993        for (int i = userList.length - 1; i >= 0; --i) {
4994            final int userId = userList[i];
4995            // don't add instant app to the list of updates
4996            if (pkgSetting.getInstantApp(userId)) {
4997                continue;
4998            }
4999            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5000            if (changedPackages == null) {
5001                changedPackages = new SparseArray<>();
5002                mChangedPackages.put(userId, changedPackages);
5003            }
5004            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5005            if (sequenceNumbers == null) {
5006                sequenceNumbers = new HashMap<>();
5007                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5008            }
5009            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5010            if (sequenceNumber != null) {
5011                changedPackages.remove(sequenceNumber);
5012            }
5013            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5014            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5015        }
5016        mChangedPackagesSequenceNumber++;
5017    }
5018
5019    @Override
5020    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5021        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5022            return null;
5023        }
5024        synchronized (mPackages) {
5025            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5026                return null;
5027            }
5028            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5029            if (changedPackages == null) {
5030                return null;
5031            }
5032            final List<String> packageNames =
5033                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5034            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5035                final String packageName = changedPackages.get(i);
5036                if (packageName != null) {
5037                    packageNames.add(packageName);
5038                }
5039            }
5040            return packageNames.isEmpty()
5041                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5042        }
5043    }
5044
5045    @Override
5046    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5047        // allow instant applications
5048        ArrayList<FeatureInfo> res;
5049        synchronized (mAvailableFeatures) {
5050            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5051            res.addAll(mAvailableFeatures.values());
5052        }
5053        final FeatureInfo fi = new FeatureInfo();
5054        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5055                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5056        res.add(fi);
5057
5058        return new ParceledListSlice<>(res);
5059    }
5060
5061    @Override
5062    public boolean hasSystemFeature(String name, int version) {
5063        // allow instant applications
5064        synchronized (mAvailableFeatures) {
5065            final FeatureInfo feat = mAvailableFeatures.get(name);
5066            if (feat == null) {
5067                return false;
5068            } else {
5069                return feat.version >= version;
5070            }
5071        }
5072    }
5073
5074    @Override
5075    public int checkPermission(String permName, String pkgName, int userId) {
5076        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5077    }
5078
5079    @Override
5080    public int checkUidPermission(String permName, int uid) {
5081        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5082    }
5083
5084    @Override
5085    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5086        if (UserHandle.getCallingUserId() != userId) {
5087            mContext.enforceCallingPermission(
5088                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5089                    "isPermissionRevokedByPolicy for user " + userId);
5090        }
5091
5092        if (checkPermission(permission, packageName, userId)
5093                == PackageManager.PERMISSION_GRANTED) {
5094            return false;
5095        }
5096
5097        final int callingUid = Binder.getCallingUid();
5098        if (getInstantAppPackageName(callingUid) != null) {
5099            if (!isCallerSameApp(packageName, callingUid)) {
5100                return false;
5101            }
5102        } else {
5103            if (isInstantApp(packageName, userId)) {
5104                return false;
5105            }
5106        }
5107
5108        final long identity = Binder.clearCallingIdentity();
5109        try {
5110            final int flags = getPermissionFlags(permission, packageName, userId);
5111            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5112        } finally {
5113            Binder.restoreCallingIdentity(identity);
5114        }
5115    }
5116
5117    @Override
5118    public String getPermissionControllerPackageName() {
5119        synchronized (mPackages) {
5120            return mRequiredInstallerPackage;
5121        }
5122    }
5123
5124    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5125        return mPermissionManager.addDynamicPermission(
5126                info, async, getCallingUid(), new PermissionCallback() {
5127                    @Override
5128                    public void onPermissionChanged() {
5129                        if (!async) {
5130                            mSettings.writeLPr();
5131                        } else {
5132                            scheduleWriteSettingsLocked();
5133                        }
5134                    }
5135                });
5136    }
5137
5138    @Override
5139    public boolean addPermission(PermissionInfo info) {
5140        synchronized (mPackages) {
5141            return addDynamicPermission(info, false);
5142        }
5143    }
5144
5145    @Override
5146    public boolean addPermissionAsync(PermissionInfo info) {
5147        synchronized (mPackages) {
5148            return addDynamicPermission(info, true);
5149        }
5150    }
5151
5152    @Override
5153    public void removePermission(String permName) {
5154        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5155    }
5156
5157    @Override
5158    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5159        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5160                getCallingUid(), userId, mPermissionCallback);
5161    }
5162
5163    @Override
5164    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5165        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5166                getCallingUid(), userId, mPermissionCallback);
5167    }
5168
5169    @Override
5170    public void resetRuntimePermissions() {
5171        mContext.enforceCallingOrSelfPermission(
5172                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5173                "revokeRuntimePermission");
5174
5175        int callingUid = Binder.getCallingUid();
5176        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5177            mContext.enforceCallingOrSelfPermission(
5178                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5179                    "resetRuntimePermissions");
5180        }
5181
5182        synchronized (mPackages) {
5183            mPermissionManager.updateAllPermissions(
5184                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5185                    mPermissionCallback);
5186            for (int userId : UserManagerService.getInstance().getUserIds()) {
5187                final int packageCount = mPackages.size();
5188                for (int i = 0; i < packageCount; i++) {
5189                    PackageParser.Package pkg = mPackages.valueAt(i);
5190                    if (!(pkg.mExtras instanceof PackageSetting)) {
5191                        continue;
5192                    }
5193                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5194                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5195                }
5196            }
5197        }
5198    }
5199
5200    @Override
5201    public int getPermissionFlags(String permName, String packageName, int userId) {
5202        return mPermissionManager.getPermissionFlags(
5203                permName, packageName, getCallingUid(), userId);
5204    }
5205
5206    @Override
5207    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5208            int flagValues, int userId) {
5209        mPermissionManager.updatePermissionFlags(
5210                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5211                mPermissionCallback);
5212    }
5213
5214    /**
5215     * Update the permission flags for all packages and runtime permissions of a user in order
5216     * to allow device or profile owner to remove POLICY_FIXED.
5217     */
5218    @Override
5219    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5220        synchronized (mPackages) {
5221            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5222                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5223                    mPermissionCallback);
5224            if (changed) {
5225                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5226            }
5227        }
5228    }
5229
5230    @Override
5231    public boolean shouldShowRequestPermissionRationale(String permissionName,
5232            String packageName, int userId) {
5233        if (UserHandle.getCallingUserId() != userId) {
5234            mContext.enforceCallingPermission(
5235                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5236                    "canShowRequestPermissionRationale for user " + userId);
5237        }
5238
5239        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5240        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5241            return false;
5242        }
5243
5244        if (checkPermission(permissionName, packageName, userId)
5245                == PackageManager.PERMISSION_GRANTED) {
5246            return false;
5247        }
5248
5249        final int flags;
5250
5251        final long identity = Binder.clearCallingIdentity();
5252        try {
5253            flags = getPermissionFlags(permissionName,
5254                    packageName, userId);
5255        } finally {
5256            Binder.restoreCallingIdentity(identity);
5257        }
5258
5259        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5260                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5261                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5262
5263        if ((flags & fixedFlags) != 0) {
5264            return false;
5265        }
5266
5267        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5268    }
5269
5270    @Override
5271    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5272        mContext.enforceCallingOrSelfPermission(
5273                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5274                "addOnPermissionsChangeListener");
5275
5276        synchronized (mPackages) {
5277            mOnPermissionChangeListeners.addListenerLocked(listener);
5278        }
5279    }
5280
5281    @Override
5282    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5283        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5284            throw new SecurityException("Instant applications don't have access to this method");
5285        }
5286        synchronized (mPackages) {
5287            mOnPermissionChangeListeners.removeListenerLocked(listener);
5288        }
5289    }
5290
5291    @Override
5292    public boolean isProtectedBroadcast(String actionName) {
5293        // allow instant applications
5294        synchronized (mProtectedBroadcasts) {
5295            if (mProtectedBroadcasts.contains(actionName)) {
5296                return true;
5297            } else if (actionName != null) {
5298                // TODO: remove these terrible hacks
5299                if (actionName.startsWith("android.net.netmon.lingerExpired")
5300                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5301                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5302                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5303                    return true;
5304                }
5305            }
5306        }
5307        return false;
5308    }
5309
5310    @Override
5311    public int checkSignatures(String pkg1, String pkg2) {
5312        synchronized (mPackages) {
5313            final PackageParser.Package p1 = mPackages.get(pkg1);
5314            final PackageParser.Package p2 = mPackages.get(pkg2);
5315            if (p1 == null || p1.mExtras == null
5316                    || p2 == null || p2.mExtras == null) {
5317                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5318            }
5319            final int callingUid = Binder.getCallingUid();
5320            final int callingUserId = UserHandle.getUserId(callingUid);
5321            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5322            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5323            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5324                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5325                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5326            }
5327            return compareSignatures(p1.mSignatures, p2.mSignatures);
5328        }
5329    }
5330
5331    @Override
5332    public int checkUidSignatures(int uid1, int uid2) {
5333        final int callingUid = Binder.getCallingUid();
5334        final int callingUserId = UserHandle.getUserId(callingUid);
5335        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5336        // Map to base uids.
5337        uid1 = UserHandle.getAppId(uid1);
5338        uid2 = UserHandle.getAppId(uid2);
5339        // reader
5340        synchronized (mPackages) {
5341            Signature[] s1;
5342            Signature[] s2;
5343            Object obj = mSettings.getUserIdLPr(uid1);
5344            if (obj != null) {
5345                if (obj instanceof SharedUserSetting) {
5346                    if (isCallerInstantApp) {
5347                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5348                    }
5349                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5350                } else if (obj instanceof PackageSetting) {
5351                    final PackageSetting ps = (PackageSetting) obj;
5352                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5353                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5354                    }
5355                    s1 = ps.signatures.mSignatures;
5356                } else {
5357                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5358                }
5359            } else {
5360                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5361            }
5362            obj = mSettings.getUserIdLPr(uid2);
5363            if (obj != null) {
5364                if (obj instanceof SharedUserSetting) {
5365                    if (isCallerInstantApp) {
5366                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5367                    }
5368                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5369                } else if (obj instanceof PackageSetting) {
5370                    final PackageSetting ps = (PackageSetting) obj;
5371                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5372                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5373                    }
5374                    s2 = ps.signatures.mSignatures;
5375                } else {
5376                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5377                }
5378            } else {
5379                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5380            }
5381            return compareSignatures(s1, s2);
5382        }
5383    }
5384
5385    /**
5386     * This method should typically only be used when granting or revoking
5387     * permissions, since the app may immediately restart after this call.
5388     * <p>
5389     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5390     * guard your work against the app being relaunched.
5391     */
5392    private void killUid(int appId, int userId, String reason) {
5393        final long identity = Binder.clearCallingIdentity();
5394        try {
5395            IActivityManager am = ActivityManager.getService();
5396            if (am != null) {
5397                try {
5398                    am.killUid(appId, userId, reason);
5399                } catch (RemoteException e) {
5400                    /* ignore - same process */
5401                }
5402            }
5403        } finally {
5404            Binder.restoreCallingIdentity(identity);
5405        }
5406    }
5407
5408    /**
5409     * If the database version for this type of package (internal storage or
5410     * external storage) is less than the version where package signatures
5411     * were updated, return true.
5412     */
5413    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5414        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5415        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5416    }
5417
5418    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5419        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5420        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5421    }
5422
5423    @Override
5424    public List<String> getAllPackages() {
5425        final int callingUid = Binder.getCallingUid();
5426        final int callingUserId = UserHandle.getUserId(callingUid);
5427        synchronized (mPackages) {
5428            if (canViewInstantApps(callingUid, callingUserId)) {
5429                return new ArrayList<String>(mPackages.keySet());
5430            }
5431            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5432            final List<String> result = new ArrayList<>();
5433            if (instantAppPkgName != null) {
5434                // caller is an instant application; filter unexposed applications
5435                for (PackageParser.Package pkg : mPackages.values()) {
5436                    if (!pkg.visibleToInstantApps) {
5437                        continue;
5438                    }
5439                    result.add(pkg.packageName);
5440                }
5441            } else {
5442                // caller is a normal application; filter instant applications
5443                for (PackageParser.Package pkg : mPackages.values()) {
5444                    final PackageSetting ps =
5445                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5446                    if (ps != null
5447                            && ps.getInstantApp(callingUserId)
5448                            && !mInstantAppRegistry.isInstantAccessGranted(
5449                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5450                        continue;
5451                    }
5452                    result.add(pkg.packageName);
5453                }
5454            }
5455            return result;
5456        }
5457    }
5458
5459    @Override
5460    public String[] getPackagesForUid(int uid) {
5461        final int callingUid = Binder.getCallingUid();
5462        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5463        final int userId = UserHandle.getUserId(uid);
5464        uid = UserHandle.getAppId(uid);
5465        // reader
5466        synchronized (mPackages) {
5467            Object obj = mSettings.getUserIdLPr(uid);
5468            if (obj instanceof SharedUserSetting) {
5469                if (isCallerInstantApp) {
5470                    return null;
5471                }
5472                final SharedUserSetting sus = (SharedUserSetting) obj;
5473                final int N = sus.packages.size();
5474                String[] res = new String[N];
5475                final Iterator<PackageSetting> it = sus.packages.iterator();
5476                int i = 0;
5477                while (it.hasNext()) {
5478                    PackageSetting ps = it.next();
5479                    if (ps.getInstalled(userId)) {
5480                        res[i++] = ps.name;
5481                    } else {
5482                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5483                    }
5484                }
5485                return res;
5486            } else if (obj instanceof PackageSetting) {
5487                final PackageSetting ps = (PackageSetting) obj;
5488                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5489                    return new String[]{ps.name};
5490                }
5491            }
5492        }
5493        return null;
5494    }
5495
5496    @Override
5497    public String getNameForUid(int uid) {
5498        final int callingUid = Binder.getCallingUid();
5499        if (getInstantAppPackageName(callingUid) != null) {
5500            return null;
5501        }
5502        synchronized (mPackages) {
5503            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5504            if (obj instanceof SharedUserSetting) {
5505                final SharedUserSetting sus = (SharedUserSetting) obj;
5506                return sus.name + ":" + sus.userId;
5507            } else if (obj instanceof PackageSetting) {
5508                final PackageSetting ps = (PackageSetting) obj;
5509                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5510                    return null;
5511                }
5512                return ps.name;
5513            }
5514            return null;
5515        }
5516    }
5517
5518    @Override
5519    public String[] getNamesForUids(int[] uids) {
5520        if (uids == null || uids.length == 0) {
5521            return null;
5522        }
5523        final int callingUid = Binder.getCallingUid();
5524        if (getInstantAppPackageName(callingUid) != null) {
5525            return null;
5526        }
5527        final String[] names = new String[uids.length];
5528        synchronized (mPackages) {
5529            for (int i = uids.length - 1; i >= 0; i--) {
5530                final int uid = uids[i];
5531                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5532                if (obj instanceof SharedUserSetting) {
5533                    final SharedUserSetting sus = (SharedUserSetting) obj;
5534                    names[i] = "shared:" + sus.name;
5535                } else if (obj instanceof PackageSetting) {
5536                    final PackageSetting ps = (PackageSetting) obj;
5537                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5538                        names[i] = null;
5539                    } else {
5540                        names[i] = ps.name;
5541                    }
5542                } else {
5543                    names[i] = null;
5544                }
5545            }
5546        }
5547        return names;
5548    }
5549
5550    @Override
5551    public int getUidForSharedUser(String sharedUserName) {
5552        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5553            return -1;
5554        }
5555        if (sharedUserName == null) {
5556            return -1;
5557        }
5558        // reader
5559        synchronized (mPackages) {
5560            SharedUserSetting suid;
5561            try {
5562                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5563                if (suid != null) {
5564                    return suid.userId;
5565                }
5566            } catch (PackageManagerException ignore) {
5567                // can't happen, but, still need to catch it
5568            }
5569            return -1;
5570        }
5571    }
5572
5573    @Override
5574    public int getFlagsForUid(int uid) {
5575        final int callingUid = Binder.getCallingUid();
5576        if (getInstantAppPackageName(callingUid) != null) {
5577            return 0;
5578        }
5579        synchronized (mPackages) {
5580            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5581            if (obj instanceof SharedUserSetting) {
5582                final SharedUserSetting sus = (SharedUserSetting) obj;
5583                return sus.pkgFlags;
5584            } else if (obj instanceof PackageSetting) {
5585                final PackageSetting ps = (PackageSetting) obj;
5586                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5587                    return 0;
5588                }
5589                return ps.pkgFlags;
5590            }
5591        }
5592        return 0;
5593    }
5594
5595    @Override
5596    public int getPrivateFlagsForUid(int uid) {
5597        final int callingUid = Binder.getCallingUid();
5598        if (getInstantAppPackageName(callingUid) != null) {
5599            return 0;
5600        }
5601        synchronized (mPackages) {
5602            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5603            if (obj instanceof SharedUserSetting) {
5604                final SharedUserSetting sus = (SharedUserSetting) obj;
5605                return sus.pkgPrivateFlags;
5606            } else if (obj instanceof PackageSetting) {
5607                final PackageSetting ps = (PackageSetting) obj;
5608                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5609                    return 0;
5610                }
5611                return ps.pkgPrivateFlags;
5612            }
5613        }
5614        return 0;
5615    }
5616
5617    @Override
5618    public boolean isUidPrivileged(int uid) {
5619        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5620            return false;
5621        }
5622        uid = UserHandle.getAppId(uid);
5623        // reader
5624        synchronized (mPackages) {
5625            Object obj = mSettings.getUserIdLPr(uid);
5626            if (obj instanceof SharedUserSetting) {
5627                final SharedUserSetting sus = (SharedUserSetting) obj;
5628                final Iterator<PackageSetting> it = sus.packages.iterator();
5629                while (it.hasNext()) {
5630                    if (it.next().isPrivileged()) {
5631                        return true;
5632                    }
5633                }
5634            } else if (obj instanceof PackageSetting) {
5635                final PackageSetting ps = (PackageSetting) obj;
5636                return ps.isPrivileged();
5637            }
5638        }
5639        return false;
5640    }
5641
5642    @Override
5643    public String[] getAppOpPermissionPackages(String permName) {
5644        return mPermissionManager.getAppOpPermissionPackages(permName);
5645    }
5646
5647    @Override
5648    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5649            int flags, int userId) {
5650        return resolveIntentInternal(
5651                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5652    }
5653
5654    /**
5655     * Normally instant apps can only be resolved when they're visible to the caller.
5656     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5657     * since we need to allow the system to start any installed application.
5658     */
5659    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5660            int flags, int userId, boolean resolveForStart) {
5661        try {
5662            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5663
5664            if (!sUserManager.exists(userId)) return null;
5665            final int callingUid = Binder.getCallingUid();
5666            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5667            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5668                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5669
5670            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5671            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5672                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5673            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5674
5675            final ResolveInfo bestChoice =
5676                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5677            return bestChoice;
5678        } finally {
5679            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5680        }
5681    }
5682
5683    @Override
5684    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5685        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5686            throw new SecurityException(
5687                    "findPersistentPreferredActivity can only be run by the system");
5688        }
5689        if (!sUserManager.exists(userId)) {
5690            return null;
5691        }
5692        final int callingUid = Binder.getCallingUid();
5693        intent = updateIntentForResolve(intent);
5694        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5695        final int flags = updateFlagsForResolve(
5696                0, userId, intent, callingUid, false /*includeInstantApps*/);
5697        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5698                userId);
5699        synchronized (mPackages) {
5700            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5701                    userId);
5702        }
5703    }
5704
5705    @Override
5706    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5707            IntentFilter filter, int match, ComponentName activity) {
5708        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5709            return;
5710        }
5711        final int userId = UserHandle.getCallingUserId();
5712        if (DEBUG_PREFERRED) {
5713            Log.v(TAG, "setLastChosenActivity intent=" + intent
5714                + " resolvedType=" + resolvedType
5715                + " flags=" + flags
5716                + " filter=" + filter
5717                + " match=" + match
5718                + " activity=" + activity);
5719            filter.dump(new PrintStreamPrinter(System.out), "    ");
5720        }
5721        intent.setComponent(null);
5722        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5723                userId);
5724        // Find any earlier preferred or last chosen entries and nuke them
5725        findPreferredActivity(intent, resolvedType,
5726                flags, query, 0, false, true, false, userId);
5727        // Add the new activity as the last chosen for this filter
5728        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5729                "Setting last chosen");
5730    }
5731
5732    @Override
5733    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5734        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5735            return null;
5736        }
5737        final int userId = UserHandle.getCallingUserId();
5738        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5739        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5740                userId);
5741        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5742                false, false, false, userId);
5743    }
5744
5745    /**
5746     * Returns whether or not instant apps have been disabled remotely.
5747     */
5748    private boolean isEphemeralDisabled() {
5749        return mEphemeralAppsDisabled;
5750    }
5751
5752    private boolean isInstantAppAllowed(
5753            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5754            boolean skipPackageCheck) {
5755        if (mInstantAppResolverConnection == null) {
5756            return false;
5757        }
5758        if (mInstantAppInstallerActivity == null) {
5759            return false;
5760        }
5761        if (intent.getComponent() != null) {
5762            return false;
5763        }
5764        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5765            return false;
5766        }
5767        if (!skipPackageCheck && intent.getPackage() != null) {
5768            return false;
5769        }
5770        final boolean isWebUri = hasWebURI(intent);
5771        if (!isWebUri || intent.getData().getHost() == null) {
5772            return false;
5773        }
5774        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5775        // Or if there's already an ephemeral app installed that handles the action
5776        synchronized (mPackages) {
5777            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5778            for (int n = 0; n < count; n++) {
5779                final ResolveInfo info = resolvedActivities.get(n);
5780                final String packageName = info.activityInfo.packageName;
5781                final PackageSetting ps = mSettings.mPackages.get(packageName);
5782                if (ps != null) {
5783                    // only check domain verification status if the app is not a browser
5784                    if (!info.handleAllWebDataURI) {
5785                        // Try to get the status from User settings first
5786                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5787                        final int status = (int) (packedStatus >> 32);
5788                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5789                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5790                            if (DEBUG_EPHEMERAL) {
5791                                Slog.v(TAG, "DENY instant app;"
5792                                    + " pkg: " + packageName + ", status: " + status);
5793                            }
5794                            return false;
5795                        }
5796                    }
5797                    if (ps.getInstantApp(userId)) {
5798                        if (DEBUG_EPHEMERAL) {
5799                            Slog.v(TAG, "DENY instant app installed;"
5800                                    + " pkg: " + packageName);
5801                        }
5802                        return false;
5803                    }
5804                }
5805            }
5806        }
5807        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5808        return true;
5809    }
5810
5811    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5812            Intent origIntent, String resolvedType, String callingPackage,
5813            Bundle verificationBundle, int userId) {
5814        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5815                new InstantAppRequest(responseObj, origIntent, resolvedType,
5816                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5817        mHandler.sendMessage(msg);
5818    }
5819
5820    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5821            int flags, List<ResolveInfo> query, int userId) {
5822        if (query != null) {
5823            final int N = query.size();
5824            if (N == 1) {
5825                return query.get(0);
5826            } else if (N > 1) {
5827                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5828                // If there is more than one activity with the same priority,
5829                // then let the user decide between them.
5830                ResolveInfo r0 = query.get(0);
5831                ResolveInfo r1 = query.get(1);
5832                if (DEBUG_INTENT_MATCHING || debug) {
5833                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5834                            + r1.activityInfo.name + "=" + r1.priority);
5835                }
5836                // If the first activity has a higher priority, or a different
5837                // default, then it is always desirable to pick it.
5838                if (r0.priority != r1.priority
5839                        || r0.preferredOrder != r1.preferredOrder
5840                        || r0.isDefault != r1.isDefault) {
5841                    return query.get(0);
5842                }
5843                // If we have saved a preference for a preferred activity for
5844                // this Intent, use that.
5845                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5846                        flags, query, r0.priority, true, false, debug, userId);
5847                if (ri != null) {
5848                    return ri;
5849                }
5850                // If we have an ephemeral app, use it
5851                for (int i = 0; i < N; i++) {
5852                    ri = query.get(i);
5853                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5854                        final String packageName = ri.activityInfo.packageName;
5855                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5856                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5857                        final int status = (int)(packedStatus >> 32);
5858                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5859                            return ri;
5860                        }
5861                    }
5862                }
5863                ri = new ResolveInfo(mResolveInfo);
5864                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5865                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5866                // If all of the options come from the same package, show the application's
5867                // label and icon instead of the generic resolver's.
5868                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5869                // and then throw away the ResolveInfo itself, meaning that the caller loses
5870                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5871                // a fallback for this case; we only set the target package's resources on
5872                // the ResolveInfo, not the ActivityInfo.
5873                final String intentPackage = intent.getPackage();
5874                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5875                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5876                    ri.resolvePackageName = intentPackage;
5877                    if (userNeedsBadging(userId)) {
5878                        ri.noResourceId = true;
5879                    } else {
5880                        ri.icon = appi.icon;
5881                    }
5882                    ri.iconResourceId = appi.icon;
5883                    ri.labelRes = appi.labelRes;
5884                }
5885                ri.activityInfo.applicationInfo = new ApplicationInfo(
5886                        ri.activityInfo.applicationInfo);
5887                if (userId != 0) {
5888                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5889                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5890                }
5891                // Make sure that the resolver is displayable in car mode
5892                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5893                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5894                return ri;
5895            }
5896        }
5897        return null;
5898    }
5899
5900    /**
5901     * Return true if the given list is not empty and all of its contents have
5902     * an activityInfo with the given package name.
5903     */
5904    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5905        if (ArrayUtils.isEmpty(list)) {
5906            return false;
5907        }
5908        for (int i = 0, N = list.size(); i < N; i++) {
5909            final ResolveInfo ri = list.get(i);
5910            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5911            if (ai == null || !packageName.equals(ai.packageName)) {
5912                return false;
5913            }
5914        }
5915        return true;
5916    }
5917
5918    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5919            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5920        final int N = query.size();
5921        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5922                .get(userId);
5923        // Get the list of persistent preferred activities that handle the intent
5924        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5925        List<PersistentPreferredActivity> pprefs = ppir != null
5926                ? ppir.queryIntent(intent, resolvedType,
5927                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5928                        userId)
5929                : null;
5930        if (pprefs != null && pprefs.size() > 0) {
5931            final int M = pprefs.size();
5932            for (int i=0; i<M; i++) {
5933                final PersistentPreferredActivity ppa = pprefs.get(i);
5934                if (DEBUG_PREFERRED || debug) {
5935                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5936                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5937                            + "\n  component=" + ppa.mComponent);
5938                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5939                }
5940                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5941                        flags | MATCH_DISABLED_COMPONENTS, userId);
5942                if (DEBUG_PREFERRED || debug) {
5943                    Slog.v(TAG, "Found persistent preferred activity:");
5944                    if (ai != null) {
5945                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5946                    } else {
5947                        Slog.v(TAG, "  null");
5948                    }
5949                }
5950                if (ai == null) {
5951                    // This previously registered persistent preferred activity
5952                    // component is no longer known. Ignore it and do NOT remove it.
5953                    continue;
5954                }
5955                for (int j=0; j<N; j++) {
5956                    final ResolveInfo ri = query.get(j);
5957                    if (!ri.activityInfo.applicationInfo.packageName
5958                            .equals(ai.applicationInfo.packageName)) {
5959                        continue;
5960                    }
5961                    if (!ri.activityInfo.name.equals(ai.name)) {
5962                        continue;
5963                    }
5964                    //  Found a persistent preference that can handle the intent.
5965                    if (DEBUG_PREFERRED || debug) {
5966                        Slog.v(TAG, "Returning persistent preferred activity: " +
5967                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5968                    }
5969                    return ri;
5970                }
5971            }
5972        }
5973        return null;
5974    }
5975
5976    // TODO: handle preferred activities missing while user has amnesia
5977    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5978            List<ResolveInfo> query, int priority, boolean always,
5979            boolean removeMatches, boolean debug, int userId) {
5980        if (!sUserManager.exists(userId)) return null;
5981        final int callingUid = Binder.getCallingUid();
5982        flags = updateFlagsForResolve(
5983                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5984        intent = updateIntentForResolve(intent);
5985        // writer
5986        synchronized (mPackages) {
5987            // Try to find a matching persistent preferred activity.
5988            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5989                    debug, userId);
5990
5991            // If a persistent preferred activity matched, use it.
5992            if (pri != null) {
5993                return pri;
5994            }
5995
5996            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5997            // Get the list of preferred activities that handle the intent
5998            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5999            List<PreferredActivity> prefs = pir != null
6000                    ? pir.queryIntent(intent, resolvedType,
6001                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6002                            userId)
6003                    : null;
6004            if (prefs != null && prefs.size() > 0) {
6005                boolean changed = false;
6006                try {
6007                    // First figure out how good the original match set is.
6008                    // We will only allow preferred activities that came
6009                    // from the same match quality.
6010                    int match = 0;
6011
6012                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6013
6014                    final int N = query.size();
6015                    for (int j=0; j<N; j++) {
6016                        final ResolveInfo ri = query.get(j);
6017                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6018                                + ": 0x" + Integer.toHexString(match));
6019                        if (ri.match > match) {
6020                            match = ri.match;
6021                        }
6022                    }
6023
6024                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6025                            + Integer.toHexString(match));
6026
6027                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6028                    final int M = prefs.size();
6029                    for (int i=0; i<M; i++) {
6030                        final PreferredActivity pa = prefs.get(i);
6031                        if (DEBUG_PREFERRED || debug) {
6032                            Slog.v(TAG, "Checking PreferredActivity ds="
6033                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6034                                    + "\n  component=" + pa.mPref.mComponent);
6035                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6036                        }
6037                        if (pa.mPref.mMatch != match) {
6038                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6039                                    + Integer.toHexString(pa.mPref.mMatch));
6040                            continue;
6041                        }
6042                        // If it's not an "always" type preferred activity and that's what we're
6043                        // looking for, skip it.
6044                        if (always && !pa.mPref.mAlways) {
6045                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6046                            continue;
6047                        }
6048                        final ActivityInfo ai = getActivityInfo(
6049                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6050                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6051                                userId);
6052                        if (DEBUG_PREFERRED || debug) {
6053                            Slog.v(TAG, "Found preferred activity:");
6054                            if (ai != null) {
6055                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6056                            } else {
6057                                Slog.v(TAG, "  null");
6058                            }
6059                        }
6060                        if (ai == null) {
6061                            // This previously registered preferred activity
6062                            // component is no longer known.  Most likely an update
6063                            // to the app was installed and in the new version this
6064                            // component no longer exists.  Clean it up by removing
6065                            // it from the preferred activities list, and skip it.
6066                            Slog.w(TAG, "Removing dangling preferred activity: "
6067                                    + pa.mPref.mComponent);
6068                            pir.removeFilter(pa);
6069                            changed = true;
6070                            continue;
6071                        }
6072                        for (int j=0; j<N; j++) {
6073                            final ResolveInfo ri = query.get(j);
6074                            if (!ri.activityInfo.applicationInfo.packageName
6075                                    .equals(ai.applicationInfo.packageName)) {
6076                                continue;
6077                            }
6078                            if (!ri.activityInfo.name.equals(ai.name)) {
6079                                continue;
6080                            }
6081
6082                            if (removeMatches) {
6083                                pir.removeFilter(pa);
6084                                changed = true;
6085                                if (DEBUG_PREFERRED) {
6086                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6087                                }
6088                                break;
6089                            }
6090
6091                            // Okay we found a previously set preferred or last chosen app.
6092                            // If the result set is different from when this
6093                            // was created, and is not a subset of the preferred set, we need to
6094                            // clear it and re-ask the user their preference, if we're looking for
6095                            // an "always" type entry.
6096                            if (always && !pa.mPref.sameSet(query)) {
6097                                if (pa.mPref.isSuperset(query)) {
6098                                    // some components of the set are no longer present in
6099                                    // the query, but the preferred activity can still be reused
6100                                    if (DEBUG_PREFERRED) {
6101                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6102                                                + " still valid as only non-preferred components"
6103                                                + " were removed for " + intent + " type "
6104                                                + resolvedType);
6105                                    }
6106                                    // remove obsolete components and re-add the up-to-date filter
6107                                    PreferredActivity freshPa = new PreferredActivity(pa,
6108                                            pa.mPref.mMatch,
6109                                            pa.mPref.discardObsoleteComponents(query),
6110                                            pa.mPref.mComponent,
6111                                            pa.mPref.mAlways);
6112                                    pir.removeFilter(pa);
6113                                    pir.addFilter(freshPa);
6114                                    changed = true;
6115                                } else {
6116                                    Slog.i(TAG,
6117                                            "Result set changed, dropping preferred activity for "
6118                                                    + intent + " type " + resolvedType);
6119                                    if (DEBUG_PREFERRED) {
6120                                        Slog.v(TAG, "Removing preferred activity since set changed "
6121                                                + pa.mPref.mComponent);
6122                                    }
6123                                    pir.removeFilter(pa);
6124                                    // Re-add the filter as a "last chosen" entry (!always)
6125                                    PreferredActivity lastChosen = new PreferredActivity(
6126                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6127                                    pir.addFilter(lastChosen);
6128                                    changed = true;
6129                                    return null;
6130                                }
6131                            }
6132
6133                            // Yay! Either the set matched or we're looking for the last chosen
6134                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6135                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6136                            return ri;
6137                        }
6138                    }
6139                } finally {
6140                    if (changed) {
6141                        if (DEBUG_PREFERRED) {
6142                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6143                        }
6144                        scheduleWritePackageRestrictionsLocked(userId);
6145                    }
6146                }
6147            }
6148        }
6149        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6150        return null;
6151    }
6152
6153    /*
6154     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6155     */
6156    @Override
6157    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6158            int targetUserId) {
6159        mContext.enforceCallingOrSelfPermission(
6160                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6161        List<CrossProfileIntentFilter> matches =
6162                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6163        if (matches != null) {
6164            int size = matches.size();
6165            for (int i = 0; i < size; i++) {
6166                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6167            }
6168        }
6169        if (hasWebURI(intent)) {
6170            // cross-profile app linking works only towards the parent.
6171            final int callingUid = Binder.getCallingUid();
6172            final UserInfo parent = getProfileParent(sourceUserId);
6173            synchronized(mPackages) {
6174                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6175                        false /*includeInstantApps*/);
6176                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6177                        intent, resolvedType, flags, sourceUserId, parent.id);
6178                return xpDomainInfo != null;
6179            }
6180        }
6181        return false;
6182    }
6183
6184    private UserInfo getProfileParent(int userId) {
6185        final long identity = Binder.clearCallingIdentity();
6186        try {
6187            return sUserManager.getProfileParent(userId);
6188        } finally {
6189            Binder.restoreCallingIdentity(identity);
6190        }
6191    }
6192
6193    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6194            String resolvedType, int userId) {
6195        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6196        if (resolver != null) {
6197            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6198        }
6199        return null;
6200    }
6201
6202    @Override
6203    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6204            String resolvedType, int flags, int userId) {
6205        try {
6206            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6207
6208            return new ParceledListSlice<>(
6209                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6210        } finally {
6211            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6212        }
6213    }
6214
6215    /**
6216     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6217     * instant, returns {@code null}.
6218     */
6219    private String getInstantAppPackageName(int callingUid) {
6220        synchronized (mPackages) {
6221            // If the caller is an isolated app use the owner's uid for the lookup.
6222            if (Process.isIsolated(callingUid)) {
6223                callingUid = mIsolatedOwners.get(callingUid);
6224            }
6225            final int appId = UserHandle.getAppId(callingUid);
6226            final Object obj = mSettings.getUserIdLPr(appId);
6227            if (obj instanceof PackageSetting) {
6228                final PackageSetting ps = (PackageSetting) obj;
6229                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6230                return isInstantApp ? ps.pkg.packageName : null;
6231            }
6232        }
6233        return null;
6234    }
6235
6236    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6237            String resolvedType, int flags, int userId) {
6238        return queryIntentActivitiesInternal(
6239                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6240                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6241    }
6242
6243    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6244            String resolvedType, int flags, int filterCallingUid, int userId,
6245            boolean resolveForStart, boolean allowDynamicSplits) {
6246        if (!sUserManager.exists(userId)) return Collections.emptyList();
6247        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6248        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6249                false /* requireFullPermission */, false /* checkShell */,
6250                "query intent activities");
6251        final String pkgName = intent.getPackage();
6252        ComponentName comp = intent.getComponent();
6253        if (comp == null) {
6254            if (intent.getSelector() != null) {
6255                intent = intent.getSelector();
6256                comp = intent.getComponent();
6257            }
6258        }
6259
6260        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6261                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6262        if (comp != null) {
6263            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6264            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6265            if (ai != null) {
6266                // When specifying an explicit component, we prevent the activity from being
6267                // used when either 1) the calling package is normal and the activity is within
6268                // an ephemeral application or 2) the calling package is ephemeral and the
6269                // activity is not visible to ephemeral applications.
6270                final boolean matchInstantApp =
6271                        (flags & PackageManager.MATCH_INSTANT) != 0;
6272                final boolean matchVisibleToInstantAppOnly =
6273                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6274                final boolean matchExplicitlyVisibleOnly =
6275                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6276                final boolean isCallerInstantApp =
6277                        instantAppPkgName != null;
6278                final boolean isTargetSameInstantApp =
6279                        comp.getPackageName().equals(instantAppPkgName);
6280                final boolean isTargetInstantApp =
6281                        (ai.applicationInfo.privateFlags
6282                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6283                final boolean isTargetVisibleToInstantApp =
6284                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6285                final boolean isTargetExplicitlyVisibleToInstantApp =
6286                        isTargetVisibleToInstantApp
6287                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6288                final boolean isTargetHiddenFromInstantApp =
6289                        !isTargetVisibleToInstantApp
6290                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6291                final boolean blockResolution =
6292                        !isTargetSameInstantApp
6293                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6294                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6295                                        && isTargetHiddenFromInstantApp));
6296                if (!blockResolution) {
6297                    final ResolveInfo ri = new ResolveInfo();
6298                    ri.activityInfo = ai;
6299                    list.add(ri);
6300                }
6301            }
6302            return applyPostResolutionFilter(
6303                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6304        }
6305
6306        // reader
6307        boolean sortResult = false;
6308        boolean addEphemeral = false;
6309        List<ResolveInfo> result;
6310        final boolean ephemeralDisabled = isEphemeralDisabled();
6311        synchronized (mPackages) {
6312            if (pkgName == null) {
6313                List<CrossProfileIntentFilter> matchingFilters =
6314                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6315                // Check for results that need to skip the current profile.
6316                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6317                        resolvedType, flags, userId);
6318                if (xpResolveInfo != null) {
6319                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6320                    xpResult.add(xpResolveInfo);
6321                    return applyPostResolutionFilter(
6322                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6323                            allowDynamicSplits, filterCallingUid, userId);
6324                }
6325
6326                // Check for results in the current profile.
6327                result = filterIfNotSystemUser(mActivities.queryIntent(
6328                        intent, resolvedType, flags, userId), userId);
6329                addEphemeral = !ephemeralDisabled
6330                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6331                // Check for cross profile results.
6332                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6333                xpResolveInfo = queryCrossProfileIntents(
6334                        matchingFilters, intent, resolvedType, flags, userId,
6335                        hasNonNegativePriorityResult);
6336                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6337                    boolean isVisibleToUser = filterIfNotSystemUser(
6338                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6339                    if (isVisibleToUser) {
6340                        result.add(xpResolveInfo);
6341                        sortResult = true;
6342                    }
6343                }
6344                if (hasWebURI(intent)) {
6345                    CrossProfileDomainInfo xpDomainInfo = null;
6346                    final UserInfo parent = getProfileParent(userId);
6347                    if (parent != null) {
6348                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6349                                flags, userId, parent.id);
6350                    }
6351                    if (xpDomainInfo != null) {
6352                        if (xpResolveInfo != null) {
6353                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6354                            // in the result.
6355                            result.remove(xpResolveInfo);
6356                        }
6357                        if (result.size() == 0 && !addEphemeral) {
6358                            // No result in current profile, but found candidate in parent user.
6359                            // And we are not going to add emphemeral app, so we can return the
6360                            // result straight away.
6361                            result.add(xpDomainInfo.resolveInfo);
6362                            return applyPostResolutionFilter(result, instantAppPkgName,
6363                                    allowDynamicSplits, filterCallingUid, userId);
6364                        }
6365                    } else if (result.size() <= 1 && !addEphemeral) {
6366                        // No result in parent user and <= 1 result in current profile, and we
6367                        // are not going to add emphemeral app, so we can return the result without
6368                        // further processing.
6369                        return applyPostResolutionFilter(result, instantAppPkgName,
6370                                allowDynamicSplits, filterCallingUid, userId);
6371                    }
6372                    // We have more than one candidate (combining results from current and parent
6373                    // profile), so we need filtering and sorting.
6374                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6375                            intent, flags, result, xpDomainInfo, userId);
6376                    sortResult = true;
6377                }
6378            } else {
6379                final PackageParser.Package pkg = mPackages.get(pkgName);
6380                result = null;
6381                if (pkg != null) {
6382                    result = filterIfNotSystemUser(
6383                            mActivities.queryIntentForPackage(
6384                                    intent, resolvedType, flags, pkg.activities, userId),
6385                            userId);
6386                }
6387                if (result == null || result.size() == 0) {
6388                    // the caller wants to resolve for a particular package; however, there
6389                    // were no installed results, so, try to find an ephemeral result
6390                    addEphemeral = !ephemeralDisabled
6391                            && isInstantAppAllowed(
6392                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6393                    if (result == null) {
6394                        result = new ArrayList<>();
6395                    }
6396                }
6397            }
6398        }
6399        if (addEphemeral) {
6400            result = maybeAddInstantAppInstaller(
6401                    result, intent, resolvedType, flags, userId, resolveForStart);
6402        }
6403        if (sortResult) {
6404            Collections.sort(result, mResolvePrioritySorter);
6405        }
6406        return applyPostResolutionFilter(
6407                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6408    }
6409
6410    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6411            String resolvedType, int flags, int userId, boolean resolveForStart) {
6412        // first, check to see if we've got an instant app already installed
6413        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6414        ResolveInfo localInstantApp = null;
6415        boolean blockResolution = false;
6416        if (!alreadyResolvedLocally) {
6417            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6418                    flags
6419                        | PackageManager.GET_RESOLVED_FILTER
6420                        | PackageManager.MATCH_INSTANT
6421                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6422                    userId);
6423            for (int i = instantApps.size() - 1; i >= 0; --i) {
6424                final ResolveInfo info = instantApps.get(i);
6425                final String packageName = info.activityInfo.packageName;
6426                final PackageSetting ps = mSettings.mPackages.get(packageName);
6427                if (ps.getInstantApp(userId)) {
6428                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6429                    final int status = (int)(packedStatus >> 32);
6430                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6431                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6432                        // there's a local instant application installed, but, the user has
6433                        // chosen to never use it; skip resolution and don't acknowledge
6434                        // an instant application is even available
6435                        if (DEBUG_EPHEMERAL) {
6436                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6437                        }
6438                        blockResolution = true;
6439                        break;
6440                    } else {
6441                        // we have a locally installed instant application; skip resolution
6442                        // but acknowledge there's an instant application available
6443                        if (DEBUG_EPHEMERAL) {
6444                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6445                        }
6446                        localInstantApp = info;
6447                        break;
6448                    }
6449                }
6450            }
6451        }
6452        // no app installed, let's see if one's available
6453        AuxiliaryResolveInfo auxiliaryResponse = null;
6454        if (!blockResolution) {
6455            if (localInstantApp == null) {
6456                // we don't have an instant app locally, resolve externally
6457                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6458                final InstantAppRequest requestObject = new InstantAppRequest(
6459                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6460                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6461                        resolveForStart);
6462                auxiliaryResponse =
6463                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6464                                mContext, mInstantAppResolverConnection, requestObject);
6465                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6466            } else {
6467                // we have an instant application locally, but, we can't admit that since
6468                // callers shouldn't be able to determine prior browsing. create a dummy
6469                // auxiliary response so the downstream code behaves as if there's an
6470                // instant application available externally. when it comes time to start
6471                // the instant application, we'll do the right thing.
6472                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6473                auxiliaryResponse = new AuxiliaryResolveInfo(
6474                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6475                        ai.versionCode, null /*failureIntent*/);
6476            }
6477        }
6478        if (auxiliaryResponse != null) {
6479            if (DEBUG_EPHEMERAL) {
6480                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6481            }
6482            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6483            final PackageSetting ps =
6484                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6485            if (ps != null) {
6486                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6487                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6488                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6489                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6490                // make sure this resolver is the default
6491                ephemeralInstaller.isDefault = true;
6492                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6493                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6494                // add a non-generic filter
6495                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6496                ephemeralInstaller.filter.addDataPath(
6497                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6498                ephemeralInstaller.isInstantAppAvailable = true;
6499                result.add(ephemeralInstaller);
6500            }
6501        }
6502        return result;
6503    }
6504
6505    private static class CrossProfileDomainInfo {
6506        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6507        ResolveInfo resolveInfo;
6508        /* Best domain verification status of the activities found in the other profile */
6509        int bestDomainVerificationStatus;
6510    }
6511
6512    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6513            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6514        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6515                sourceUserId)) {
6516            return null;
6517        }
6518        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6519                resolvedType, flags, parentUserId);
6520
6521        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6522            return null;
6523        }
6524        CrossProfileDomainInfo result = null;
6525        int size = resultTargetUser.size();
6526        for (int i = 0; i < size; i++) {
6527            ResolveInfo riTargetUser = resultTargetUser.get(i);
6528            // Intent filter verification is only for filters that specify a host. So don't return
6529            // those that handle all web uris.
6530            if (riTargetUser.handleAllWebDataURI) {
6531                continue;
6532            }
6533            String packageName = riTargetUser.activityInfo.packageName;
6534            PackageSetting ps = mSettings.mPackages.get(packageName);
6535            if (ps == null) {
6536                continue;
6537            }
6538            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6539            int status = (int)(verificationState >> 32);
6540            if (result == null) {
6541                result = new CrossProfileDomainInfo();
6542                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6543                        sourceUserId, parentUserId);
6544                result.bestDomainVerificationStatus = status;
6545            } else {
6546                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6547                        result.bestDomainVerificationStatus);
6548            }
6549        }
6550        // Don't consider matches with status NEVER across profiles.
6551        if (result != null && result.bestDomainVerificationStatus
6552                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6553            return null;
6554        }
6555        return result;
6556    }
6557
6558    /**
6559     * Verification statuses are ordered from the worse to the best, except for
6560     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6561     */
6562    private int bestDomainVerificationStatus(int status1, int status2) {
6563        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6564            return status2;
6565        }
6566        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6567            return status1;
6568        }
6569        return (int) MathUtils.max(status1, status2);
6570    }
6571
6572    private boolean isUserEnabled(int userId) {
6573        long callingId = Binder.clearCallingIdentity();
6574        try {
6575            UserInfo userInfo = sUserManager.getUserInfo(userId);
6576            return userInfo != null && userInfo.isEnabled();
6577        } finally {
6578            Binder.restoreCallingIdentity(callingId);
6579        }
6580    }
6581
6582    /**
6583     * Filter out activities with systemUserOnly flag set, when current user is not System.
6584     *
6585     * @return filtered list
6586     */
6587    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6588        if (userId == UserHandle.USER_SYSTEM) {
6589            return resolveInfos;
6590        }
6591        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6592            ResolveInfo info = resolveInfos.get(i);
6593            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6594                resolveInfos.remove(i);
6595            }
6596        }
6597        return resolveInfos;
6598    }
6599
6600    /**
6601     * Filters out ephemeral activities.
6602     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6603     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6604     *
6605     * @param resolveInfos The pre-filtered list of resolved activities
6606     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6607     *          is performed.
6608     * @return A filtered list of resolved activities.
6609     */
6610    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6611            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6612        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6613            final ResolveInfo info = resolveInfos.get(i);
6614            // allow activities that are defined in the provided package
6615            if (allowDynamicSplits
6616                    && info.activityInfo.splitName != null
6617                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6618                            info.activityInfo.splitName)) {
6619                if (mInstantAppInstallerInfo == null) {
6620                    if (DEBUG_INSTALL) {
6621                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6622                    }
6623                    resolveInfos.remove(i);
6624                    continue;
6625                }
6626                // requested activity is defined in a split that hasn't been installed yet.
6627                // add the installer to the resolve list
6628                if (DEBUG_INSTALL) {
6629                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6630                }
6631                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6632                final ComponentName installFailureActivity = findInstallFailureActivity(
6633                        info.activityInfo.packageName,  filterCallingUid, userId);
6634                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6635                        info.activityInfo.packageName, info.activityInfo.splitName,
6636                        installFailureActivity,
6637                        info.activityInfo.applicationInfo.versionCode,
6638                        null /*failureIntent*/);
6639                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6640                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6641                // add a non-generic filter
6642                installerInfo.filter = new IntentFilter();
6643
6644                // This resolve info may appear in the chooser UI, so let us make it
6645                // look as the one it replaces as far as the user is concerned which
6646                // requires loading the correct label and icon for the resolve info.
6647                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6648                installerInfo.labelRes = info.resolveLabelResId();
6649                installerInfo.icon = info.resolveIconResId();
6650
6651                // propagate priority/preferred order/default
6652                installerInfo.priority = info.priority;
6653                installerInfo.preferredOrder = info.preferredOrder;
6654                installerInfo.isDefault = info.isDefault;
6655                resolveInfos.set(i, installerInfo);
6656                continue;
6657            }
6658            // caller is a full app, don't need to apply any other filtering
6659            if (ephemeralPkgName == null) {
6660                continue;
6661            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6662                // caller is same app; don't need to apply any other filtering
6663                continue;
6664            }
6665            // allow activities that have been explicitly exposed to ephemeral apps
6666            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6667            if (!isEphemeralApp
6668                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6669                continue;
6670            }
6671            resolveInfos.remove(i);
6672        }
6673        return resolveInfos;
6674    }
6675
6676    /**
6677     * Returns the activity component that can handle install failures.
6678     * <p>By default, the instant application installer handles failures. However, an
6679     * application may want to handle failures on its own. Applications do this by
6680     * creating an activity with an intent filter that handles the action
6681     * {@link Intent#ACTION_INSTALL_FAILURE}.
6682     */
6683    private @Nullable ComponentName findInstallFailureActivity(
6684            String packageName, int filterCallingUid, int userId) {
6685        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6686        failureActivityIntent.setPackage(packageName);
6687        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6688        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6689                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6690                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6691        final int NR = result.size();
6692        if (NR > 0) {
6693            for (int i = 0; i < NR; i++) {
6694                final ResolveInfo info = result.get(i);
6695                if (info.activityInfo.splitName != null) {
6696                    continue;
6697                }
6698                return new ComponentName(packageName, info.activityInfo.name);
6699            }
6700        }
6701        return null;
6702    }
6703
6704    /**
6705     * @param resolveInfos list of resolve infos in descending priority order
6706     * @return if the list contains a resolve info with non-negative priority
6707     */
6708    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6709        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6710    }
6711
6712    private static boolean hasWebURI(Intent intent) {
6713        if (intent.getData() == null) {
6714            return false;
6715        }
6716        final String scheme = intent.getScheme();
6717        if (TextUtils.isEmpty(scheme)) {
6718            return false;
6719        }
6720        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6721    }
6722
6723    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6724            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6725            int userId) {
6726        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6727
6728        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6729            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6730                    candidates.size());
6731        }
6732
6733        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6734        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6735        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6736        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6737        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6738        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6739
6740        synchronized (mPackages) {
6741            final int count = candidates.size();
6742            // First, try to use linked apps. Partition the candidates into four lists:
6743            // one for the final results, one for the "do not use ever", one for "undefined status"
6744            // and finally one for "browser app type".
6745            for (int n=0; n<count; n++) {
6746                ResolveInfo info = candidates.get(n);
6747                String packageName = info.activityInfo.packageName;
6748                PackageSetting ps = mSettings.mPackages.get(packageName);
6749                if (ps != null) {
6750                    // Add to the special match all list (Browser use case)
6751                    if (info.handleAllWebDataURI) {
6752                        matchAllList.add(info);
6753                        continue;
6754                    }
6755                    // Try to get the status from User settings first
6756                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6757                    int status = (int)(packedStatus >> 32);
6758                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6759                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6760                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6761                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6762                                    + " : linkgen=" + linkGeneration);
6763                        }
6764                        // Use link-enabled generation as preferredOrder, i.e.
6765                        // prefer newly-enabled over earlier-enabled.
6766                        info.preferredOrder = linkGeneration;
6767                        alwaysList.add(info);
6768                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6769                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6770                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6771                        }
6772                        neverList.add(info);
6773                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6774                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6775                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6776                        }
6777                        alwaysAskList.add(info);
6778                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6779                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6780                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6781                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6782                        }
6783                        undefinedList.add(info);
6784                    }
6785                }
6786            }
6787
6788            // We'll want to include browser possibilities in a few cases
6789            boolean includeBrowser = false;
6790
6791            // First try to add the "always" resolution(s) for the current user, if any
6792            if (alwaysList.size() > 0) {
6793                result.addAll(alwaysList);
6794            } else {
6795                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6796                result.addAll(undefinedList);
6797                // Maybe add one for the other profile.
6798                if (xpDomainInfo != null && (
6799                        xpDomainInfo.bestDomainVerificationStatus
6800                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6801                    result.add(xpDomainInfo.resolveInfo);
6802                }
6803                includeBrowser = true;
6804            }
6805
6806            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6807            // If there were 'always' entries their preferred order has been set, so we also
6808            // back that off to make the alternatives equivalent
6809            if (alwaysAskList.size() > 0) {
6810                for (ResolveInfo i : result) {
6811                    i.preferredOrder = 0;
6812                }
6813                result.addAll(alwaysAskList);
6814                includeBrowser = true;
6815            }
6816
6817            if (includeBrowser) {
6818                // Also add browsers (all of them or only the default one)
6819                if (DEBUG_DOMAIN_VERIFICATION) {
6820                    Slog.v(TAG, "   ...including browsers in candidate set");
6821                }
6822                if ((matchFlags & MATCH_ALL) != 0) {
6823                    result.addAll(matchAllList);
6824                } else {
6825                    // Browser/generic handling case.  If there's a default browser, go straight
6826                    // to that (but only if there is no other higher-priority match).
6827                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6828                    int maxMatchPrio = 0;
6829                    ResolveInfo defaultBrowserMatch = null;
6830                    final int numCandidates = matchAllList.size();
6831                    for (int n = 0; n < numCandidates; n++) {
6832                        ResolveInfo info = matchAllList.get(n);
6833                        // track the highest overall match priority...
6834                        if (info.priority > maxMatchPrio) {
6835                            maxMatchPrio = info.priority;
6836                        }
6837                        // ...and the highest-priority default browser match
6838                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6839                            if (defaultBrowserMatch == null
6840                                    || (defaultBrowserMatch.priority < info.priority)) {
6841                                if (debug) {
6842                                    Slog.v(TAG, "Considering default browser match " + info);
6843                                }
6844                                defaultBrowserMatch = info;
6845                            }
6846                        }
6847                    }
6848                    if (defaultBrowserMatch != null
6849                            && defaultBrowserMatch.priority >= maxMatchPrio
6850                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6851                    {
6852                        if (debug) {
6853                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6854                        }
6855                        result.add(defaultBrowserMatch);
6856                    } else {
6857                        result.addAll(matchAllList);
6858                    }
6859                }
6860
6861                // If there is nothing selected, add all candidates and remove the ones that the user
6862                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6863                if (result.size() == 0) {
6864                    result.addAll(candidates);
6865                    result.removeAll(neverList);
6866                }
6867            }
6868        }
6869        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6870            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6871                    result.size());
6872            for (ResolveInfo info : result) {
6873                Slog.v(TAG, "  + " + info.activityInfo);
6874            }
6875        }
6876        return result;
6877    }
6878
6879    // Returns a packed value as a long:
6880    //
6881    // high 'int'-sized word: link status: undefined/ask/never/always.
6882    // low 'int'-sized word: relative priority among 'always' results.
6883    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6884        long result = ps.getDomainVerificationStatusForUser(userId);
6885        // if none available, get the master status
6886        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6887            if (ps.getIntentFilterVerificationInfo() != null) {
6888                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6889            }
6890        }
6891        return result;
6892    }
6893
6894    private ResolveInfo querySkipCurrentProfileIntents(
6895            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6896            int flags, int sourceUserId) {
6897        if (matchingFilters != null) {
6898            int size = matchingFilters.size();
6899            for (int i = 0; i < size; i ++) {
6900                CrossProfileIntentFilter filter = matchingFilters.get(i);
6901                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6902                    // Checking if there are activities in the target user that can handle the
6903                    // intent.
6904                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6905                            resolvedType, flags, sourceUserId);
6906                    if (resolveInfo != null) {
6907                        return resolveInfo;
6908                    }
6909                }
6910            }
6911        }
6912        return null;
6913    }
6914
6915    // Return matching ResolveInfo in target user if any.
6916    private ResolveInfo queryCrossProfileIntents(
6917            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6918            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6919        if (matchingFilters != null) {
6920            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6921            // match the same intent. For performance reasons, it is better not to
6922            // run queryIntent twice for the same userId
6923            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6924            int size = matchingFilters.size();
6925            for (int i = 0; i < size; i++) {
6926                CrossProfileIntentFilter filter = matchingFilters.get(i);
6927                int targetUserId = filter.getTargetUserId();
6928                boolean skipCurrentProfile =
6929                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6930                boolean skipCurrentProfileIfNoMatchFound =
6931                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6932                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6933                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6934                    // Checking if there are activities in the target user that can handle the
6935                    // intent.
6936                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6937                            resolvedType, flags, sourceUserId);
6938                    if (resolveInfo != null) return resolveInfo;
6939                    alreadyTriedUserIds.put(targetUserId, true);
6940                }
6941            }
6942        }
6943        return null;
6944    }
6945
6946    /**
6947     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6948     * will forward the intent to the filter's target user.
6949     * Otherwise, returns null.
6950     */
6951    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6952            String resolvedType, int flags, int sourceUserId) {
6953        int targetUserId = filter.getTargetUserId();
6954        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6955                resolvedType, flags, targetUserId);
6956        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6957            // If all the matches in the target profile are suspended, return null.
6958            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6959                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6960                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6961                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6962                            targetUserId);
6963                }
6964            }
6965        }
6966        return null;
6967    }
6968
6969    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6970            int sourceUserId, int targetUserId) {
6971        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6972        long ident = Binder.clearCallingIdentity();
6973        boolean targetIsProfile;
6974        try {
6975            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6976        } finally {
6977            Binder.restoreCallingIdentity(ident);
6978        }
6979        String className;
6980        if (targetIsProfile) {
6981            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6982        } else {
6983            className = FORWARD_INTENT_TO_PARENT;
6984        }
6985        ComponentName forwardingActivityComponentName = new ComponentName(
6986                mAndroidApplication.packageName, className);
6987        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6988                sourceUserId);
6989        if (!targetIsProfile) {
6990            forwardingActivityInfo.showUserIcon = targetUserId;
6991            forwardingResolveInfo.noResourceId = true;
6992        }
6993        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6994        forwardingResolveInfo.priority = 0;
6995        forwardingResolveInfo.preferredOrder = 0;
6996        forwardingResolveInfo.match = 0;
6997        forwardingResolveInfo.isDefault = true;
6998        forwardingResolveInfo.filter = filter;
6999        forwardingResolveInfo.targetUserId = targetUserId;
7000        return forwardingResolveInfo;
7001    }
7002
7003    @Override
7004    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7005            Intent[] specifics, String[] specificTypes, Intent intent,
7006            String resolvedType, int flags, int userId) {
7007        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7008                specificTypes, intent, resolvedType, flags, userId));
7009    }
7010
7011    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7012            Intent[] specifics, String[] specificTypes, Intent intent,
7013            String resolvedType, int flags, int userId) {
7014        if (!sUserManager.exists(userId)) return Collections.emptyList();
7015        final int callingUid = Binder.getCallingUid();
7016        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7017                false /*includeInstantApps*/);
7018        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7019                false /*requireFullPermission*/, false /*checkShell*/,
7020                "query intent activity options");
7021        final String resultsAction = intent.getAction();
7022
7023        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7024                | PackageManager.GET_RESOLVED_FILTER, userId);
7025
7026        if (DEBUG_INTENT_MATCHING) {
7027            Log.v(TAG, "Query " + intent + ": " + results);
7028        }
7029
7030        int specificsPos = 0;
7031        int N;
7032
7033        // todo: note that the algorithm used here is O(N^2).  This
7034        // isn't a problem in our current environment, but if we start running
7035        // into situations where we have more than 5 or 10 matches then this
7036        // should probably be changed to something smarter...
7037
7038        // First we go through and resolve each of the specific items
7039        // that were supplied, taking care of removing any corresponding
7040        // duplicate items in the generic resolve list.
7041        if (specifics != null) {
7042            for (int i=0; i<specifics.length; i++) {
7043                final Intent sintent = specifics[i];
7044                if (sintent == null) {
7045                    continue;
7046                }
7047
7048                if (DEBUG_INTENT_MATCHING) {
7049                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7050                }
7051
7052                String action = sintent.getAction();
7053                if (resultsAction != null && resultsAction.equals(action)) {
7054                    // If this action was explicitly requested, then don't
7055                    // remove things that have it.
7056                    action = null;
7057                }
7058
7059                ResolveInfo ri = null;
7060                ActivityInfo ai = null;
7061
7062                ComponentName comp = sintent.getComponent();
7063                if (comp == null) {
7064                    ri = resolveIntent(
7065                        sintent,
7066                        specificTypes != null ? specificTypes[i] : null,
7067                            flags, userId);
7068                    if (ri == null) {
7069                        continue;
7070                    }
7071                    if (ri == mResolveInfo) {
7072                        // ACK!  Must do something better with this.
7073                    }
7074                    ai = ri.activityInfo;
7075                    comp = new ComponentName(ai.applicationInfo.packageName,
7076                            ai.name);
7077                } else {
7078                    ai = getActivityInfo(comp, flags, userId);
7079                    if (ai == null) {
7080                        continue;
7081                    }
7082                }
7083
7084                // Look for any generic query activities that are duplicates
7085                // of this specific one, and remove them from the results.
7086                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7087                N = results.size();
7088                int j;
7089                for (j=specificsPos; j<N; j++) {
7090                    ResolveInfo sri = results.get(j);
7091                    if ((sri.activityInfo.name.equals(comp.getClassName())
7092                            && sri.activityInfo.applicationInfo.packageName.equals(
7093                                    comp.getPackageName()))
7094                        || (action != null && sri.filter.matchAction(action))) {
7095                        results.remove(j);
7096                        if (DEBUG_INTENT_MATCHING) Log.v(
7097                            TAG, "Removing duplicate item from " + j
7098                            + " due to specific " + specificsPos);
7099                        if (ri == null) {
7100                            ri = sri;
7101                        }
7102                        j--;
7103                        N--;
7104                    }
7105                }
7106
7107                // Add this specific item to its proper place.
7108                if (ri == null) {
7109                    ri = new ResolveInfo();
7110                    ri.activityInfo = ai;
7111                }
7112                results.add(specificsPos, ri);
7113                ri.specificIndex = i;
7114                specificsPos++;
7115            }
7116        }
7117
7118        // Now we go through the remaining generic results and remove any
7119        // duplicate actions that are found here.
7120        N = results.size();
7121        for (int i=specificsPos; i<N-1; i++) {
7122            final ResolveInfo rii = results.get(i);
7123            if (rii.filter == null) {
7124                continue;
7125            }
7126
7127            // Iterate over all of the actions of this result's intent
7128            // filter...  typically this should be just one.
7129            final Iterator<String> it = rii.filter.actionsIterator();
7130            if (it == null) {
7131                continue;
7132            }
7133            while (it.hasNext()) {
7134                final String action = it.next();
7135                if (resultsAction != null && resultsAction.equals(action)) {
7136                    // If this action was explicitly requested, then don't
7137                    // remove things that have it.
7138                    continue;
7139                }
7140                for (int j=i+1; j<N; j++) {
7141                    final ResolveInfo rij = results.get(j);
7142                    if (rij.filter != null && rij.filter.hasAction(action)) {
7143                        results.remove(j);
7144                        if (DEBUG_INTENT_MATCHING) Log.v(
7145                            TAG, "Removing duplicate item from " + j
7146                            + " due to action " + action + " at " + i);
7147                        j--;
7148                        N--;
7149                    }
7150                }
7151            }
7152
7153            // If the caller didn't request filter information, drop it now
7154            // so we don't have to marshall/unmarshall it.
7155            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7156                rii.filter = null;
7157            }
7158        }
7159
7160        // Filter out the caller activity if so requested.
7161        if (caller != null) {
7162            N = results.size();
7163            for (int i=0; i<N; i++) {
7164                ActivityInfo ainfo = results.get(i).activityInfo;
7165                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7166                        && caller.getClassName().equals(ainfo.name)) {
7167                    results.remove(i);
7168                    break;
7169                }
7170            }
7171        }
7172
7173        // If the caller didn't request filter information,
7174        // drop them now so we don't have to
7175        // marshall/unmarshall it.
7176        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7177            N = results.size();
7178            for (int i=0; i<N; i++) {
7179                results.get(i).filter = null;
7180            }
7181        }
7182
7183        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7184        return results;
7185    }
7186
7187    @Override
7188    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7189            String resolvedType, int flags, int userId) {
7190        return new ParceledListSlice<>(
7191                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7192                        false /*allowDynamicSplits*/));
7193    }
7194
7195    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7196            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7197        if (!sUserManager.exists(userId)) return Collections.emptyList();
7198        final int callingUid = Binder.getCallingUid();
7199        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7200                false /*requireFullPermission*/, false /*checkShell*/,
7201                "query intent receivers");
7202        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7203        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7204                false /*includeInstantApps*/);
7205        ComponentName comp = intent.getComponent();
7206        if (comp == null) {
7207            if (intent.getSelector() != null) {
7208                intent = intent.getSelector();
7209                comp = intent.getComponent();
7210            }
7211        }
7212        if (comp != null) {
7213            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7214            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7215            if (ai != null) {
7216                // When specifying an explicit component, we prevent the activity from being
7217                // used when either 1) the calling package is normal and the activity is within
7218                // an instant application or 2) the calling package is ephemeral and the
7219                // activity is not visible to instant applications.
7220                final boolean matchInstantApp =
7221                        (flags & PackageManager.MATCH_INSTANT) != 0;
7222                final boolean matchVisibleToInstantAppOnly =
7223                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7224                final boolean matchExplicitlyVisibleOnly =
7225                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7226                final boolean isCallerInstantApp =
7227                        instantAppPkgName != null;
7228                final boolean isTargetSameInstantApp =
7229                        comp.getPackageName().equals(instantAppPkgName);
7230                final boolean isTargetInstantApp =
7231                        (ai.applicationInfo.privateFlags
7232                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7233                final boolean isTargetVisibleToInstantApp =
7234                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7235                final boolean isTargetExplicitlyVisibleToInstantApp =
7236                        isTargetVisibleToInstantApp
7237                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7238                final boolean isTargetHiddenFromInstantApp =
7239                        !isTargetVisibleToInstantApp
7240                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7241                final boolean blockResolution =
7242                        !isTargetSameInstantApp
7243                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7244                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7245                                        && isTargetHiddenFromInstantApp));
7246                if (!blockResolution) {
7247                    ResolveInfo ri = new ResolveInfo();
7248                    ri.activityInfo = ai;
7249                    list.add(ri);
7250                }
7251            }
7252            return applyPostResolutionFilter(
7253                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7254        }
7255
7256        // reader
7257        synchronized (mPackages) {
7258            String pkgName = intent.getPackage();
7259            if (pkgName == null) {
7260                final List<ResolveInfo> result =
7261                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7262                return applyPostResolutionFilter(
7263                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7264            }
7265            final PackageParser.Package pkg = mPackages.get(pkgName);
7266            if (pkg != null) {
7267                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7268                        intent, resolvedType, flags, pkg.receivers, userId);
7269                return applyPostResolutionFilter(
7270                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7271            }
7272            return Collections.emptyList();
7273        }
7274    }
7275
7276    @Override
7277    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7278        final int callingUid = Binder.getCallingUid();
7279        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7280    }
7281
7282    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7283            int userId, int callingUid) {
7284        if (!sUserManager.exists(userId)) return null;
7285        flags = updateFlagsForResolve(
7286                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7287        List<ResolveInfo> query = queryIntentServicesInternal(
7288                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7289        if (query != null) {
7290            if (query.size() >= 1) {
7291                // If there is more than one service with the same priority,
7292                // just arbitrarily pick the first one.
7293                return query.get(0);
7294            }
7295        }
7296        return null;
7297    }
7298
7299    @Override
7300    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7301            String resolvedType, int flags, int userId) {
7302        final int callingUid = Binder.getCallingUid();
7303        return new ParceledListSlice<>(queryIntentServicesInternal(
7304                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7305    }
7306
7307    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7308            String resolvedType, int flags, int userId, int callingUid,
7309            boolean includeInstantApps) {
7310        if (!sUserManager.exists(userId)) return Collections.emptyList();
7311        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7312                false /*requireFullPermission*/, false /*checkShell*/,
7313                "query intent receivers");
7314        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7315        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7316        ComponentName comp = intent.getComponent();
7317        if (comp == null) {
7318            if (intent.getSelector() != null) {
7319                intent = intent.getSelector();
7320                comp = intent.getComponent();
7321            }
7322        }
7323        if (comp != null) {
7324            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7325            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7326            if (si != null) {
7327                // When specifying an explicit component, we prevent the service from being
7328                // used when either 1) the service is in an instant application and the
7329                // caller is not the same instant application or 2) the calling package is
7330                // ephemeral and the activity is not visible to ephemeral applications.
7331                final boolean matchInstantApp =
7332                        (flags & PackageManager.MATCH_INSTANT) != 0;
7333                final boolean matchVisibleToInstantAppOnly =
7334                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7335                final boolean isCallerInstantApp =
7336                        instantAppPkgName != null;
7337                final boolean isTargetSameInstantApp =
7338                        comp.getPackageName().equals(instantAppPkgName);
7339                final boolean isTargetInstantApp =
7340                        (si.applicationInfo.privateFlags
7341                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7342                final boolean isTargetHiddenFromInstantApp =
7343                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7344                final boolean blockResolution =
7345                        !isTargetSameInstantApp
7346                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7347                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7348                                        && isTargetHiddenFromInstantApp));
7349                if (!blockResolution) {
7350                    final ResolveInfo ri = new ResolveInfo();
7351                    ri.serviceInfo = si;
7352                    list.add(ri);
7353                }
7354            }
7355            return list;
7356        }
7357
7358        // reader
7359        synchronized (mPackages) {
7360            String pkgName = intent.getPackage();
7361            if (pkgName == null) {
7362                return applyPostServiceResolutionFilter(
7363                        mServices.queryIntent(intent, resolvedType, flags, userId),
7364                        instantAppPkgName);
7365            }
7366            final PackageParser.Package pkg = mPackages.get(pkgName);
7367            if (pkg != null) {
7368                return applyPostServiceResolutionFilter(
7369                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7370                                userId),
7371                        instantAppPkgName);
7372            }
7373            return Collections.emptyList();
7374        }
7375    }
7376
7377    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7378            String instantAppPkgName) {
7379        if (instantAppPkgName == null) {
7380            return resolveInfos;
7381        }
7382        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7383            final ResolveInfo info = resolveInfos.get(i);
7384            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7385            // allow services that are defined in the provided package
7386            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7387                if (info.serviceInfo.splitName != null
7388                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7389                                info.serviceInfo.splitName)) {
7390                    // requested service is defined in a split that hasn't been installed yet.
7391                    // add the installer to the resolve list
7392                    if (DEBUG_EPHEMERAL) {
7393                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7394                    }
7395                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7396                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7397                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7398                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7399                            null /*failureIntent*/);
7400                    // make sure this resolver is the default
7401                    installerInfo.isDefault = true;
7402                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7403                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7404                    // add a non-generic filter
7405                    installerInfo.filter = new IntentFilter();
7406                    // load resources from the correct package
7407                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7408                    resolveInfos.set(i, installerInfo);
7409                }
7410                continue;
7411            }
7412            // allow services that have been explicitly exposed to ephemeral apps
7413            if (!isEphemeralApp
7414                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7415                continue;
7416            }
7417            resolveInfos.remove(i);
7418        }
7419        return resolveInfos;
7420    }
7421
7422    @Override
7423    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7424            String resolvedType, int flags, int userId) {
7425        return new ParceledListSlice<>(
7426                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7427    }
7428
7429    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7430            Intent intent, String resolvedType, int flags, int userId) {
7431        if (!sUserManager.exists(userId)) return Collections.emptyList();
7432        final int callingUid = Binder.getCallingUid();
7433        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7434        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7435                false /*includeInstantApps*/);
7436        ComponentName comp = intent.getComponent();
7437        if (comp == null) {
7438            if (intent.getSelector() != null) {
7439                intent = intent.getSelector();
7440                comp = intent.getComponent();
7441            }
7442        }
7443        if (comp != null) {
7444            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7445            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7446            if (pi != null) {
7447                // When specifying an explicit component, we prevent the provider from being
7448                // used when either 1) the provider is in an instant application and the
7449                // caller is not the same instant application or 2) the calling package is an
7450                // instant application and the provider is not visible to instant applications.
7451                final boolean matchInstantApp =
7452                        (flags & PackageManager.MATCH_INSTANT) != 0;
7453                final boolean matchVisibleToInstantAppOnly =
7454                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7455                final boolean isCallerInstantApp =
7456                        instantAppPkgName != null;
7457                final boolean isTargetSameInstantApp =
7458                        comp.getPackageName().equals(instantAppPkgName);
7459                final boolean isTargetInstantApp =
7460                        (pi.applicationInfo.privateFlags
7461                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7462                final boolean isTargetHiddenFromInstantApp =
7463                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7464                final boolean blockResolution =
7465                        !isTargetSameInstantApp
7466                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7467                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7468                                        && isTargetHiddenFromInstantApp));
7469                if (!blockResolution) {
7470                    final ResolveInfo ri = new ResolveInfo();
7471                    ri.providerInfo = pi;
7472                    list.add(ri);
7473                }
7474            }
7475            return list;
7476        }
7477
7478        // reader
7479        synchronized (mPackages) {
7480            String pkgName = intent.getPackage();
7481            if (pkgName == null) {
7482                return applyPostContentProviderResolutionFilter(
7483                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7484                        instantAppPkgName);
7485            }
7486            final PackageParser.Package pkg = mPackages.get(pkgName);
7487            if (pkg != null) {
7488                return applyPostContentProviderResolutionFilter(
7489                        mProviders.queryIntentForPackage(
7490                        intent, resolvedType, flags, pkg.providers, userId),
7491                        instantAppPkgName);
7492            }
7493            return Collections.emptyList();
7494        }
7495    }
7496
7497    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7498            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7499        if (instantAppPkgName == null) {
7500            return resolveInfos;
7501        }
7502        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7503            final ResolveInfo info = resolveInfos.get(i);
7504            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7505            // allow providers that are defined in the provided package
7506            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7507                if (info.providerInfo.splitName != null
7508                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7509                                info.providerInfo.splitName)) {
7510                    // requested provider is defined in a split that hasn't been installed yet.
7511                    // add the installer to the resolve list
7512                    if (DEBUG_EPHEMERAL) {
7513                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7514                    }
7515                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7516                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7517                            info.providerInfo.packageName, info.providerInfo.splitName,
7518                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7519                            null /*failureIntent*/);
7520                    // make sure this resolver is the default
7521                    installerInfo.isDefault = true;
7522                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7523                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7524                    // add a non-generic filter
7525                    installerInfo.filter = new IntentFilter();
7526                    // load resources from the correct package
7527                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7528                    resolveInfos.set(i, installerInfo);
7529                }
7530                continue;
7531            }
7532            // allow providers that have been explicitly exposed to instant applications
7533            if (!isEphemeralApp
7534                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7535                continue;
7536            }
7537            resolveInfos.remove(i);
7538        }
7539        return resolveInfos;
7540    }
7541
7542    @Override
7543    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7544        final int callingUid = Binder.getCallingUid();
7545        if (getInstantAppPackageName(callingUid) != null) {
7546            return ParceledListSlice.emptyList();
7547        }
7548        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7549        flags = updateFlagsForPackage(flags, userId, null);
7550        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7551        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7552                true /* requireFullPermission */, false /* checkShell */,
7553                "get installed packages");
7554
7555        // writer
7556        synchronized (mPackages) {
7557            ArrayList<PackageInfo> list;
7558            if (listUninstalled) {
7559                list = new ArrayList<>(mSettings.mPackages.size());
7560                for (PackageSetting ps : mSettings.mPackages.values()) {
7561                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7562                        continue;
7563                    }
7564                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7565                        continue;
7566                    }
7567                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7568                    if (pi != null) {
7569                        list.add(pi);
7570                    }
7571                }
7572            } else {
7573                list = new ArrayList<>(mPackages.size());
7574                for (PackageParser.Package p : mPackages.values()) {
7575                    final PackageSetting ps = (PackageSetting) p.mExtras;
7576                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7577                        continue;
7578                    }
7579                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7580                        continue;
7581                    }
7582                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7583                            p.mExtras, flags, userId);
7584                    if (pi != null) {
7585                        list.add(pi);
7586                    }
7587                }
7588            }
7589
7590            return new ParceledListSlice<>(list);
7591        }
7592    }
7593
7594    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7595            String[] permissions, boolean[] tmp, int flags, int userId) {
7596        int numMatch = 0;
7597        final PermissionsState permissionsState = ps.getPermissionsState();
7598        for (int i=0; i<permissions.length; i++) {
7599            final String permission = permissions[i];
7600            if (permissionsState.hasPermission(permission, userId)) {
7601                tmp[i] = true;
7602                numMatch++;
7603            } else {
7604                tmp[i] = false;
7605            }
7606        }
7607        if (numMatch == 0) {
7608            return;
7609        }
7610        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7611
7612        // The above might return null in cases of uninstalled apps or install-state
7613        // skew across users/profiles.
7614        if (pi != null) {
7615            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7616                if (numMatch == permissions.length) {
7617                    pi.requestedPermissions = permissions;
7618                } else {
7619                    pi.requestedPermissions = new String[numMatch];
7620                    numMatch = 0;
7621                    for (int i=0; i<permissions.length; i++) {
7622                        if (tmp[i]) {
7623                            pi.requestedPermissions[numMatch] = permissions[i];
7624                            numMatch++;
7625                        }
7626                    }
7627                }
7628            }
7629            list.add(pi);
7630        }
7631    }
7632
7633    @Override
7634    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7635            String[] permissions, int flags, int userId) {
7636        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7637        flags = updateFlagsForPackage(flags, userId, permissions);
7638        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7639                true /* requireFullPermission */, false /* checkShell */,
7640                "get packages holding permissions");
7641        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7642
7643        // writer
7644        synchronized (mPackages) {
7645            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7646            boolean[] tmpBools = new boolean[permissions.length];
7647            if (listUninstalled) {
7648                for (PackageSetting ps : mSettings.mPackages.values()) {
7649                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7650                            userId);
7651                }
7652            } else {
7653                for (PackageParser.Package pkg : mPackages.values()) {
7654                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7655                    if (ps != null) {
7656                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7657                                userId);
7658                    }
7659                }
7660            }
7661
7662            return new ParceledListSlice<PackageInfo>(list);
7663        }
7664    }
7665
7666    @Override
7667    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7668        final int callingUid = Binder.getCallingUid();
7669        if (getInstantAppPackageName(callingUid) != null) {
7670            return ParceledListSlice.emptyList();
7671        }
7672        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7673        flags = updateFlagsForApplication(flags, userId, null);
7674        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7675
7676        // writer
7677        synchronized (mPackages) {
7678            ArrayList<ApplicationInfo> list;
7679            if (listUninstalled) {
7680                list = new ArrayList<>(mSettings.mPackages.size());
7681                for (PackageSetting ps : mSettings.mPackages.values()) {
7682                    ApplicationInfo ai;
7683                    int effectiveFlags = flags;
7684                    if (ps.isSystem()) {
7685                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7686                    }
7687                    if (ps.pkg != null) {
7688                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7689                            continue;
7690                        }
7691                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7692                            continue;
7693                        }
7694                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7695                                ps.readUserState(userId), userId);
7696                        if (ai != null) {
7697                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7698                        }
7699                    } else {
7700                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7701                        // and already converts to externally visible package name
7702                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7703                                callingUid, effectiveFlags, userId);
7704                    }
7705                    if (ai != null) {
7706                        list.add(ai);
7707                    }
7708                }
7709            } else {
7710                list = new ArrayList<>(mPackages.size());
7711                for (PackageParser.Package p : mPackages.values()) {
7712                    if (p.mExtras != null) {
7713                        PackageSetting ps = (PackageSetting) p.mExtras;
7714                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7715                            continue;
7716                        }
7717                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7718                            continue;
7719                        }
7720                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7721                                ps.readUserState(userId), userId);
7722                        if (ai != null) {
7723                            ai.packageName = resolveExternalPackageNameLPr(p);
7724                            list.add(ai);
7725                        }
7726                    }
7727                }
7728            }
7729
7730            return new ParceledListSlice<>(list);
7731        }
7732    }
7733
7734    @Override
7735    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7736        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7737            return null;
7738        }
7739        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7740            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7741                    "getEphemeralApplications");
7742        }
7743        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7744                true /* requireFullPermission */, false /* checkShell */,
7745                "getEphemeralApplications");
7746        synchronized (mPackages) {
7747            List<InstantAppInfo> instantApps = mInstantAppRegistry
7748                    .getInstantAppsLPr(userId);
7749            if (instantApps != null) {
7750                return new ParceledListSlice<>(instantApps);
7751            }
7752        }
7753        return null;
7754    }
7755
7756    @Override
7757    public boolean isInstantApp(String packageName, int userId) {
7758        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7759                true /* requireFullPermission */, false /* checkShell */,
7760                "isInstantApp");
7761        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7762            return false;
7763        }
7764
7765        synchronized (mPackages) {
7766            int callingUid = Binder.getCallingUid();
7767            if (Process.isIsolated(callingUid)) {
7768                callingUid = mIsolatedOwners.get(callingUid);
7769            }
7770            final PackageSetting ps = mSettings.mPackages.get(packageName);
7771            PackageParser.Package pkg = mPackages.get(packageName);
7772            final boolean returnAllowed =
7773                    ps != null
7774                    && (isCallerSameApp(packageName, callingUid)
7775                            || canViewInstantApps(callingUid, userId)
7776                            || mInstantAppRegistry.isInstantAccessGranted(
7777                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7778            if (returnAllowed) {
7779                return ps.getInstantApp(userId);
7780            }
7781        }
7782        return false;
7783    }
7784
7785    @Override
7786    public byte[] getInstantAppCookie(String packageName, int userId) {
7787        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7788            return null;
7789        }
7790
7791        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7792                true /* requireFullPermission */, false /* checkShell */,
7793                "getInstantAppCookie");
7794        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7795            return null;
7796        }
7797        synchronized (mPackages) {
7798            return mInstantAppRegistry.getInstantAppCookieLPw(
7799                    packageName, userId);
7800        }
7801    }
7802
7803    @Override
7804    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7805        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7806            return true;
7807        }
7808
7809        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7810                true /* requireFullPermission */, true /* checkShell */,
7811                "setInstantAppCookie");
7812        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7813            return false;
7814        }
7815        synchronized (mPackages) {
7816            return mInstantAppRegistry.setInstantAppCookieLPw(
7817                    packageName, cookie, userId);
7818        }
7819    }
7820
7821    @Override
7822    public Bitmap getInstantAppIcon(String packageName, int userId) {
7823        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7824            return null;
7825        }
7826
7827        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7828            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7829                    "getInstantAppIcon");
7830        }
7831        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7832                true /* requireFullPermission */, false /* checkShell */,
7833                "getInstantAppIcon");
7834
7835        synchronized (mPackages) {
7836            return mInstantAppRegistry.getInstantAppIconLPw(
7837                    packageName, userId);
7838        }
7839    }
7840
7841    private boolean isCallerSameApp(String packageName, int uid) {
7842        PackageParser.Package pkg = mPackages.get(packageName);
7843        return pkg != null
7844                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7845    }
7846
7847    @Override
7848    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7849        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7850            return ParceledListSlice.emptyList();
7851        }
7852        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7853    }
7854
7855    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7856        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7857
7858        // reader
7859        synchronized (mPackages) {
7860            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7861            final int userId = UserHandle.getCallingUserId();
7862            while (i.hasNext()) {
7863                final PackageParser.Package p = i.next();
7864                if (p.applicationInfo == null) continue;
7865
7866                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7867                        && !p.applicationInfo.isDirectBootAware();
7868                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7869                        && p.applicationInfo.isDirectBootAware();
7870
7871                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7872                        && (!mSafeMode || isSystemApp(p))
7873                        && (matchesUnaware || matchesAware)) {
7874                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7875                    if (ps != null) {
7876                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7877                                ps.readUserState(userId), userId);
7878                        if (ai != null) {
7879                            finalList.add(ai);
7880                        }
7881                    }
7882                }
7883            }
7884        }
7885
7886        return finalList;
7887    }
7888
7889    @Override
7890    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7891        return resolveContentProviderInternal(name, flags, userId);
7892    }
7893
7894    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7895        if (!sUserManager.exists(userId)) return null;
7896        flags = updateFlagsForComponent(flags, userId, name);
7897        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7898        // reader
7899        synchronized (mPackages) {
7900            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7901            PackageSetting ps = provider != null
7902                    ? mSettings.mPackages.get(provider.owner.packageName)
7903                    : null;
7904            if (ps != null) {
7905                final boolean isInstantApp = ps.getInstantApp(userId);
7906                // normal application; filter out instant application provider
7907                if (instantAppPkgName == null && isInstantApp) {
7908                    return null;
7909                }
7910                // instant application; filter out other instant applications
7911                if (instantAppPkgName != null
7912                        && isInstantApp
7913                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7914                    return null;
7915                }
7916                // instant application; filter out non-exposed provider
7917                if (instantAppPkgName != null
7918                        && !isInstantApp
7919                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7920                    return null;
7921                }
7922                // provider not enabled
7923                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7924                    return null;
7925                }
7926                return PackageParser.generateProviderInfo(
7927                        provider, flags, ps.readUserState(userId), userId);
7928            }
7929            return null;
7930        }
7931    }
7932
7933    /**
7934     * @deprecated
7935     */
7936    @Deprecated
7937    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7938        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7939            return;
7940        }
7941        // reader
7942        synchronized (mPackages) {
7943            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7944                    .entrySet().iterator();
7945            final int userId = UserHandle.getCallingUserId();
7946            while (i.hasNext()) {
7947                Map.Entry<String, PackageParser.Provider> entry = i.next();
7948                PackageParser.Provider p = entry.getValue();
7949                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7950
7951                if (ps != null && p.syncable
7952                        && (!mSafeMode || (p.info.applicationInfo.flags
7953                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7954                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7955                            ps.readUserState(userId), userId);
7956                    if (info != null) {
7957                        outNames.add(entry.getKey());
7958                        outInfo.add(info);
7959                    }
7960                }
7961            }
7962        }
7963    }
7964
7965    @Override
7966    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7967            int uid, int flags, String metaDataKey) {
7968        final int callingUid = Binder.getCallingUid();
7969        final int userId = processName != null ? UserHandle.getUserId(uid)
7970                : UserHandle.getCallingUserId();
7971        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7972        flags = updateFlagsForComponent(flags, userId, processName);
7973        ArrayList<ProviderInfo> finalList = null;
7974        // reader
7975        synchronized (mPackages) {
7976            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7977            while (i.hasNext()) {
7978                final PackageParser.Provider p = i.next();
7979                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7980                if (ps != null && p.info.authority != null
7981                        && (processName == null
7982                                || (p.info.processName.equals(processName)
7983                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7984                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7985
7986                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7987                    // parameter.
7988                    if (metaDataKey != null
7989                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7990                        continue;
7991                    }
7992                    final ComponentName component =
7993                            new ComponentName(p.info.packageName, p.info.name);
7994                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
7995                        continue;
7996                    }
7997                    if (finalList == null) {
7998                        finalList = new ArrayList<ProviderInfo>(3);
7999                    }
8000                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8001                            ps.readUserState(userId), userId);
8002                    if (info != null) {
8003                        finalList.add(info);
8004                    }
8005                }
8006            }
8007        }
8008
8009        if (finalList != null) {
8010            Collections.sort(finalList, mProviderInitOrderSorter);
8011            return new ParceledListSlice<ProviderInfo>(finalList);
8012        }
8013
8014        return ParceledListSlice.emptyList();
8015    }
8016
8017    @Override
8018    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8019        // reader
8020        synchronized (mPackages) {
8021            final int callingUid = Binder.getCallingUid();
8022            final int callingUserId = UserHandle.getUserId(callingUid);
8023            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8024            if (ps == null) return null;
8025            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8026                return null;
8027            }
8028            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8029            return PackageParser.generateInstrumentationInfo(i, flags);
8030        }
8031    }
8032
8033    @Override
8034    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8035            String targetPackage, int flags) {
8036        final int callingUid = Binder.getCallingUid();
8037        final int callingUserId = UserHandle.getUserId(callingUid);
8038        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8039        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8040            return ParceledListSlice.emptyList();
8041        }
8042        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8043    }
8044
8045    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8046            int flags) {
8047        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8048
8049        // reader
8050        synchronized (mPackages) {
8051            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8052            while (i.hasNext()) {
8053                final PackageParser.Instrumentation p = i.next();
8054                if (targetPackage == null
8055                        || targetPackage.equals(p.info.targetPackage)) {
8056                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8057                            flags);
8058                    if (ii != null) {
8059                        finalList.add(ii);
8060                    }
8061                }
8062            }
8063        }
8064
8065        return finalList;
8066    }
8067
8068    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8069        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8070        try {
8071            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8072        } finally {
8073            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8074        }
8075    }
8076
8077    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8078        final File[] files = scanDir.listFiles();
8079        if (ArrayUtils.isEmpty(files)) {
8080            Log.d(TAG, "No files in app dir " + scanDir);
8081            return;
8082        }
8083
8084        if (DEBUG_PACKAGE_SCANNING) {
8085            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8086                    + " flags=0x" + Integer.toHexString(parseFlags));
8087        }
8088        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8089                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8090                mParallelPackageParserCallback)) {
8091            // Submit files for parsing in parallel
8092            int fileCount = 0;
8093            for (File file : files) {
8094                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8095                        && !PackageInstallerService.isStageName(file.getName());
8096                if (!isPackage) {
8097                    // Ignore entries which are not packages
8098                    continue;
8099                }
8100                parallelPackageParser.submit(file, parseFlags);
8101                fileCount++;
8102            }
8103
8104            // Process results one by one
8105            for (; fileCount > 0; fileCount--) {
8106                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8107                Throwable throwable = parseResult.throwable;
8108                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8109
8110                if (throwable == null) {
8111                    // Static shared libraries have synthetic package names
8112                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8113                        renameStaticSharedLibraryPackage(parseResult.pkg);
8114                    }
8115                    try {
8116                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8117                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8118                                    currentTime, null);
8119                        }
8120                    } catch (PackageManagerException e) {
8121                        errorCode = e.error;
8122                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8123                    }
8124                } else if (throwable instanceof PackageParser.PackageParserException) {
8125                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8126                            throwable;
8127                    errorCode = e.error;
8128                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8129                } else {
8130                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8131                            + parseResult.scanFile, throwable);
8132                }
8133
8134                // Delete invalid userdata apps
8135                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8136                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8137                    logCriticalInfo(Log.WARN,
8138                            "Deleting invalid package at " + parseResult.scanFile);
8139                    removeCodePathLI(parseResult.scanFile);
8140                }
8141            }
8142        }
8143    }
8144
8145    public static void reportSettingsProblem(int priority, String msg) {
8146        logCriticalInfo(priority, msg);
8147    }
8148
8149    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8150            final @ParseFlags int parseFlags) throws PackageManagerException {
8151        // When upgrading from pre-N MR1, verify the package time stamp using the package
8152        // directory and not the APK file.
8153        final long lastModifiedTime = mIsPreNMR1Upgrade
8154                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8155        if (ps != null
8156                && ps.codePathString.equals(pkg.codePath)
8157                && ps.timeStamp == lastModifiedTime
8158                && !isCompatSignatureUpdateNeeded(pkg)
8159                && !isRecoverSignatureUpdateNeeded(pkg)) {
8160            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8161            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
8162            ArraySet<PublicKey> signingKs;
8163            synchronized (mPackages) {
8164                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8165            }
8166            if (ps.signatures.mSignatures != null
8167                    && ps.signatures.mSignatures.length != 0
8168                    && signingKs != null) {
8169                // Optimization: reuse the existing cached certificates
8170                // if the package appears to be unchanged.
8171                pkg.mSignatures = ps.signatures.mSignatures;
8172                pkg.mSigningKeys = signingKs;
8173                return;
8174            }
8175
8176            Slog.w(TAG, "PackageSetting for " + ps.name
8177                    + " is missing signatures.  Collecting certs again to recover them.");
8178        } else {
8179            Slog.i(TAG, toString() + " changed; collecting certs");
8180        }
8181
8182        try {
8183            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8184            PackageParser.collectCertificates(pkg, parseFlags);
8185        } catch (PackageParserException e) {
8186            throw PackageManagerException.from(e);
8187        } finally {
8188            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8189        }
8190    }
8191
8192    /**
8193     *  Traces a package scan.
8194     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8195     */
8196    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8197            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8198        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8199        try {
8200            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8201        } finally {
8202            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8203        }
8204    }
8205
8206    /**
8207     *  Scans a package and returns the newly parsed package.
8208     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8209     */
8210    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8211            long currentTime, UserHandle user) throws PackageManagerException {
8212        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8213        PackageParser pp = new PackageParser();
8214        pp.setSeparateProcesses(mSeparateProcesses);
8215        pp.setOnlyCoreApps(mOnlyCore);
8216        pp.setDisplayMetrics(mMetrics);
8217        pp.setCallback(mPackageParserCallback);
8218
8219        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8220        final PackageParser.Package pkg;
8221        try {
8222            pkg = pp.parsePackage(scanFile, parseFlags);
8223        } catch (PackageParserException e) {
8224            throw PackageManagerException.from(e);
8225        } finally {
8226            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8227        }
8228
8229        // Static shared libraries have synthetic package names
8230        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8231            renameStaticSharedLibraryPackage(pkg);
8232        }
8233
8234        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8235    }
8236
8237    /**
8238     *  Scans a package and returns the newly parsed package.
8239     *  @throws PackageManagerException on a parse error.
8240     */
8241    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8242            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8243            @Nullable UserHandle user)
8244                    throws PackageManagerException {
8245        // If the package has children and this is the first dive in the function
8246        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8247        // packages (parent and children) would be successfully scanned before the
8248        // actual scan since scanning mutates internal state and we want to atomically
8249        // install the package and its children.
8250        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8251            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8252                scanFlags |= SCAN_CHECK_ONLY;
8253            }
8254        } else {
8255            scanFlags &= ~SCAN_CHECK_ONLY;
8256        }
8257
8258        // Scan the parent
8259        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, parseFlags,
8260                scanFlags, currentTime, user);
8261
8262        // Scan the children
8263        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8264        for (int i = 0; i < childCount; i++) {
8265            PackageParser.Package childPackage = pkg.childPackages.get(i);
8266            scanPackageInternalLI(childPackage, parseFlags, scanFlags,
8267                    currentTime, user);
8268        }
8269
8270
8271        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8272            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8273        }
8274
8275        return scannedPkg;
8276    }
8277
8278    /**
8279     *  Scans a package and returns the newly parsed package.
8280     *  @throws PackageManagerException on a parse error.
8281     */
8282    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg,
8283            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8284            @Nullable UserHandle user)
8285                    throws PackageManagerException {
8286        PackageSetting ps = null;
8287        PackageSetting updatedPs;
8288        // reader
8289        synchronized (mPackages) {
8290            // Look to see if we already know about this package.
8291            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8292            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8293                // This package has been renamed to its original name.  Let's
8294                // use that.
8295                ps = mSettings.getPackageLPr(oldName);
8296            }
8297            // If there was no original package, see one for the real package name.
8298            if (ps == null) {
8299                ps = mSettings.getPackageLPr(pkg.packageName);
8300            }
8301            // Check to see if this package could be hiding/updating a system
8302            // package.  Must look for it either under the original or real
8303            // package name depending on our state.
8304            updatedPs = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8305            if (DEBUG_INSTALL && updatedPs != null) Slog.d(TAG, "updatedPkg = " + updatedPs);
8306
8307            // If this is a package we don't know about on the system partition, we
8308            // may need to remove disabled child packages on the system partition
8309            // or may need to not add child packages if the parent apk is updated
8310            // on the data partition and no longer defines this child package.
8311            if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
8312                // If this is a parent package for an updated system app and this system
8313                // app got an OTA update which no longer defines some of the child packages
8314                // we have to prune them from the disabled system packages.
8315                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8316                if (disabledPs != null) {
8317                    final int scannedChildCount = (pkg.childPackages != null)
8318                            ? pkg.childPackages.size() : 0;
8319                    final int disabledChildCount = disabledPs.childPackageNames != null
8320                            ? disabledPs.childPackageNames.size() : 0;
8321                    for (int i = 0; i < disabledChildCount; i++) {
8322                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8323                        boolean disabledPackageAvailable = false;
8324                        for (int j = 0; j < scannedChildCount; j++) {
8325                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8326                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8327                                disabledPackageAvailable = true;
8328                                break;
8329                            }
8330                         }
8331                         if (!disabledPackageAvailable) {
8332                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8333                         }
8334                    }
8335                }
8336            }
8337        }
8338
8339        final boolean isUpdatedPkg = updatedPs != null;
8340        final boolean isUpdatedSystemPkg = isUpdatedPkg && (scanFlags & SCAN_AS_SYSTEM) != 0;
8341        boolean isUpdatedPkgBetter = false;
8342        // First check if this is a system package that may involve an update
8343        if (isUpdatedSystemPkg) {
8344            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8345            // it needs to drop FLAG_PRIVILEGED.
8346            if (locationIsPrivileged(pkg.codePath)) {
8347                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8348            } else {
8349                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8350            }
8351            // If new package is not located in "/oem" (e.g. due to an OTA),
8352            // it needs to drop FLAG_OEM.
8353            if (locationIsOem(pkg.codePath)) {
8354                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8355            } else {
8356                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8357            }
8358            // If new package is not located in "/vendor" (e.g. due to an OTA),
8359            // it needs to drop FLAG_VENDOR.
8360            if (locationIsVendor(pkg.codePath)) {
8361                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
8362            } else {
8363                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_VENDOR;
8364            }
8365
8366            if (ps != null && !ps.codePathString.equals(pkg.codePath)) {
8367                // The path has changed from what was last scanned...  check the
8368                // version of the new path against what we have stored to determine
8369                // what to do.
8370                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8371                if (pkg.mVersionCode <= ps.versionCode) {
8372                    // The system package has been updated and the code path does not match
8373                    // Ignore entry. Skip it.
8374                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + pkg.codePath
8375                            + " ignored: updated version " + ps.versionCode
8376                            + " better than this " + pkg.mVersionCode);
8377                    if (!updatedPs.codePathString.equals(pkg.codePath)) {
8378                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8379                                + ps.name + " changing from " + updatedPs.codePathString
8380                                + " to " + pkg.codePath);
8381                        final File codePath = new File(pkg.codePath);
8382                        updatedPs.codePath = codePath;
8383                        updatedPs.codePathString = pkg.codePath;
8384                        updatedPs.resourcePath = codePath;
8385                        updatedPs.resourcePathString = pkg.codePath;
8386                    }
8387                    updatedPs.pkg = pkg;
8388                    updatedPs.versionCode = pkg.mVersionCode;
8389
8390                    // Update the disabled system child packages to point to the package too.
8391                    final int childCount = updatedPs.childPackageNames != null
8392                            ? updatedPs.childPackageNames.size() : 0;
8393                    for (int i = 0; i < childCount; i++) {
8394                        String childPackageName = updatedPs.childPackageNames.get(i);
8395                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8396                                childPackageName);
8397                        if (updatedChildPkg != null) {
8398                            updatedChildPkg.pkg = pkg;
8399                            updatedChildPkg.versionCode = pkg.mVersionCode;
8400                        }
8401                    }
8402                } else {
8403                    // The current app on the system partition is better than
8404                    // what we have updated to on the data partition; switch
8405                    // back to the system partition version.
8406                    // At this point, its safely assumed that package installation for
8407                    // apps in system partition will go through. If not there won't be a working
8408                    // version of the app
8409                    // writer
8410                    synchronized (mPackages) {
8411                        // Just remove the loaded entries from package lists.
8412                        mPackages.remove(ps.name);
8413                    }
8414
8415                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath
8416                            + " reverting from " + ps.codePathString
8417                            + ": new version " + pkg.mVersionCode
8418                            + " better than installed " + ps.versionCode);
8419
8420                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8421                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8422                    synchronized (mInstallLock) {
8423                        args.cleanUpResourcesLI();
8424                    }
8425                    synchronized (mPackages) {
8426                        mSettings.enableSystemPackageLPw(ps.name);
8427                    }
8428                    isUpdatedPkgBetter = true;
8429                }
8430            }
8431        }
8432
8433        String resourcePath = null;
8434        String baseResourcePath = null;
8435        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8436            if (ps != null && ps.resourcePathString != null) {
8437                resourcePath = ps.resourcePathString;
8438                baseResourcePath = ps.resourcePathString;
8439            } else {
8440                // Should not happen at all. Just log an error.
8441                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8442            }
8443        } else {
8444            resourcePath = pkg.codePath;
8445            baseResourcePath = pkg.baseCodePath;
8446        }
8447
8448        // Set application objects path explicitly.
8449        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8450        pkg.setApplicationInfoCodePath(pkg.codePath);
8451        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8452        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8453        pkg.setApplicationInfoResourcePath(resourcePath);
8454        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8455        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8456
8457        // throw an exception if we have an update to a system application, but, it's not more
8458        // recent than the package we've already scanned
8459        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8460            // Set CPU Abis to application info.
8461            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8462                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPs);
8463                derivePackageAbi(pkg, cpuAbiOverride, false, mAppLib32InstallDir);
8464            } else {
8465                pkg.applicationInfo.primaryCpuAbi = updatedPs.primaryCpuAbiString;
8466                pkg.applicationInfo.secondaryCpuAbi = updatedPs.secondaryCpuAbiString;
8467            }
8468            pkg.mExtras = updatedPs;
8469
8470            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8471                    + pkg.codePath + " ignored: updated version " + updatedPs.versionCode
8472                    + " better than this " + pkg.mVersionCode);
8473        }
8474
8475        if (isUpdatedPkg) {
8476            // updated system applications don't initially have the SCAN_AS_SYSTEM flag set
8477            scanFlags |= SCAN_AS_SYSTEM;
8478
8479            // An updated privileged application will not have the PARSE_IS_PRIVILEGED
8480            // flag set initially
8481            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8482                scanFlags |= SCAN_AS_PRIVILEGED;
8483            }
8484
8485            // An updated OEM app will not have the SCAN_AS_OEM
8486            // flag set initially
8487            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8488                scanFlags |= SCAN_AS_OEM;
8489            }
8490
8491            // An updated vendor app will not have the SCAN_AS_VENDOR
8492            // flag set initially
8493            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
8494                scanFlags |= SCAN_AS_VENDOR;
8495            }
8496        }
8497
8498        // Verify certificates against what was last scanned
8499        collectCertificatesLI(ps, pkg, parseFlags);
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                && (parseFlags & 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 " + pkg.codePath
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 " + pkg.codePath
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 ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8556            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8557                parseFlags |= 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, parseFlags, 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(@Nullable List<String> packageNames) {
9077        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9078            return false;
9079        }
9080        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
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 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9573            @Nullable UserHandle user) 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, parseFlags, 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, parseFlags,
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, parseFlags, scanFlags, currentTime, user);
9605        }
9606
9607        return scannedPkg;
9608    }
9609
9610    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
9611            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9612            @Nullable UserHandle user) throws PackageManagerException {
9613        boolean success = false;
9614        try {
9615            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, 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 @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9679            @Nullable UserHandle user)
9680                    throws PackageManagerException {
9681        if (DEBUG_PACKAGE_SCANNING) {
9682            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9683                Log.d(TAG, "Scanning package " + pkg.packageName);
9684        }
9685
9686        applyPolicy(pkg, parseFlags, scanFlags);
9687
9688        assertPackageIsValid(pkg, parseFlags, scanFlags);
9689
9690        if (Build.IS_DEBUGGABLE &&
9691                pkg.isPrivileged() &&
9692                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
9693            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
9694        }
9695
9696        // Initialize package source and resource directories
9697        final File scanFile = new File(pkg.codePath);
9698        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9699        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9700
9701        SharedUserSetting suid = null;
9702        PackageSetting pkgSetting = null;
9703
9704        // Getting the package setting may have a side-effect, so if we
9705        // are only checking if scan would succeed, stash a copy of the
9706        // old setting to restore at the end.
9707        PackageSetting nonMutatedPs = null;
9708
9709        // We keep references to the derived CPU Abis from settings in oder to reuse
9710        // them in the case where we're not upgrading or booting for the first time.
9711        String primaryCpuAbiFromSettings = null;
9712        String secondaryCpuAbiFromSettings = null;
9713
9714        // writer
9715        synchronized (mPackages) {
9716            if (pkg.mSharedUserId != null) {
9717                // SIDE EFFECTS; may potentially allocate a new shared user
9718                suid = mSettings.getSharedUserLPw(
9719                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9720                if (DEBUG_PACKAGE_SCANNING) {
9721                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9722                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9723                                + "): packages=" + suid.packages);
9724                }
9725            }
9726
9727            // Check if we are renaming from an original package name.
9728            PackageSetting origPackage = null;
9729            String realName = null;
9730            if (pkg.mOriginalPackages != null) {
9731                // This package may need to be renamed to a previously
9732                // installed name.  Let's check on that...
9733                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9734                if (pkg.mOriginalPackages.contains(renamed)) {
9735                    // This package had originally been installed as the
9736                    // original name, and we have already taken care of
9737                    // transitioning to the new one.  Just update the new
9738                    // one to continue using the old name.
9739                    realName = pkg.mRealPackage;
9740                    if (!pkg.packageName.equals(renamed)) {
9741                        // Callers into this function may have already taken
9742                        // care of renaming the package; only do it here if
9743                        // it is not already done.
9744                        pkg.setPackageName(renamed);
9745                    }
9746                } else {
9747                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9748                        if ((origPackage = mSettings.getPackageLPr(
9749                                pkg.mOriginalPackages.get(i))) != null) {
9750                            // We do have the package already installed under its
9751                            // original name...  should we use it?
9752                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9753                                // New package is not compatible with original.
9754                                origPackage = null;
9755                                continue;
9756                            } else if (origPackage.sharedUser != null) {
9757                                // Make sure uid is compatible between packages.
9758                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9759                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9760                                            + " to " + pkg.packageName + ": old uid "
9761                                            + origPackage.sharedUser.name
9762                                            + " differs from " + pkg.mSharedUserId);
9763                                    origPackage = null;
9764                                    continue;
9765                                }
9766                                // TODO: Add case when shared user id is added [b/28144775]
9767                            } else {
9768                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9769                                        + pkg.packageName + " to old name " + origPackage.name);
9770                            }
9771                            break;
9772                        }
9773                    }
9774                }
9775            }
9776
9777            if (mTransferedPackages.contains(pkg.packageName)) {
9778                Slog.w(TAG, "Package " + pkg.packageName
9779                        + " was transferred to another, but its .apk remains");
9780            }
9781
9782            // See comments in nonMutatedPs declaration
9783            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9784                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9785                if (foundPs != null) {
9786                    nonMutatedPs = new PackageSetting(foundPs);
9787                }
9788            }
9789
9790            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9791                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9792                if (foundPs != null) {
9793                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9794                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9795                }
9796            }
9797
9798            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9799            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9800                PackageManagerService.reportSettingsProblem(Log.WARN,
9801                        "Package " + pkg.packageName + " shared user changed from "
9802                                + (pkgSetting.sharedUser != null
9803                                        ? pkgSetting.sharedUser.name : "<nothing>")
9804                                + " to "
9805                                + (suid != null ? suid.name : "<nothing>")
9806                                + "; replacing with new");
9807                pkgSetting = null;
9808            }
9809            final PackageSetting oldPkgSetting =
9810                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9811            final PackageSetting disabledPkgSetting =
9812                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9813
9814            String[] usesStaticLibraries = null;
9815            if (pkg.usesStaticLibraries != null) {
9816                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9817                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9818            }
9819
9820            if (pkgSetting == null) {
9821                final String parentPackageName = (pkg.parentPackage != null)
9822                        ? pkg.parentPackage.packageName : null;
9823                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9824                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
9825                // REMOVE SharedUserSetting from method; update in a separate call
9826                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9827                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9828                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9829                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9830                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9831                        true /*allowInstall*/, instantApp, virtualPreload,
9832                        parentPackageName, pkg.getChildPackageNames(),
9833                        UserManagerService.getInstance(), usesStaticLibraries,
9834                        pkg.usesStaticLibrariesVersions);
9835                // SIDE EFFECTS; updates system state; move elsewhere
9836                if (origPackage != null) {
9837                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9838                }
9839                mSettings.addUserToSettingLPw(pkgSetting);
9840            } else {
9841                // REMOVE SharedUserSetting from method; update in a separate call.
9842                //
9843                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9844                // secondaryCpuAbi are not known at this point so we always update them
9845                // to null here, only to reset them at a later point.
9846                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9847                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9848                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9849                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9850                        UserManagerService.getInstance(), usesStaticLibraries,
9851                        pkg.usesStaticLibrariesVersions);
9852            }
9853            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9854            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9855
9856            // SIDE EFFECTS; modifies system state; move elsewhere
9857            if (pkgSetting.origPackage != null) {
9858                // If we are first transitioning from an original package,
9859                // fix up the new package's name now.  We need to do this after
9860                // looking up the package under its new name, so getPackageLP
9861                // can take care of fiddling things correctly.
9862                pkg.setPackageName(origPackage.name);
9863
9864                // File a report about this.
9865                String msg = "New package " + pkgSetting.realName
9866                        + " renamed to replace old package " + pkgSetting.name;
9867                reportSettingsProblem(Log.WARN, msg);
9868
9869                // Make a note of it.
9870                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9871                    mTransferedPackages.add(origPackage.name);
9872                }
9873
9874                // No longer need to retain this.
9875                pkgSetting.origPackage = null;
9876            }
9877
9878            // SIDE EFFECTS; modifies system state; move elsewhere
9879            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9880                // Make a note of it.
9881                mTransferedPackages.add(pkg.packageName);
9882            }
9883
9884            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9885                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9886            }
9887
9888            if ((scanFlags & SCAN_BOOTING) == 0
9889                    && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9890                // Check all shared libraries and map to their actual file path.
9891                // We only do this here for apps not on a system dir, because those
9892                // are the only ones that can fail an install due to this.  We
9893                // will take care of the system apps by updating all of their
9894                // library paths after the scan is done. Also during the initial
9895                // scan don't update any libs as we do this wholesale after all
9896                // apps are scanned to avoid dependency based scanning.
9897                updateSharedLibrariesLPr(pkg, null);
9898            }
9899
9900            if (mFoundPolicyFile) {
9901                SELinuxMMAC.assignSeInfoValue(pkg);
9902            }
9903            pkg.applicationInfo.uid = pkgSetting.appId;
9904            pkg.mExtras = pkgSetting;
9905
9906
9907            // Static shared libs have same package with different versions where
9908            // we internally use a synthetic package name to allow multiple versions
9909            // of the same package, therefore we need to compare signatures against
9910            // the package setting for the latest library version.
9911            PackageSetting signatureCheckPs = pkgSetting;
9912            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9913                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9914                if (libraryEntry != null) {
9915                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9916                }
9917            }
9918
9919            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9920            if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9921                if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9922                    // We just determined the app is signed correctly, so bring
9923                    // over the latest parsed certs.
9924                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9925                } else {
9926                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9927                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9928                                "Package " + pkg.packageName + " upgrade keys do not match the "
9929                                + "previously installed version");
9930                    } else {
9931                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9932                        String msg = "System package " + pkg.packageName
9933                                + " signature changed; retaining data.";
9934                        reportSettingsProblem(Log.WARN, msg);
9935                    }
9936                }
9937            } else {
9938                try {
9939                    final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9940                    final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9941                    final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures,
9942                            compareCompat, compareRecover);
9943                    // The new KeySets will be re-added later in the scanning process.
9944                    if (compatMatch) {
9945                        synchronized (mPackages) {
9946                            ksms.removeAppKeySetDataLPw(pkg.packageName);
9947                        }
9948                    }
9949                    // We just determined the app is signed correctly, so bring
9950                    // over the latest parsed certs.
9951                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9952                } catch (PackageManagerException e) {
9953                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9954                        throw e;
9955                    }
9956                    // The signature has changed, but this package is in the system
9957                    // image...  let's recover!
9958                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9959                    // However...  if this package is part of a shared user, but it
9960                    // doesn't match the signature of the shared user, let's fail.
9961                    // What this means is that you can't change the signatures
9962                    // associated with an overall shared user, which doesn't seem all
9963                    // that unreasonable.
9964                    if (signatureCheckPs.sharedUser != null) {
9965                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9966                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9967                            throw new PackageManagerException(
9968                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9969                                    "Signature mismatch for shared user: "
9970                                            + pkgSetting.sharedUser);
9971                        }
9972                    }
9973                    // File a report about this.
9974                    String msg = "System package " + pkg.packageName
9975                            + " signature changed; retaining data.";
9976                    reportSettingsProblem(Log.WARN, msg);
9977                }
9978            }
9979
9980            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9981                // This package wants to adopt ownership of permissions from
9982                // another package.
9983                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9984                    final String origName = pkg.mAdoptPermissions.get(i);
9985                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9986                    if (orig != null) {
9987                        if (verifyPackageUpdateLPr(orig, pkg)) {
9988                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9989                                    + pkg.packageName);
9990                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9991                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9992                        }
9993                    }
9994                }
9995            }
9996        }
9997
9998        pkg.applicationInfo.processName = fixProcessName(
9999                pkg.applicationInfo.packageName,
10000                pkg.applicationInfo.processName);
10001
10002        if (pkg != mPlatformPackage) {
10003            // Get all of our default paths setup
10004            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10005        }
10006
10007        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10008
10009        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10010            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10011                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10012                final boolean extractNativeLibs = !pkg.isLibrary();
10013                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs, 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);
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 ((parseFlags & 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                    (parseFlags & 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, final @ParseFlags int parseFlags,
10165            final @ScanFlags int scanFlags) {
10166        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10167            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10168            if (pkg.applicationInfo.isDirectBootAware()) {
10169                // we're direct boot aware; set for all components
10170                for (PackageParser.Service s : pkg.services) {
10171                    s.info.encryptionAware = s.info.directBootAware = true;
10172                }
10173                for (PackageParser.Provider p : pkg.providers) {
10174                    p.info.encryptionAware = p.info.directBootAware = true;
10175                }
10176                for (PackageParser.Activity a : pkg.activities) {
10177                    a.info.encryptionAware = a.info.directBootAware = true;
10178                }
10179                for (PackageParser.Activity r : pkg.receivers) {
10180                    r.info.encryptionAware = r.info.directBootAware = true;
10181                }
10182            }
10183            if (compressedFileExists(pkg.codePath)) {
10184                pkg.isStub = true;
10185            }
10186        } else {
10187            // non system apps can't be flagged as core
10188            pkg.coreApp = false;
10189            // clear flags not applicable to regular apps
10190            pkg.applicationInfo.flags &=
10191                    ~ApplicationInfo.FLAG_PERSISTENT;
10192            pkg.applicationInfo.privateFlags &=
10193                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10194            pkg.applicationInfo.privateFlags &=
10195                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10196            // clear protected broadcasts
10197            pkg.protectedBroadcasts = null;
10198            // cap permission priorities
10199            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10200                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10201                    pkg.permissionGroups.get(i).info.priority = 0;
10202                }
10203            }
10204        }
10205        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10206            // ignore export request for single user receivers
10207            if (pkg.receivers != null) {
10208                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10209                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10210                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10211                        receiver.info.exported = false;
10212                    }
10213                }
10214            }
10215            // ignore export request for single user services
10216            if (pkg.services != null) {
10217                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10218                    final PackageParser.Service service = pkg.services.get(i);
10219                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10220                        service.info.exported = false;
10221                    }
10222                }
10223            }
10224            // ignore export request for single user providers
10225            if (pkg.providers != null) {
10226                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10227                    final PackageParser.Provider provider = pkg.providers.get(i);
10228                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10229                        provider.info.exported = false;
10230                    }
10231                }
10232            }
10233        }
10234        pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0;
10235
10236        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10237            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10238        }
10239
10240        if ((scanFlags & SCAN_AS_OEM) != 0) {
10241            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10242        }
10243
10244        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10245            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10246        }
10247
10248        if (!isSystemApp(pkg)) {
10249            // Only system apps can use these features.
10250            pkg.mOriginalPackages = null;
10251            pkg.mRealPackage = null;
10252            pkg.mAdoptPermissions = null;
10253        }
10254    }
10255
10256    /**
10257     * Asserts the parsed package is valid according to the given policy. If the
10258     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10259     * <p>
10260     * Implementation detail: This method must NOT have any side effects. It would
10261     * ideally be static, but, it requires locks to read system state.
10262     *
10263     * @throws PackageManagerException If the package fails any of the validation checks
10264     */
10265    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10266            final @ScanFlags int scanFlags)
10267                    throws PackageManagerException {
10268        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10269            assertCodePolicy(pkg);
10270        }
10271
10272        if (pkg.applicationInfo.getCodePath() == null ||
10273                pkg.applicationInfo.getResourcePath() == null) {
10274            // Bail out. The resource and code paths haven't been set.
10275            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10276                    "Code and resource paths haven't been set correctly");
10277        }
10278
10279        // Make sure we're not adding any bogus keyset info
10280        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10281        ksms.assertScannedPackageValid(pkg);
10282
10283        synchronized (mPackages) {
10284            // The special "android" package can only be defined once
10285            if (pkg.packageName.equals("android")) {
10286                if (mAndroidApplication != null) {
10287                    Slog.w(TAG, "*************************************************");
10288                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10289                    Slog.w(TAG, " codePath=" + pkg.codePath);
10290                    Slog.w(TAG, "*************************************************");
10291                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10292                            "Core android package being redefined.  Skipping.");
10293                }
10294            }
10295
10296            // A package name must be unique; don't allow duplicates
10297            if (mPackages.containsKey(pkg.packageName)) {
10298                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10299                        "Application package " + pkg.packageName
10300                        + " already installed.  Skipping duplicate.");
10301            }
10302
10303            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10304                // Static libs have a synthetic package name containing the version
10305                // but we still want the base name to be unique.
10306                if (mPackages.containsKey(pkg.manifestPackageName)) {
10307                    throw new PackageManagerException(
10308                            "Duplicate static shared lib provider package");
10309                }
10310
10311                // Static shared libraries should have at least O target SDK
10312                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10313                    throw new PackageManagerException(
10314                            "Packages declaring static-shared libs must target O SDK or higher");
10315                }
10316
10317                // Package declaring static a shared lib cannot be instant apps
10318                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10319                    throw new PackageManagerException(
10320                            "Packages declaring static-shared libs cannot be instant apps");
10321                }
10322
10323                // Package declaring static a shared lib cannot be renamed since the package
10324                // name is synthetic and apps can't code around package manager internals.
10325                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10326                    throw new PackageManagerException(
10327                            "Packages declaring static-shared libs cannot be renamed");
10328                }
10329
10330                // Package declaring static a shared lib cannot declare child packages
10331                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10332                    throw new PackageManagerException(
10333                            "Packages declaring static-shared libs cannot have child packages");
10334                }
10335
10336                // Package declaring static a shared lib cannot declare dynamic libs
10337                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10338                    throw new PackageManagerException(
10339                            "Packages declaring static-shared libs cannot declare dynamic libs");
10340                }
10341
10342                // Package declaring static a shared lib cannot declare shared users
10343                if (pkg.mSharedUserId != null) {
10344                    throw new PackageManagerException(
10345                            "Packages declaring static-shared libs cannot declare shared users");
10346                }
10347
10348                // Static shared libs cannot declare activities
10349                if (!pkg.activities.isEmpty()) {
10350                    throw new PackageManagerException(
10351                            "Static shared libs cannot declare activities");
10352                }
10353
10354                // Static shared libs cannot declare services
10355                if (!pkg.services.isEmpty()) {
10356                    throw new PackageManagerException(
10357                            "Static shared libs cannot declare services");
10358                }
10359
10360                // Static shared libs cannot declare providers
10361                if (!pkg.providers.isEmpty()) {
10362                    throw new PackageManagerException(
10363                            "Static shared libs cannot declare content providers");
10364                }
10365
10366                // Static shared libs cannot declare receivers
10367                if (!pkg.receivers.isEmpty()) {
10368                    throw new PackageManagerException(
10369                            "Static shared libs cannot declare broadcast receivers");
10370                }
10371
10372                // Static shared libs cannot declare permission groups
10373                if (!pkg.permissionGroups.isEmpty()) {
10374                    throw new PackageManagerException(
10375                            "Static shared libs cannot declare permission groups");
10376                }
10377
10378                // Static shared libs cannot declare permissions
10379                if (!pkg.permissions.isEmpty()) {
10380                    throw new PackageManagerException(
10381                            "Static shared libs cannot declare permissions");
10382                }
10383
10384                // Static shared libs cannot declare protected broadcasts
10385                if (pkg.protectedBroadcasts != null) {
10386                    throw new PackageManagerException(
10387                            "Static shared libs cannot declare protected broadcasts");
10388                }
10389
10390                // Static shared libs cannot be overlay targets
10391                if (pkg.mOverlayTarget != null) {
10392                    throw new PackageManagerException(
10393                            "Static shared libs cannot be overlay targets");
10394                }
10395
10396                // The version codes must be ordered as lib versions
10397                int minVersionCode = Integer.MIN_VALUE;
10398                int maxVersionCode = Integer.MAX_VALUE;
10399
10400                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10401                        pkg.staticSharedLibName);
10402                if (versionedLib != null) {
10403                    final int versionCount = versionedLib.size();
10404                    for (int i = 0; i < versionCount; i++) {
10405                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10406                        final int libVersionCode = libInfo.getDeclaringPackage()
10407                                .getVersionCode();
10408                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10409                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10410                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10411                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10412                        } else {
10413                            minVersionCode = maxVersionCode = libVersionCode;
10414                            break;
10415                        }
10416                    }
10417                }
10418                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10419                    throw new PackageManagerException("Static shared"
10420                            + " lib version codes must be ordered as lib versions");
10421                }
10422            }
10423
10424            // Only privileged apps and updated privileged apps can add child packages.
10425            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10426                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10427                    throw new PackageManagerException("Only privileged apps can add child "
10428                            + "packages. Ignoring package " + pkg.packageName);
10429                }
10430                final int childCount = pkg.childPackages.size();
10431                for (int i = 0; i < childCount; i++) {
10432                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10433                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10434                            childPkg.packageName)) {
10435                        throw new PackageManagerException("Can't override child of "
10436                                + "another disabled app. Ignoring package " + pkg.packageName);
10437                    }
10438                }
10439            }
10440
10441            // If we're only installing presumed-existing packages, require that the
10442            // scanned APK is both already known and at the path previously established
10443            // for it.  Previously unknown packages we pick up normally, but if we have an
10444            // a priori expectation about this package's install presence, enforce it.
10445            // With a singular exception for new system packages. When an OTA contains
10446            // a new system package, we allow the codepath to change from a system location
10447            // to the user-installed location. If we don't allow this change, any newer,
10448            // user-installed version of the application will be ignored.
10449            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10450                if (mExpectingBetter.containsKey(pkg.packageName)) {
10451                    logCriticalInfo(Log.WARN,
10452                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10453                } else {
10454                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10455                    if (known != null) {
10456                        if (DEBUG_PACKAGE_SCANNING) {
10457                            Log.d(TAG, "Examining " + pkg.codePath
10458                                    + " and requiring known paths " + known.codePathString
10459                                    + " & " + known.resourcePathString);
10460                        }
10461                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10462                                || !pkg.applicationInfo.getResourcePath().equals(
10463                                        known.resourcePathString)) {
10464                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10465                                    "Application package " + pkg.packageName
10466                                    + " found at " + pkg.applicationInfo.getCodePath()
10467                                    + " but expected at " + known.codePathString
10468                                    + "; ignoring.");
10469                        }
10470                    } else {
10471                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10472                                "Application package " + pkg.packageName
10473                                + " not found; ignoring.");
10474                    }
10475                }
10476            }
10477
10478            // Verify that this new package doesn't have any content providers
10479            // that conflict with existing packages.  Only do this if the
10480            // package isn't already installed, since we don't want to break
10481            // things that are installed.
10482            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10483                final int N = pkg.providers.size();
10484                int i;
10485                for (i=0; i<N; i++) {
10486                    PackageParser.Provider p = pkg.providers.get(i);
10487                    if (p.info.authority != null) {
10488                        String names[] = p.info.authority.split(";");
10489                        for (int j = 0; j < names.length; j++) {
10490                            if (mProvidersByAuthority.containsKey(names[j])) {
10491                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10492                                final String otherPackageName =
10493                                        ((other != null && other.getComponentName() != null) ?
10494                                                other.getComponentName().getPackageName() : "?");
10495                                throw new PackageManagerException(
10496                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10497                                        "Can't install because provider name " + names[j]
10498                                                + " (in package " + pkg.applicationInfo.packageName
10499                                                + ") is already used by " + otherPackageName);
10500                            }
10501                        }
10502                    }
10503                }
10504            }
10505        }
10506    }
10507
10508    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10509            int type, String declaringPackageName, int declaringVersionCode) {
10510        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10511        if (versionedLib == null) {
10512            versionedLib = new SparseArray<>();
10513            mSharedLibraries.put(name, versionedLib);
10514            if (type == SharedLibraryInfo.TYPE_STATIC) {
10515                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10516            }
10517        } else if (versionedLib.indexOfKey(version) >= 0) {
10518            return false;
10519        }
10520        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10521                version, type, declaringPackageName, declaringVersionCode);
10522        versionedLib.put(version, libEntry);
10523        return true;
10524    }
10525
10526    private boolean removeSharedLibraryLPw(String name, int version) {
10527        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10528        if (versionedLib == null) {
10529            return false;
10530        }
10531        final int libIdx = versionedLib.indexOfKey(version);
10532        if (libIdx < 0) {
10533            return false;
10534        }
10535        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10536        versionedLib.remove(version);
10537        if (versionedLib.size() <= 0) {
10538            mSharedLibraries.remove(name);
10539            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10540                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10541                        .getPackageName());
10542            }
10543        }
10544        return true;
10545    }
10546
10547    /**
10548     * Adds a scanned package to the system. When this method is finished, the package will
10549     * be available for query, resolution, etc...
10550     */
10551    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10552            UserHandle user, final @ScanFlags int scanFlags, boolean chatty)
10553                    throws PackageManagerException {
10554        final String pkgName = pkg.packageName;
10555        if (mCustomResolverComponentName != null &&
10556                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10557            setUpCustomResolverActivity(pkg);
10558        }
10559
10560        if (pkg.packageName.equals("android")) {
10561            synchronized (mPackages) {
10562                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10563                    // Set up information for our fall-back user intent resolution activity.
10564                    mPlatformPackage = pkg;
10565                    pkg.mVersionCode = mSdkVersion;
10566                    mAndroidApplication = pkg.applicationInfo;
10567                    if (!mResolverReplaced) {
10568                        mResolveActivity.applicationInfo = mAndroidApplication;
10569                        mResolveActivity.name = ResolverActivity.class.getName();
10570                        mResolveActivity.packageName = mAndroidApplication.packageName;
10571                        mResolveActivity.processName = "system:ui";
10572                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10573                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10574                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10575                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10576                        mResolveActivity.exported = true;
10577                        mResolveActivity.enabled = true;
10578                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10579                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10580                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10581                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10582                                | ActivityInfo.CONFIG_ORIENTATION
10583                                | ActivityInfo.CONFIG_KEYBOARD
10584                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10585                        mResolveInfo.activityInfo = mResolveActivity;
10586                        mResolveInfo.priority = 0;
10587                        mResolveInfo.preferredOrder = 0;
10588                        mResolveInfo.match = 0;
10589                        mResolveComponentName = new ComponentName(
10590                                mAndroidApplication.packageName, mResolveActivity.name);
10591                    }
10592                }
10593            }
10594        }
10595
10596        ArrayList<PackageParser.Package> clientLibPkgs = null;
10597        // writer
10598        synchronized (mPackages) {
10599            boolean hasStaticSharedLibs = false;
10600
10601            // Any app can add new static shared libraries
10602            if (pkg.staticSharedLibName != null) {
10603                // Static shared libs don't allow renaming as they have synthetic package
10604                // names to allow install of multiple versions, so use name from manifest.
10605                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10606                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10607                        pkg.manifestPackageName, pkg.mVersionCode)) {
10608                    hasStaticSharedLibs = true;
10609                } else {
10610                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10611                                + pkg.staticSharedLibName + " already exists; skipping");
10612                }
10613                // Static shared libs cannot be updated once installed since they
10614                // use synthetic package name which includes the version code, so
10615                // not need to update other packages's shared lib dependencies.
10616            }
10617
10618            if (!hasStaticSharedLibs
10619                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10620                // Only system apps can add new dynamic shared libraries.
10621                if (pkg.libraryNames != null) {
10622                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10623                        String name = pkg.libraryNames.get(i);
10624                        boolean allowed = false;
10625                        if (pkg.isUpdatedSystemApp()) {
10626                            // New library entries can only be added through the
10627                            // system image.  This is important to get rid of a lot
10628                            // of nasty edge cases: for example if we allowed a non-
10629                            // system update of the app to add a library, then uninstalling
10630                            // the update would make the library go away, and assumptions
10631                            // we made such as through app install filtering would now
10632                            // have allowed apps on the device which aren't compatible
10633                            // with it.  Better to just have the restriction here, be
10634                            // conservative, and create many fewer cases that can negatively
10635                            // impact the user experience.
10636                            final PackageSetting sysPs = mSettings
10637                                    .getDisabledSystemPkgLPr(pkg.packageName);
10638                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10639                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10640                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10641                                        allowed = true;
10642                                        break;
10643                                    }
10644                                }
10645                            }
10646                        } else {
10647                            allowed = true;
10648                        }
10649                        if (allowed) {
10650                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10651                                    SharedLibraryInfo.VERSION_UNDEFINED,
10652                                    SharedLibraryInfo.TYPE_DYNAMIC,
10653                                    pkg.packageName, pkg.mVersionCode)) {
10654                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10655                                        + name + " already exists; skipping");
10656                            }
10657                        } else {
10658                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10659                                    + name + " that is not declared on system image; skipping");
10660                        }
10661                    }
10662
10663                    if ((scanFlags & SCAN_BOOTING) == 0) {
10664                        // If we are not booting, we need to update any applications
10665                        // that are clients of our shared library.  If we are booting,
10666                        // this will all be done once the scan is complete.
10667                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10668                    }
10669                }
10670            }
10671        }
10672
10673        if ((scanFlags & SCAN_BOOTING) != 0) {
10674            // No apps can run during boot scan, so they don't need to be frozen
10675        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10676            // Caller asked to not kill app, so it's probably not frozen
10677        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10678            // Caller asked us to ignore frozen check for some reason; they
10679            // probably didn't know the package name
10680        } else {
10681            // We're doing major surgery on this package, so it better be frozen
10682            // right now to keep it from launching
10683            checkPackageFrozen(pkgName);
10684        }
10685
10686        // Also need to kill any apps that are dependent on the library.
10687        if (clientLibPkgs != null) {
10688            for (int i=0; i<clientLibPkgs.size(); i++) {
10689                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10690                killApplication(clientPkg.applicationInfo.packageName,
10691                        clientPkg.applicationInfo.uid, "update lib");
10692            }
10693        }
10694
10695        // writer
10696        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10697
10698        synchronized (mPackages) {
10699            // We don't expect installation to fail beyond this point
10700
10701            // Add the new setting to mSettings
10702            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10703            // Add the new setting to mPackages
10704            mPackages.put(pkg.applicationInfo.packageName, pkg);
10705            // Make sure we don't accidentally delete its data.
10706            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10707            while (iter.hasNext()) {
10708                PackageCleanItem item = iter.next();
10709                if (pkgName.equals(item.packageName)) {
10710                    iter.remove();
10711                }
10712            }
10713
10714            // Add the package's KeySets to the global KeySetManagerService
10715            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10716            ksms.addScannedPackageLPw(pkg);
10717
10718            int N = pkg.providers.size();
10719            StringBuilder r = null;
10720            int i;
10721            for (i=0; i<N; i++) {
10722                PackageParser.Provider p = pkg.providers.get(i);
10723                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10724                        p.info.processName);
10725                mProviders.addProvider(p);
10726                p.syncable = p.info.isSyncable;
10727                if (p.info.authority != null) {
10728                    String names[] = p.info.authority.split(";");
10729                    p.info.authority = null;
10730                    for (int j = 0; j < names.length; j++) {
10731                        if (j == 1 && p.syncable) {
10732                            // We only want the first authority for a provider to possibly be
10733                            // syncable, so if we already added this provider using a different
10734                            // authority clear the syncable flag. We copy the provider before
10735                            // changing it because the mProviders object contains a reference
10736                            // to a provider that we don't want to change.
10737                            // Only do this for the second authority since the resulting provider
10738                            // object can be the same for all future authorities for this provider.
10739                            p = new PackageParser.Provider(p);
10740                            p.syncable = false;
10741                        }
10742                        if (!mProvidersByAuthority.containsKey(names[j])) {
10743                            mProvidersByAuthority.put(names[j], p);
10744                            if (p.info.authority == null) {
10745                                p.info.authority = names[j];
10746                            } else {
10747                                p.info.authority = p.info.authority + ";" + names[j];
10748                            }
10749                            if (DEBUG_PACKAGE_SCANNING) {
10750                                if (chatty)
10751                                    Log.d(TAG, "Registered content provider: " + names[j]
10752                                            + ", className = " + p.info.name + ", isSyncable = "
10753                                            + p.info.isSyncable);
10754                            }
10755                        } else {
10756                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10757                            Slog.w(TAG, "Skipping provider name " + names[j] +
10758                                    " (in package " + pkg.applicationInfo.packageName +
10759                                    "): name already used by "
10760                                    + ((other != null && other.getComponentName() != null)
10761                                            ? other.getComponentName().getPackageName() : "?"));
10762                        }
10763                    }
10764                }
10765                if (chatty) {
10766                    if (r == null) {
10767                        r = new StringBuilder(256);
10768                    } else {
10769                        r.append(' ');
10770                    }
10771                    r.append(p.info.name);
10772                }
10773            }
10774            if (r != null) {
10775                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10776            }
10777
10778            N = pkg.services.size();
10779            r = null;
10780            for (i=0; i<N; i++) {
10781                PackageParser.Service s = pkg.services.get(i);
10782                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10783                        s.info.processName);
10784                mServices.addService(s);
10785                if (chatty) {
10786                    if (r == null) {
10787                        r = new StringBuilder(256);
10788                    } else {
10789                        r.append(' ');
10790                    }
10791                    r.append(s.info.name);
10792                }
10793            }
10794            if (r != null) {
10795                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10796            }
10797
10798            N = pkg.receivers.size();
10799            r = null;
10800            for (i=0; i<N; i++) {
10801                PackageParser.Activity a = pkg.receivers.get(i);
10802                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10803                        a.info.processName);
10804                mReceivers.addActivity(a, "receiver");
10805                if (chatty) {
10806                    if (r == null) {
10807                        r = new StringBuilder(256);
10808                    } else {
10809                        r.append(' ');
10810                    }
10811                    r.append(a.info.name);
10812                }
10813            }
10814            if (r != null) {
10815                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10816            }
10817
10818            N = pkg.activities.size();
10819            r = null;
10820            for (i=0; i<N; i++) {
10821                PackageParser.Activity a = pkg.activities.get(i);
10822                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10823                        a.info.processName);
10824                mActivities.addActivity(a, "activity");
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, "  Activities: " + r);
10836            }
10837
10838            // Don't allow ephemeral applications to define new permissions groups.
10839            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10840                Slog.w(TAG, "Permission groups from package " + pkg.packageName
10841                        + " ignored: instant apps cannot define new permission groups.");
10842            } else {
10843                mPermissionManager.addAllPermissionGroups(pkg, chatty);
10844            }
10845
10846            // Don't allow ephemeral applications to define new permissions.
10847            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10848                Slog.w(TAG, "Permissions from package " + pkg.packageName
10849                        + " ignored: instant apps cannot define new permissions.");
10850            } else {
10851                mPermissionManager.addAllPermissions(pkg, chatty);
10852            }
10853
10854            N = pkg.instrumentation.size();
10855            r = null;
10856            for (i=0; i<N; i++) {
10857                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10858                a.info.packageName = pkg.applicationInfo.packageName;
10859                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10860                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10861                a.info.splitNames = pkg.splitNames;
10862                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10863                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10864                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10865                a.info.dataDir = pkg.applicationInfo.dataDir;
10866                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10867                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10868                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10869                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10870                mInstrumentation.put(a.getComponentName(), a);
10871                if (chatty) {
10872                    if (r == null) {
10873                        r = new StringBuilder(256);
10874                    } else {
10875                        r.append(' ');
10876                    }
10877                    r.append(a.info.name);
10878                }
10879            }
10880            if (r != null) {
10881                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10882            }
10883
10884            if (pkg.protectedBroadcasts != null) {
10885                N = pkg.protectedBroadcasts.size();
10886                synchronized (mProtectedBroadcasts) {
10887                    for (i = 0; i < N; i++) {
10888                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10889                    }
10890                }
10891            }
10892        }
10893
10894        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10895    }
10896
10897    /**
10898     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10899     * is derived purely on the basis of the contents of {@code scanFile} and
10900     * {@code cpuAbiOverride}.
10901     *
10902     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10903     */
10904    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
10905            boolean extractLibs, File appLib32InstallDir)
10906                    throws PackageManagerException {
10907        // Give ourselves some initial paths; we'll come back for another
10908        // pass once we've determined ABI below.
10909        setNativeLibraryPaths(pkg, appLib32InstallDir);
10910
10911        // We would never need to extract libs for forward-locked and external packages,
10912        // since the container service will do it for us. We shouldn't attempt to
10913        // extract libs from system app when it was not updated.
10914        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10915                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10916            extractLibs = false;
10917        }
10918
10919        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10920        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10921
10922        NativeLibraryHelper.Handle handle = null;
10923        try {
10924            handle = NativeLibraryHelper.Handle.create(pkg);
10925            // TODO(multiArch): This can be null for apps that didn't go through the
10926            // usual installation process. We can calculate it again, like we
10927            // do during install time.
10928            //
10929            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10930            // unnecessary.
10931            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10932
10933            // Null out the abis so that they can be recalculated.
10934            pkg.applicationInfo.primaryCpuAbi = null;
10935            pkg.applicationInfo.secondaryCpuAbi = null;
10936            if (isMultiArch(pkg.applicationInfo)) {
10937                // Warn if we've set an abiOverride for multi-lib packages..
10938                // By definition, we need to copy both 32 and 64 bit libraries for
10939                // such packages.
10940                if (pkg.cpuAbiOverride != null
10941                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10942                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10943                }
10944
10945                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10946                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10947                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10948                    if (extractLibs) {
10949                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10950                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10951                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10952                                useIsaSpecificSubdirs);
10953                    } else {
10954                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10955                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10956                    }
10957                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10958                }
10959
10960                // Shared library native code should be in the APK zip aligned
10961                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
10962                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10963                            "Shared library native lib extraction not supported");
10964                }
10965
10966                maybeThrowExceptionForMultiArchCopy(
10967                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10968
10969                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10970                    if (extractLibs) {
10971                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10972                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10973                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10974                                useIsaSpecificSubdirs);
10975                    } else {
10976                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10977                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10978                    }
10979                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10980                }
10981
10982                maybeThrowExceptionForMultiArchCopy(
10983                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10984
10985                if (abi64 >= 0) {
10986                    // Shared library native libs should be in the APK zip aligned
10987                    if (extractLibs && pkg.isLibrary()) {
10988                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10989                                "Shared library native lib extraction not supported");
10990                    }
10991                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10992                }
10993
10994                if (abi32 >= 0) {
10995                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10996                    if (abi64 >= 0) {
10997                        if (pkg.use32bitAbi) {
10998                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10999                            pkg.applicationInfo.primaryCpuAbi = abi;
11000                        } else {
11001                            pkg.applicationInfo.secondaryCpuAbi = abi;
11002                        }
11003                    } else {
11004                        pkg.applicationInfo.primaryCpuAbi = abi;
11005                    }
11006                }
11007            } else {
11008                String[] abiList = (cpuAbiOverride != null) ?
11009                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11010
11011                // Enable gross and lame hacks for apps that are built with old
11012                // SDK tools. We must scan their APKs for renderscript bitcode and
11013                // not launch them if it's present. Don't bother checking on devices
11014                // that don't have 64 bit support.
11015                boolean needsRenderScriptOverride = false;
11016                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11017                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11018                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11019                    needsRenderScriptOverride = true;
11020                }
11021
11022                final int copyRet;
11023                if (extractLibs) {
11024                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11025                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11026                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11027                } else {
11028                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11029                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11030                }
11031                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11032
11033                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11034                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11035                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11036                }
11037
11038                if (copyRet >= 0) {
11039                    // Shared libraries that have native libs must be multi-architecture
11040                    if (pkg.isLibrary()) {
11041                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11042                                "Shared library with native libs must be multiarch");
11043                    }
11044                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11045                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11046                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11047                } else if (needsRenderScriptOverride) {
11048                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11049                }
11050            }
11051        } catch (IOException ioe) {
11052            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11053        } finally {
11054            IoUtils.closeQuietly(handle);
11055        }
11056
11057        // Now that we've calculated the ABIs and determined if it's an internal app,
11058        // we will go ahead and populate the nativeLibraryPath.
11059        setNativeLibraryPaths(pkg, appLib32InstallDir);
11060    }
11061
11062    /**
11063     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11064     * i.e, so that all packages can be run inside a single process if required.
11065     *
11066     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11067     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11068     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11069     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11070     * updating a package that belongs to a shared user.
11071     *
11072     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11073     * adds unnecessary complexity.
11074     */
11075    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11076            PackageParser.Package scannedPackage) {
11077        String requiredInstructionSet = null;
11078        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11079            requiredInstructionSet = VMRuntime.getInstructionSet(
11080                     scannedPackage.applicationInfo.primaryCpuAbi);
11081        }
11082
11083        PackageSetting requirer = null;
11084        for (PackageSetting ps : packagesForUser) {
11085            // If packagesForUser contains scannedPackage, we skip it. This will happen
11086            // when scannedPackage is an update of an existing package. Without this check,
11087            // we will never be able to change the ABI of any package belonging to a shared
11088            // user, even if it's compatible with other packages.
11089            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11090                if (ps.primaryCpuAbiString == null) {
11091                    continue;
11092                }
11093
11094                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11095                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11096                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11097                    // this but there's not much we can do.
11098                    String errorMessage = "Instruction set mismatch, "
11099                            + ((requirer == null) ? "[caller]" : requirer)
11100                            + " requires " + requiredInstructionSet + " whereas " + ps
11101                            + " requires " + instructionSet;
11102                    Slog.w(TAG, errorMessage);
11103                }
11104
11105                if (requiredInstructionSet == null) {
11106                    requiredInstructionSet = instructionSet;
11107                    requirer = ps;
11108                }
11109            }
11110        }
11111
11112        if (requiredInstructionSet != null) {
11113            String adjustedAbi;
11114            if (requirer != null) {
11115                // requirer != null implies that either scannedPackage was null or that scannedPackage
11116                // did not require an ABI, in which case we have to adjust scannedPackage to match
11117                // the ABI of the set (which is the same as requirer's ABI)
11118                adjustedAbi = requirer.primaryCpuAbiString;
11119                if (scannedPackage != null) {
11120                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11121                }
11122            } else {
11123                // requirer == null implies that we're updating all ABIs in the set to
11124                // match scannedPackage.
11125                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11126            }
11127
11128            for (PackageSetting ps : packagesForUser) {
11129                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11130                    if (ps.primaryCpuAbiString != null) {
11131                        continue;
11132                    }
11133
11134                    ps.primaryCpuAbiString = adjustedAbi;
11135                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11136                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11137                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11138                        if (DEBUG_ABI_SELECTION) {
11139                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11140                                    + " (requirer="
11141                                    + (requirer != null ? requirer.pkg : "null")
11142                                    + ", scannedPackage="
11143                                    + (scannedPackage != null ? scannedPackage : "null")
11144                                    + ")");
11145                        }
11146                        try {
11147                            mInstaller.rmdex(ps.codePathString,
11148                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11149                        } catch (InstallerException ignored) {
11150                        }
11151                    }
11152                }
11153            }
11154        }
11155    }
11156
11157    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11158        synchronized (mPackages) {
11159            mResolverReplaced = true;
11160            // Set up information for custom user intent resolution activity.
11161            mResolveActivity.applicationInfo = pkg.applicationInfo;
11162            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11163            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11164            mResolveActivity.processName = pkg.applicationInfo.packageName;
11165            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11166            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11167                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11168            mResolveActivity.theme = 0;
11169            mResolveActivity.exported = true;
11170            mResolveActivity.enabled = true;
11171            mResolveInfo.activityInfo = mResolveActivity;
11172            mResolveInfo.priority = 0;
11173            mResolveInfo.preferredOrder = 0;
11174            mResolveInfo.match = 0;
11175            mResolveComponentName = mCustomResolverComponentName;
11176            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11177                    mResolveComponentName);
11178        }
11179    }
11180
11181    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11182        if (installerActivity == null) {
11183            if (DEBUG_EPHEMERAL) {
11184                Slog.d(TAG, "Clear ephemeral installer activity");
11185            }
11186            mInstantAppInstallerActivity = null;
11187            return;
11188        }
11189
11190        if (DEBUG_EPHEMERAL) {
11191            Slog.d(TAG, "Set ephemeral installer activity: "
11192                    + installerActivity.getComponentName());
11193        }
11194        // Set up information for ephemeral installer activity
11195        mInstantAppInstallerActivity = installerActivity;
11196        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11197                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11198        mInstantAppInstallerActivity.exported = true;
11199        mInstantAppInstallerActivity.enabled = true;
11200        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11201        mInstantAppInstallerInfo.priority = 0;
11202        mInstantAppInstallerInfo.preferredOrder = 1;
11203        mInstantAppInstallerInfo.isDefault = true;
11204        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11205                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11206    }
11207
11208    private static String calculateBundledApkRoot(final String codePathString) {
11209        final File codePath = new File(codePathString);
11210        final File codeRoot;
11211        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11212            codeRoot = Environment.getRootDirectory();
11213        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11214            codeRoot = Environment.getOemDirectory();
11215        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11216            codeRoot = Environment.getVendorDirectory();
11217        } else {
11218            // Unrecognized code path; take its top real segment as the apk root:
11219            // e.g. /something/app/blah.apk => /something
11220            try {
11221                File f = codePath.getCanonicalFile();
11222                File parent = f.getParentFile();    // non-null because codePath is a file
11223                File tmp;
11224                while ((tmp = parent.getParentFile()) != null) {
11225                    f = parent;
11226                    parent = tmp;
11227                }
11228                codeRoot = f;
11229                Slog.w(TAG, "Unrecognized code path "
11230                        + codePath + " - using " + codeRoot);
11231            } catch (IOException e) {
11232                // Can't canonicalize the code path -- shenanigans?
11233                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11234                return Environment.getRootDirectory().getPath();
11235            }
11236        }
11237        return codeRoot.getPath();
11238    }
11239
11240    /**
11241     * Derive and set the location of native libraries for the given package,
11242     * which varies depending on where and how the package was installed.
11243     */
11244    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11245        final ApplicationInfo info = pkg.applicationInfo;
11246        final String codePath = pkg.codePath;
11247        final File codeFile = new File(codePath);
11248        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11249        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11250
11251        info.nativeLibraryRootDir = null;
11252        info.nativeLibraryRootRequiresIsa = false;
11253        info.nativeLibraryDir = null;
11254        info.secondaryNativeLibraryDir = null;
11255
11256        if (isApkFile(codeFile)) {
11257            // Monolithic install
11258            if (bundledApp) {
11259                // If "/system/lib64/apkname" exists, assume that is the per-package
11260                // native library directory to use; otherwise use "/system/lib/apkname".
11261                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11262                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11263                        getPrimaryInstructionSet(info));
11264
11265                // This is a bundled system app so choose the path based on the ABI.
11266                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11267                // is just the default path.
11268                final String apkName = deriveCodePathName(codePath);
11269                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11270                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11271                        apkName).getAbsolutePath();
11272
11273                if (info.secondaryCpuAbi != null) {
11274                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11275                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11276                            secondaryLibDir, apkName).getAbsolutePath();
11277                }
11278            } else if (asecApp) {
11279                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11280                        .getAbsolutePath();
11281            } else {
11282                final String apkName = deriveCodePathName(codePath);
11283                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11284                        .getAbsolutePath();
11285            }
11286
11287            info.nativeLibraryRootRequiresIsa = false;
11288            info.nativeLibraryDir = info.nativeLibraryRootDir;
11289        } else {
11290            // Cluster install
11291            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11292            info.nativeLibraryRootRequiresIsa = true;
11293
11294            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11295                    getPrimaryInstructionSet(info)).getAbsolutePath();
11296
11297            if (info.secondaryCpuAbi != null) {
11298                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11299                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11300            }
11301        }
11302    }
11303
11304    /**
11305     * Calculate the abis and roots for a bundled app. These can uniquely
11306     * be determined from the contents of the system partition, i.e whether
11307     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11308     * of this information, and instead assume that the system was built
11309     * sensibly.
11310     */
11311    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11312                                           PackageSetting pkgSetting) {
11313        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11314
11315        // If "/system/lib64/apkname" exists, assume that is the per-package
11316        // native library directory to use; otherwise use "/system/lib/apkname".
11317        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11318        setBundledAppAbi(pkg, apkRoot, apkName);
11319        // pkgSetting might be null during rescan following uninstall of updates
11320        // to a bundled app, so accommodate that possibility.  The settings in
11321        // that case will be established later from the parsed package.
11322        //
11323        // If the settings aren't null, sync them up with what we've just derived.
11324        // note that apkRoot isn't stored in the package settings.
11325        if (pkgSetting != null) {
11326            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11327            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11328        }
11329    }
11330
11331    /**
11332     * Deduces the ABI of a bundled app and sets the relevant fields on the
11333     * parsed pkg object.
11334     *
11335     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11336     *        under which system libraries are installed.
11337     * @param apkName the name of the installed package.
11338     */
11339    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11340        final File codeFile = new File(pkg.codePath);
11341
11342        final boolean has64BitLibs;
11343        final boolean has32BitLibs;
11344        if (isApkFile(codeFile)) {
11345            // Monolithic install
11346            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11347            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11348        } else {
11349            // Cluster install
11350            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11351            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11352                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11353                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11354                has64BitLibs = (new File(rootDir, isa)).exists();
11355            } else {
11356                has64BitLibs = false;
11357            }
11358            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11359                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11360                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11361                has32BitLibs = (new File(rootDir, isa)).exists();
11362            } else {
11363                has32BitLibs = false;
11364            }
11365        }
11366
11367        if (has64BitLibs && !has32BitLibs) {
11368            // The package has 64 bit libs, but not 32 bit libs. Its primary
11369            // ABI should be 64 bit. We can safely assume here that the bundled
11370            // native libraries correspond to the most preferred ABI in the list.
11371
11372            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11373            pkg.applicationInfo.secondaryCpuAbi = null;
11374        } else if (has32BitLibs && !has64BitLibs) {
11375            // The package has 32 bit libs but not 64 bit libs. Its primary
11376            // ABI should be 32 bit.
11377
11378            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11379            pkg.applicationInfo.secondaryCpuAbi = null;
11380        } else if (has32BitLibs && has64BitLibs) {
11381            // The application has both 64 and 32 bit bundled libraries. We check
11382            // here that the app declares multiArch support, and warn if it doesn't.
11383            //
11384            // We will be lenient here and record both ABIs. The primary will be the
11385            // ABI that's higher on the list, i.e, a device that's configured to prefer
11386            // 64 bit apps will see a 64 bit primary ABI,
11387
11388            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11389                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11390            }
11391
11392            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11393                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11394                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11395            } else {
11396                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11397                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11398            }
11399        } else {
11400            pkg.applicationInfo.primaryCpuAbi = null;
11401            pkg.applicationInfo.secondaryCpuAbi = null;
11402        }
11403    }
11404
11405    private void killApplication(String pkgName, int appId, String reason) {
11406        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11407    }
11408
11409    private void killApplication(String pkgName, int appId, int userId, String reason) {
11410        // Request the ActivityManager to kill the process(only for existing packages)
11411        // so that we do not end up in a confused state while the user is still using the older
11412        // version of the application while the new one gets installed.
11413        final long token = Binder.clearCallingIdentity();
11414        try {
11415            IActivityManager am = ActivityManager.getService();
11416            if (am != null) {
11417                try {
11418                    am.killApplication(pkgName, appId, userId, reason);
11419                } catch (RemoteException e) {
11420                }
11421            }
11422        } finally {
11423            Binder.restoreCallingIdentity(token);
11424        }
11425    }
11426
11427    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11428        // Remove the parent package setting
11429        PackageSetting ps = (PackageSetting) pkg.mExtras;
11430        if (ps != null) {
11431            removePackageLI(ps, chatty);
11432        }
11433        // Remove the child package setting
11434        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11435        for (int i = 0; i < childCount; i++) {
11436            PackageParser.Package childPkg = pkg.childPackages.get(i);
11437            ps = (PackageSetting) childPkg.mExtras;
11438            if (ps != null) {
11439                removePackageLI(ps, chatty);
11440            }
11441        }
11442    }
11443
11444    void removePackageLI(PackageSetting ps, boolean chatty) {
11445        if (DEBUG_INSTALL) {
11446            if (chatty)
11447                Log.d(TAG, "Removing package " + ps.name);
11448        }
11449
11450        // writer
11451        synchronized (mPackages) {
11452            mPackages.remove(ps.name);
11453            final PackageParser.Package pkg = ps.pkg;
11454            if (pkg != null) {
11455                cleanPackageDataStructuresLILPw(pkg, chatty);
11456            }
11457        }
11458    }
11459
11460    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11461        if (DEBUG_INSTALL) {
11462            if (chatty)
11463                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11464        }
11465
11466        // writer
11467        synchronized (mPackages) {
11468            // Remove the parent package
11469            mPackages.remove(pkg.applicationInfo.packageName);
11470            cleanPackageDataStructuresLILPw(pkg, chatty);
11471
11472            // Remove the child packages
11473            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11474            for (int i = 0; i < childCount; i++) {
11475                PackageParser.Package childPkg = pkg.childPackages.get(i);
11476                mPackages.remove(childPkg.applicationInfo.packageName);
11477                cleanPackageDataStructuresLILPw(childPkg, chatty);
11478            }
11479        }
11480    }
11481
11482    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11483        int N = pkg.providers.size();
11484        StringBuilder r = null;
11485        int i;
11486        for (i=0; i<N; i++) {
11487            PackageParser.Provider p = pkg.providers.get(i);
11488            mProviders.removeProvider(p);
11489            if (p.info.authority == null) {
11490
11491                /* There was another ContentProvider with this authority when
11492                 * this app was installed so this authority is null,
11493                 * Ignore it as we don't have to unregister the provider.
11494                 */
11495                continue;
11496            }
11497            String names[] = p.info.authority.split(";");
11498            for (int j = 0; j < names.length; j++) {
11499                if (mProvidersByAuthority.get(names[j]) == p) {
11500                    mProvidersByAuthority.remove(names[j]);
11501                    if (DEBUG_REMOVE) {
11502                        if (chatty)
11503                            Log.d(TAG, "Unregistered content provider: " + names[j]
11504                                    + ", className = " + p.info.name + ", isSyncable = "
11505                                    + p.info.isSyncable);
11506                    }
11507                }
11508            }
11509            if (DEBUG_REMOVE && chatty) {
11510                if (r == null) {
11511                    r = new StringBuilder(256);
11512                } else {
11513                    r.append(' ');
11514                }
11515                r.append(p.info.name);
11516            }
11517        }
11518        if (r != null) {
11519            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11520        }
11521
11522        N = pkg.services.size();
11523        r = null;
11524        for (i=0; i<N; i++) {
11525            PackageParser.Service s = pkg.services.get(i);
11526            mServices.removeService(s);
11527            if (chatty) {
11528                if (r == null) {
11529                    r = new StringBuilder(256);
11530                } else {
11531                    r.append(' ');
11532                }
11533                r.append(s.info.name);
11534            }
11535        }
11536        if (r != null) {
11537            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11538        }
11539
11540        N = pkg.receivers.size();
11541        r = null;
11542        for (i=0; i<N; i++) {
11543            PackageParser.Activity a = pkg.receivers.get(i);
11544            mReceivers.removeActivity(a, "receiver");
11545            if (DEBUG_REMOVE && chatty) {
11546                if (r == null) {
11547                    r = new StringBuilder(256);
11548                } else {
11549                    r.append(' ');
11550                }
11551                r.append(a.info.name);
11552            }
11553        }
11554        if (r != null) {
11555            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11556        }
11557
11558        N = pkg.activities.size();
11559        r = null;
11560        for (i=0; i<N; i++) {
11561            PackageParser.Activity a = pkg.activities.get(i);
11562            mActivities.removeActivity(a, "activity");
11563            if (DEBUG_REMOVE && chatty) {
11564                if (r == null) {
11565                    r = new StringBuilder(256);
11566                } else {
11567                    r.append(' ');
11568                }
11569                r.append(a.info.name);
11570            }
11571        }
11572        if (r != null) {
11573            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11574        }
11575
11576        mPermissionManager.removeAllPermissions(pkg, chatty);
11577
11578        N = pkg.instrumentation.size();
11579        r = null;
11580        for (i=0; i<N; i++) {
11581            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11582            mInstrumentation.remove(a.getComponentName());
11583            if (DEBUG_REMOVE && chatty) {
11584                if (r == null) {
11585                    r = new StringBuilder(256);
11586                } else {
11587                    r.append(' ');
11588                }
11589                r.append(a.info.name);
11590            }
11591        }
11592        if (r != null) {
11593            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11594        }
11595
11596        r = null;
11597        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11598            // Only system apps can hold shared libraries.
11599            if (pkg.libraryNames != null) {
11600                for (i = 0; i < pkg.libraryNames.size(); i++) {
11601                    String name = pkg.libraryNames.get(i);
11602                    if (removeSharedLibraryLPw(name, 0)) {
11603                        if (DEBUG_REMOVE && chatty) {
11604                            if (r == null) {
11605                                r = new StringBuilder(256);
11606                            } else {
11607                                r.append(' ');
11608                            }
11609                            r.append(name);
11610                        }
11611                    }
11612                }
11613            }
11614        }
11615
11616        r = null;
11617
11618        // Any package can hold static shared libraries.
11619        if (pkg.staticSharedLibName != null) {
11620            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11621                if (DEBUG_REMOVE && chatty) {
11622                    if (r == null) {
11623                        r = new StringBuilder(256);
11624                    } else {
11625                        r.append(' ');
11626                    }
11627                    r.append(pkg.staticSharedLibName);
11628                }
11629            }
11630        }
11631
11632        if (r != null) {
11633            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11634        }
11635    }
11636
11637
11638    final class ActivityIntentResolver
11639            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11640        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11641                boolean defaultOnly, int userId) {
11642            if (!sUserManager.exists(userId)) return null;
11643            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11644            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11645        }
11646
11647        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11648                int userId) {
11649            if (!sUserManager.exists(userId)) return null;
11650            mFlags = flags;
11651            return super.queryIntent(intent, resolvedType,
11652                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11653                    userId);
11654        }
11655
11656        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11657                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11658            if (!sUserManager.exists(userId)) return null;
11659            if (packageActivities == null) {
11660                return null;
11661            }
11662            mFlags = flags;
11663            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11664            final int N = packageActivities.size();
11665            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11666                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11667
11668            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11669            for (int i = 0; i < N; ++i) {
11670                intentFilters = packageActivities.get(i).intents;
11671                if (intentFilters != null && intentFilters.size() > 0) {
11672                    PackageParser.ActivityIntentInfo[] array =
11673                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11674                    intentFilters.toArray(array);
11675                    listCut.add(array);
11676                }
11677            }
11678            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11679        }
11680
11681        /**
11682         * Finds a privileged activity that matches the specified activity names.
11683         */
11684        private PackageParser.Activity findMatchingActivity(
11685                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11686            for (PackageParser.Activity sysActivity : activityList) {
11687                if (sysActivity.info.name.equals(activityInfo.name)) {
11688                    return sysActivity;
11689                }
11690                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11691                    return sysActivity;
11692                }
11693                if (sysActivity.info.targetActivity != null) {
11694                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11695                        return sysActivity;
11696                    }
11697                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11698                        return sysActivity;
11699                    }
11700                }
11701            }
11702            return null;
11703        }
11704
11705        public class IterGenerator<E> {
11706            public Iterator<E> generate(ActivityIntentInfo info) {
11707                return null;
11708            }
11709        }
11710
11711        public class ActionIterGenerator extends IterGenerator<String> {
11712            @Override
11713            public Iterator<String> generate(ActivityIntentInfo info) {
11714                return info.actionsIterator();
11715            }
11716        }
11717
11718        public class CategoriesIterGenerator extends IterGenerator<String> {
11719            @Override
11720            public Iterator<String> generate(ActivityIntentInfo info) {
11721                return info.categoriesIterator();
11722            }
11723        }
11724
11725        public class SchemesIterGenerator extends IterGenerator<String> {
11726            @Override
11727            public Iterator<String> generate(ActivityIntentInfo info) {
11728                return info.schemesIterator();
11729            }
11730        }
11731
11732        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11733            @Override
11734            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11735                return info.authoritiesIterator();
11736            }
11737        }
11738
11739        /**
11740         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11741         * MODIFIED. Do not pass in a list that should not be changed.
11742         */
11743        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11744                IterGenerator<T> generator, Iterator<T> searchIterator) {
11745            // loop through the set of actions; every one must be found in the intent filter
11746            while (searchIterator.hasNext()) {
11747                // we must have at least one filter in the list to consider a match
11748                if (intentList.size() == 0) {
11749                    break;
11750                }
11751
11752                final T searchAction = searchIterator.next();
11753
11754                // loop through the set of intent filters
11755                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11756                while (intentIter.hasNext()) {
11757                    final ActivityIntentInfo intentInfo = intentIter.next();
11758                    boolean selectionFound = false;
11759
11760                    // loop through the intent filter's selection criteria; at least one
11761                    // of them must match the searched criteria
11762                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11763                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11764                        final T intentSelection = intentSelectionIter.next();
11765                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11766                            selectionFound = true;
11767                            break;
11768                        }
11769                    }
11770
11771                    // the selection criteria wasn't found in this filter's set; this filter
11772                    // is not a potential match
11773                    if (!selectionFound) {
11774                        intentIter.remove();
11775                    }
11776                }
11777            }
11778        }
11779
11780        private boolean isProtectedAction(ActivityIntentInfo filter) {
11781            final Iterator<String> actionsIter = filter.actionsIterator();
11782            while (actionsIter != null && actionsIter.hasNext()) {
11783                final String filterAction = actionsIter.next();
11784                if (PROTECTED_ACTIONS.contains(filterAction)) {
11785                    return true;
11786                }
11787            }
11788            return false;
11789        }
11790
11791        /**
11792         * Adjusts the priority of the given intent filter according to policy.
11793         * <p>
11794         * <ul>
11795         * <li>The priority for non privileged applications is capped to '0'</li>
11796         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11797         * <li>The priority for unbundled updates to privileged applications is capped to the
11798         *      priority defined on the system partition</li>
11799         * </ul>
11800         * <p>
11801         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11802         * allowed to obtain any priority on any action.
11803         */
11804        private void adjustPriority(
11805                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11806            // nothing to do; priority is fine as-is
11807            if (intent.getPriority() <= 0) {
11808                return;
11809            }
11810
11811            final ActivityInfo activityInfo = intent.activity.info;
11812            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11813
11814            final boolean privilegedApp =
11815                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11816            if (!privilegedApp) {
11817                // non-privileged applications can never define a priority >0
11818                if (DEBUG_FILTERS) {
11819                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
11820                            + " package: " + applicationInfo.packageName
11821                            + " activity: " + intent.activity.className
11822                            + " origPrio: " + intent.getPriority());
11823                }
11824                intent.setPriority(0);
11825                return;
11826            }
11827
11828            if (systemActivities == null) {
11829                // the system package is not disabled; we're parsing the system partition
11830                if (isProtectedAction(intent)) {
11831                    if (mDeferProtectedFilters) {
11832                        // We can't deal with these just yet. No component should ever obtain a
11833                        // >0 priority for a protected actions, with ONE exception -- the setup
11834                        // wizard. The setup wizard, however, cannot be known until we're able to
11835                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11836                        // until all intent filters have been processed. Chicken, meet egg.
11837                        // Let the filter temporarily have a high priority and rectify the
11838                        // priorities after all system packages have been scanned.
11839                        mProtectedFilters.add(intent);
11840                        if (DEBUG_FILTERS) {
11841                            Slog.i(TAG, "Protected action; save for later;"
11842                                    + " package: " + applicationInfo.packageName
11843                                    + " activity: " + intent.activity.className
11844                                    + " origPrio: " + intent.getPriority());
11845                        }
11846                        return;
11847                    } else {
11848                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11849                            Slog.i(TAG, "No setup wizard;"
11850                                + " All protected intents capped to priority 0");
11851                        }
11852                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11853                            if (DEBUG_FILTERS) {
11854                                Slog.i(TAG, "Found setup wizard;"
11855                                    + " allow priority " + intent.getPriority() + ";"
11856                                    + " package: " + intent.activity.info.packageName
11857                                    + " activity: " + intent.activity.className
11858                                    + " priority: " + intent.getPriority());
11859                            }
11860                            // setup wizard gets whatever it wants
11861                            return;
11862                        }
11863                        if (DEBUG_FILTERS) {
11864                            Slog.i(TAG, "Protected action; cap priority to 0;"
11865                                    + " package: " + intent.activity.info.packageName
11866                                    + " activity: " + intent.activity.className
11867                                    + " origPrio: " + intent.getPriority());
11868                        }
11869                        intent.setPriority(0);
11870                        return;
11871                    }
11872                }
11873                // privileged apps on the system image get whatever priority they request
11874                return;
11875            }
11876
11877            // privileged app unbundled update ... try to find the same activity
11878            final PackageParser.Activity foundActivity =
11879                    findMatchingActivity(systemActivities, activityInfo);
11880            if (foundActivity == null) {
11881                // this is a new activity; it cannot obtain >0 priority
11882                if (DEBUG_FILTERS) {
11883                    Slog.i(TAG, "New activity; cap priority to 0;"
11884                            + " package: " + applicationInfo.packageName
11885                            + " activity: " + intent.activity.className
11886                            + " origPrio: " + intent.getPriority());
11887                }
11888                intent.setPriority(0);
11889                return;
11890            }
11891
11892            // found activity, now check for filter equivalence
11893
11894            // a shallow copy is enough; we modify the list, not its contents
11895            final List<ActivityIntentInfo> intentListCopy =
11896                    new ArrayList<>(foundActivity.intents);
11897            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11898
11899            // find matching action subsets
11900            final Iterator<String> actionsIterator = intent.actionsIterator();
11901            if (actionsIterator != null) {
11902                getIntentListSubset(
11903                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11904                if (intentListCopy.size() == 0) {
11905                    // no more intents to match; we're not equivalent
11906                    if (DEBUG_FILTERS) {
11907                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11908                                + " package: " + applicationInfo.packageName
11909                                + " activity: " + intent.activity.className
11910                                + " origPrio: " + intent.getPriority());
11911                    }
11912                    intent.setPriority(0);
11913                    return;
11914                }
11915            }
11916
11917            // find matching category subsets
11918            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11919            if (categoriesIterator != null) {
11920                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11921                        categoriesIterator);
11922                if (intentListCopy.size() == 0) {
11923                    // no more intents to match; we're not equivalent
11924                    if (DEBUG_FILTERS) {
11925                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11926                                + " package: " + applicationInfo.packageName
11927                                + " activity: " + intent.activity.className
11928                                + " origPrio: " + intent.getPriority());
11929                    }
11930                    intent.setPriority(0);
11931                    return;
11932                }
11933            }
11934
11935            // find matching schemes subsets
11936            final Iterator<String> schemesIterator = intent.schemesIterator();
11937            if (schemesIterator != null) {
11938                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11939                        schemesIterator);
11940                if (intentListCopy.size() == 0) {
11941                    // no more intents to match; we're not equivalent
11942                    if (DEBUG_FILTERS) {
11943                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11944                                + " package: " + applicationInfo.packageName
11945                                + " activity: " + intent.activity.className
11946                                + " origPrio: " + intent.getPriority());
11947                    }
11948                    intent.setPriority(0);
11949                    return;
11950                }
11951            }
11952
11953            // find matching authorities subsets
11954            final Iterator<IntentFilter.AuthorityEntry>
11955                    authoritiesIterator = intent.authoritiesIterator();
11956            if (authoritiesIterator != null) {
11957                getIntentListSubset(intentListCopy,
11958                        new AuthoritiesIterGenerator(),
11959                        authoritiesIterator);
11960                if (intentListCopy.size() == 0) {
11961                    // no more intents to match; we're not equivalent
11962                    if (DEBUG_FILTERS) {
11963                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11964                                + " package: " + applicationInfo.packageName
11965                                + " activity: " + intent.activity.className
11966                                + " origPrio: " + intent.getPriority());
11967                    }
11968                    intent.setPriority(0);
11969                    return;
11970                }
11971            }
11972
11973            // we found matching filter(s); app gets the max priority of all intents
11974            int cappedPriority = 0;
11975            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11976                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11977            }
11978            if (intent.getPriority() > cappedPriority) {
11979                if (DEBUG_FILTERS) {
11980                    Slog.i(TAG, "Found matching filter(s);"
11981                            + " cap priority to " + cappedPriority + ";"
11982                            + " package: " + applicationInfo.packageName
11983                            + " activity: " + intent.activity.className
11984                            + " origPrio: " + intent.getPriority());
11985                }
11986                intent.setPriority(cappedPriority);
11987                return;
11988            }
11989            // all this for nothing; the requested priority was <= what was on the system
11990        }
11991
11992        public final void addActivity(PackageParser.Activity a, String type) {
11993            mActivities.put(a.getComponentName(), a);
11994            if (DEBUG_SHOW_INFO)
11995                Log.v(
11996                TAG, "  " + type + " " +
11997                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11998            if (DEBUG_SHOW_INFO)
11999                Log.v(TAG, "    Class=" + a.info.name);
12000            final int NI = a.intents.size();
12001            for (int j=0; j<NI; j++) {
12002                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12003                if ("activity".equals(type)) {
12004                    final PackageSetting ps =
12005                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12006                    final List<PackageParser.Activity> systemActivities =
12007                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12008                    adjustPriority(systemActivities, intent);
12009                }
12010                if (DEBUG_SHOW_INFO) {
12011                    Log.v(TAG, "    IntentFilter:");
12012                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12013                }
12014                if (!intent.debugCheck()) {
12015                    Log.w(TAG, "==> For Activity " + a.info.name);
12016                }
12017                addFilter(intent);
12018            }
12019        }
12020
12021        public final void removeActivity(PackageParser.Activity a, String type) {
12022            mActivities.remove(a.getComponentName());
12023            if (DEBUG_SHOW_INFO) {
12024                Log.v(TAG, "  " + type + " "
12025                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12026                                : a.info.name) + ":");
12027                Log.v(TAG, "    Class=" + a.info.name);
12028            }
12029            final int NI = a.intents.size();
12030            for (int j=0; j<NI; j++) {
12031                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12032                if (DEBUG_SHOW_INFO) {
12033                    Log.v(TAG, "    IntentFilter:");
12034                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12035                }
12036                removeFilter(intent);
12037            }
12038        }
12039
12040        @Override
12041        protected boolean allowFilterResult(
12042                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12043            ActivityInfo filterAi = filter.activity.info;
12044            for (int i=dest.size()-1; i>=0; i--) {
12045                ActivityInfo destAi = dest.get(i).activityInfo;
12046                if (destAi.name == filterAi.name
12047                        && destAi.packageName == filterAi.packageName) {
12048                    return false;
12049                }
12050            }
12051            return true;
12052        }
12053
12054        @Override
12055        protected ActivityIntentInfo[] newArray(int size) {
12056            return new ActivityIntentInfo[size];
12057        }
12058
12059        @Override
12060        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12061            if (!sUserManager.exists(userId)) return true;
12062            PackageParser.Package p = filter.activity.owner;
12063            if (p != null) {
12064                PackageSetting ps = (PackageSetting)p.mExtras;
12065                if (ps != null) {
12066                    // System apps are never considered stopped for purposes of
12067                    // filtering, because there may be no way for the user to
12068                    // actually re-launch them.
12069                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12070                            && ps.getStopped(userId);
12071                }
12072            }
12073            return false;
12074        }
12075
12076        @Override
12077        protected boolean isPackageForFilter(String packageName,
12078                PackageParser.ActivityIntentInfo info) {
12079            return packageName.equals(info.activity.owner.packageName);
12080        }
12081
12082        @Override
12083        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12084                int match, int userId) {
12085            if (!sUserManager.exists(userId)) return null;
12086            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12087                return null;
12088            }
12089            final PackageParser.Activity activity = info.activity;
12090            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12091            if (ps == null) {
12092                return null;
12093            }
12094            final PackageUserState userState = ps.readUserState(userId);
12095            ActivityInfo ai =
12096                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12097            if (ai == null) {
12098                return null;
12099            }
12100            final boolean matchExplicitlyVisibleOnly =
12101                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12102            final boolean matchVisibleToInstantApp =
12103                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12104            final boolean componentVisible =
12105                    matchVisibleToInstantApp
12106                    && info.isVisibleToInstantApp()
12107                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12108            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12109            // throw out filters that aren't visible to ephemeral apps
12110            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12111                return null;
12112            }
12113            // throw out instant app filters if we're not explicitly requesting them
12114            if (!matchInstantApp && userState.instantApp) {
12115                return null;
12116            }
12117            // throw out instant app filters if updates are available; will trigger
12118            // instant app resolution
12119            if (userState.instantApp && ps.isUpdateAvailable()) {
12120                return null;
12121            }
12122            final ResolveInfo res = new ResolveInfo();
12123            res.activityInfo = ai;
12124            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12125                res.filter = info;
12126            }
12127            if (info != null) {
12128                res.handleAllWebDataURI = info.handleAllWebDataURI();
12129            }
12130            res.priority = info.getPriority();
12131            res.preferredOrder = activity.owner.mPreferredOrder;
12132            //System.out.println("Result: " + res.activityInfo.className +
12133            //                   " = " + res.priority);
12134            res.match = match;
12135            res.isDefault = info.hasDefault;
12136            res.labelRes = info.labelRes;
12137            res.nonLocalizedLabel = info.nonLocalizedLabel;
12138            if (userNeedsBadging(userId)) {
12139                res.noResourceId = true;
12140            } else {
12141                res.icon = info.icon;
12142            }
12143            res.iconResourceId = info.icon;
12144            res.system = res.activityInfo.applicationInfo.isSystemApp();
12145            res.isInstantAppAvailable = userState.instantApp;
12146            return res;
12147        }
12148
12149        @Override
12150        protected void sortResults(List<ResolveInfo> results) {
12151            Collections.sort(results, mResolvePrioritySorter);
12152        }
12153
12154        @Override
12155        protected void dumpFilter(PrintWriter out, String prefix,
12156                PackageParser.ActivityIntentInfo filter) {
12157            out.print(prefix); out.print(
12158                    Integer.toHexString(System.identityHashCode(filter.activity)));
12159                    out.print(' ');
12160                    filter.activity.printComponentShortName(out);
12161                    out.print(" filter ");
12162                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12163        }
12164
12165        @Override
12166        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12167            return filter.activity;
12168        }
12169
12170        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12171            PackageParser.Activity activity = (PackageParser.Activity)label;
12172            out.print(prefix); out.print(
12173                    Integer.toHexString(System.identityHashCode(activity)));
12174                    out.print(' ');
12175                    activity.printComponentShortName(out);
12176            if (count > 1) {
12177                out.print(" ("); out.print(count); out.print(" filters)");
12178            }
12179            out.println();
12180        }
12181
12182        // Keys are String (activity class name), values are Activity.
12183        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12184                = new ArrayMap<ComponentName, PackageParser.Activity>();
12185        private int mFlags;
12186    }
12187
12188    private final class ServiceIntentResolver
12189            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12190        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12191                boolean defaultOnly, int userId) {
12192            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12193            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12194        }
12195
12196        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12197                int userId) {
12198            if (!sUserManager.exists(userId)) return null;
12199            mFlags = flags;
12200            return super.queryIntent(intent, resolvedType,
12201                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12202                    userId);
12203        }
12204
12205        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12206                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12207            if (!sUserManager.exists(userId)) return null;
12208            if (packageServices == null) {
12209                return null;
12210            }
12211            mFlags = flags;
12212            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12213            final int N = packageServices.size();
12214            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12215                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12216
12217            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12218            for (int i = 0; i < N; ++i) {
12219                intentFilters = packageServices.get(i).intents;
12220                if (intentFilters != null && intentFilters.size() > 0) {
12221                    PackageParser.ServiceIntentInfo[] array =
12222                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12223                    intentFilters.toArray(array);
12224                    listCut.add(array);
12225                }
12226            }
12227            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12228        }
12229
12230        public final void addService(PackageParser.Service s) {
12231            mServices.put(s.getComponentName(), s);
12232            if (DEBUG_SHOW_INFO) {
12233                Log.v(TAG, "  "
12234                        + (s.info.nonLocalizedLabel != null
12235                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12236                Log.v(TAG, "    Class=" + s.info.name);
12237            }
12238            final int NI = s.intents.size();
12239            int j;
12240            for (j=0; j<NI; j++) {
12241                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12242                if (DEBUG_SHOW_INFO) {
12243                    Log.v(TAG, "    IntentFilter:");
12244                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12245                }
12246                if (!intent.debugCheck()) {
12247                    Log.w(TAG, "==> For Service " + s.info.name);
12248                }
12249                addFilter(intent);
12250            }
12251        }
12252
12253        public final void removeService(PackageParser.Service s) {
12254            mServices.remove(s.getComponentName());
12255            if (DEBUG_SHOW_INFO) {
12256                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12257                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12258                Log.v(TAG, "    Class=" + s.info.name);
12259            }
12260            final int NI = s.intents.size();
12261            int j;
12262            for (j=0; j<NI; j++) {
12263                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12264                if (DEBUG_SHOW_INFO) {
12265                    Log.v(TAG, "    IntentFilter:");
12266                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12267                }
12268                removeFilter(intent);
12269            }
12270        }
12271
12272        @Override
12273        protected boolean allowFilterResult(
12274                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12275            ServiceInfo filterSi = filter.service.info;
12276            for (int i=dest.size()-1; i>=0; i--) {
12277                ServiceInfo destAi = dest.get(i).serviceInfo;
12278                if (destAi.name == filterSi.name
12279                        && destAi.packageName == filterSi.packageName) {
12280                    return false;
12281                }
12282            }
12283            return true;
12284        }
12285
12286        @Override
12287        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12288            return new PackageParser.ServiceIntentInfo[size];
12289        }
12290
12291        @Override
12292        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12293            if (!sUserManager.exists(userId)) return true;
12294            PackageParser.Package p = filter.service.owner;
12295            if (p != null) {
12296                PackageSetting ps = (PackageSetting)p.mExtras;
12297                if (ps != null) {
12298                    // System apps are never considered stopped for purposes of
12299                    // filtering, because there may be no way for the user to
12300                    // actually re-launch them.
12301                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12302                            && ps.getStopped(userId);
12303                }
12304            }
12305            return false;
12306        }
12307
12308        @Override
12309        protected boolean isPackageForFilter(String packageName,
12310                PackageParser.ServiceIntentInfo info) {
12311            return packageName.equals(info.service.owner.packageName);
12312        }
12313
12314        @Override
12315        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12316                int match, int userId) {
12317            if (!sUserManager.exists(userId)) return null;
12318            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12319            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12320                return null;
12321            }
12322            final PackageParser.Service service = info.service;
12323            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12324            if (ps == null) {
12325                return null;
12326            }
12327            final PackageUserState userState = ps.readUserState(userId);
12328            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12329                    userState, userId);
12330            if (si == null) {
12331                return null;
12332            }
12333            final boolean matchVisibleToInstantApp =
12334                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12335            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12336            // throw out filters that aren't visible to ephemeral apps
12337            if (matchVisibleToInstantApp
12338                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12339                return null;
12340            }
12341            // throw out ephemeral filters if we're not explicitly requesting them
12342            if (!isInstantApp && userState.instantApp) {
12343                return null;
12344            }
12345            // throw out instant app filters if updates are available; will trigger
12346            // instant app resolution
12347            if (userState.instantApp && ps.isUpdateAvailable()) {
12348                return null;
12349            }
12350            final ResolveInfo res = new ResolveInfo();
12351            res.serviceInfo = si;
12352            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12353                res.filter = filter;
12354            }
12355            res.priority = info.getPriority();
12356            res.preferredOrder = service.owner.mPreferredOrder;
12357            res.match = match;
12358            res.isDefault = info.hasDefault;
12359            res.labelRes = info.labelRes;
12360            res.nonLocalizedLabel = info.nonLocalizedLabel;
12361            res.icon = info.icon;
12362            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12363            return res;
12364        }
12365
12366        @Override
12367        protected void sortResults(List<ResolveInfo> results) {
12368            Collections.sort(results, mResolvePrioritySorter);
12369        }
12370
12371        @Override
12372        protected void dumpFilter(PrintWriter out, String prefix,
12373                PackageParser.ServiceIntentInfo filter) {
12374            out.print(prefix); out.print(
12375                    Integer.toHexString(System.identityHashCode(filter.service)));
12376                    out.print(' ');
12377                    filter.service.printComponentShortName(out);
12378                    out.print(" filter ");
12379                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12380        }
12381
12382        @Override
12383        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12384            return filter.service;
12385        }
12386
12387        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12388            PackageParser.Service service = (PackageParser.Service)label;
12389            out.print(prefix); out.print(
12390                    Integer.toHexString(System.identityHashCode(service)));
12391                    out.print(' ');
12392                    service.printComponentShortName(out);
12393            if (count > 1) {
12394                out.print(" ("); out.print(count); out.print(" filters)");
12395            }
12396            out.println();
12397        }
12398
12399//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12400//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12401//            final List<ResolveInfo> retList = Lists.newArrayList();
12402//            while (i.hasNext()) {
12403//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12404//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12405//                    retList.add(resolveInfo);
12406//                }
12407//            }
12408//            return retList;
12409//        }
12410
12411        // Keys are String (activity class name), values are Activity.
12412        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12413                = new ArrayMap<ComponentName, PackageParser.Service>();
12414        private int mFlags;
12415    }
12416
12417    private final class ProviderIntentResolver
12418            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12419        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12420                boolean defaultOnly, int userId) {
12421            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12422            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12423        }
12424
12425        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12426                int userId) {
12427            if (!sUserManager.exists(userId))
12428                return null;
12429            mFlags = flags;
12430            return super.queryIntent(intent, resolvedType,
12431                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12432                    userId);
12433        }
12434
12435        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12436                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12437            if (!sUserManager.exists(userId))
12438                return null;
12439            if (packageProviders == null) {
12440                return null;
12441            }
12442            mFlags = flags;
12443            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12444            final int N = packageProviders.size();
12445            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12446                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12447
12448            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12449            for (int i = 0; i < N; ++i) {
12450                intentFilters = packageProviders.get(i).intents;
12451                if (intentFilters != null && intentFilters.size() > 0) {
12452                    PackageParser.ProviderIntentInfo[] array =
12453                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12454                    intentFilters.toArray(array);
12455                    listCut.add(array);
12456                }
12457            }
12458            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12459        }
12460
12461        public final void addProvider(PackageParser.Provider p) {
12462            if (mProviders.containsKey(p.getComponentName())) {
12463                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12464                return;
12465            }
12466
12467            mProviders.put(p.getComponentName(), p);
12468            if (DEBUG_SHOW_INFO) {
12469                Log.v(TAG, "  "
12470                        + (p.info.nonLocalizedLabel != null
12471                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12472                Log.v(TAG, "    Class=" + p.info.name);
12473            }
12474            final int NI = p.intents.size();
12475            int j;
12476            for (j = 0; j < NI; j++) {
12477                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12478                if (DEBUG_SHOW_INFO) {
12479                    Log.v(TAG, "    IntentFilter:");
12480                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12481                }
12482                if (!intent.debugCheck()) {
12483                    Log.w(TAG, "==> For Provider " + p.info.name);
12484                }
12485                addFilter(intent);
12486            }
12487        }
12488
12489        public final void removeProvider(PackageParser.Provider p) {
12490            mProviders.remove(p.getComponentName());
12491            if (DEBUG_SHOW_INFO) {
12492                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12493                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12494                Log.v(TAG, "    Class=" + p.info.name);
12495            }
12496            final int NI = p.intents.size();
12497            int j;
12498            for (j = 0; j < NI; j++) {
12499                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12500                if (DEBUG_SHOW_INFO) {
12501                    Log.v(TAG, "    IntentFilter:");
12502                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12503                }
12504                removeFilter(intent);
12505            }
12506        }
12507
12508        @Override
12509        protected boolean allowFilterResult(
12510                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12511            ProviderInfo filterPi = filter.provider.info;
12512            for (int i = dest.size() - 1; i >= 0; i--) {
12513                ProviderInfo destPi = dest.get(i).providerInfo;
12514                if (destPi.name == filterPi.name
12515                        && destPi.packageName == filterPi.packageName) {
12516                    return false;
12517                }
12518            }
12519            return true;
12520        }
12521
12522        @Override
12523        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12524            return new PackageParser.ProviderIntentInfo[size];
12525        }
12526
12527        @Override
12528        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12529            if (!sUserManager.exists(userId))
12530                return true;
12531            PackageParser.Package p = filter.provider.owner;
12532            if (p != null) {
12533                PackageSetting ps = (PackageSetting) p.mExtras;
12534                if (ps != null) {
12535                    // System apps are never considered stopped for purposes of
12536                    // filtering, because there may be no way for the user to
12537                    // actually re-launch them.
12538                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12539                            && ps.getStopped(userId);
12540                }
12541            }
12542            return false;
12543        }
12544
12545        @Override
12546        protected boolean isPackageForFilter(String packageName,
12547                PackageParser.ProviderIntentInfo info) {
12548            return packageName.equals(info.provider.owner.packageName);
12549        }
12550
12551        @Override
12552        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12553                int match, int userId) {
12554            if (!sUserManager.exists(userId))
12555                return null;
12556            final PackageParser.ProviderIntentInfo info = filter;
12557            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12558                return null;
12559            }
12560            final PackageParser.Provider provider = info.provider;
12561            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12562            if (ps == null) {
12563                return null;
12564            }
12565            final PackageUserState userState = ps.readUserState(userId);
12566            final boolean matchVisibleToInstantApp =
12567                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12568            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12569            // throw out filters that aren't visible to instant applications
12570            if (matchVisibleToInstantApp
12571                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12572                return null;
12573            }
12574            // throw out instant application filters if we're not explicitly requesting them
12575            if (!isInstantApp && userState.instantApp) {
12576                return null;
12577            }
12578            // throw out instant application filters if updates are available; will trigger
12579            // instant application resolution
12580            if (userState.instantApp && ps.isUpdateAvailable()) {
12581                return null;
12582            }
12583            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12584                    userState, userId);
12585            if (pi == null) {
12586                return null;
12587            }
12588            final ResolveInfo res = new ResolveInfo();
12589            res.providerInfo = pi;
12590            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12591                res.filter = filter;
12592            }
12593            res.priority = info.getPriority();
12594            res.preferredOrder = provider.owner.mPreferredOrder;
12595            res.match = match;
12596            res.isDefault = info.hasDefault;
12597            res.labelRes = info.labelRes;
12598            res.nonLocalizedLabel = info.nonLocalizedLabel;
12599            res.icon = info.icon;
12600            res.system = res.providerInfo.applicationInfo.isSystemApp();
12601            return res;
12602        }
12603
12604        @Override
12605        protected void sortResults(List<ResolveInfo> results) {
12606            Collections.sort(results, mResolvePrioritySorter);
12607        }
12608
12609        @Override
12610        protected void dumpFilter(PrintWriter out, String prefix,
12611                PackageParser.ProviderIntentInfo filter) {
12612            out.print(prefix);
12613            out.print(
12614                    Integer.toHexString(System.identityHashCode(filter.provider)));
12615            out.print(' ');
12616            filter.provider.printComponentShortName(out);
12617            out.print(" filter ");
12618            out.println(Integer.toHexString(System.identityHashCode(filter)));
12619        }
12620
12621        @Override
12622        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12623            return filter.provider;
12624        }
12625
12626        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12627            PackageParser.Provider provider = (PackageParser.Provider)label;
12628            out.print(prefix); out.print(
12629                    Integer.toHexString(System.identityHashCode(provider)));
12630                    out.print(' ');
12631                    provider.printComponentShortName(out);
12632            if (count > 1) {
12633                out.print(" ("); out.print(count); out.print(" filters)");
12634            }
12635            out.println();
12636        }
12637
12638        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12639                = new ArrayMap<ComponentName, PackageParser.Provider>();
12640        private int mFlags;
12641    }
12642
12643    static final class EphemeralIntentResolver
12644            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12645        /**
12646         * The result that has the highest defined order. Ordering applies on a
12647         * per-package basis. Mapping is from package name to Pair of order and
12648         * EphemeralResolveInfo.
12649         * <p>
12650         * NOTE: This is implemented as a field variable for convenience and efficiency.
12651         * By having a field variable, we're able to track filter ordering as soon as
12652         * a non-zero order is defined. Otherwise, multiple loops across the result set
12653         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12654         * this needs to be contained entirely within {@link #filterResults}.
12655         */
12656        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12657
12658        @Override
12659        protected AuxiliaryResolveInfo[] newArray(int size) {
12660            return new AuxiliaryResolveInfo[size];
12661        }
12662
12663        @Override
12664        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12665            return true;
12666        }
12667
12668        @Override
12669        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12670                int userId) {
12671            if (!sUserManager.exists(userId)) {
12672                return null;
12673            }
12674            final String packageName = responseObj.resolveInfo.getPackageName();
12675            final Integer order = responseObj.getOrder();
12676            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12677                    mOrderResult.get(packageName);
12678            // ordering is enabled and this item's order isn't high enough
12679            if (lastOrderResult != null && lastOrderResult.first >= order) {
12680                return null;
12681            }
12682            final InstantAppResolveInfo res = responseObj.resolveInfo;
12683            if (order > 0) {
12684                // non-zero order, enable ordering
12685                mOrderResult.put(packageName, new Pair<>(order, res));
12686            }
12687            return responseObj;
12688        }
12689
12690        @Override
12691        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12692            // only do work if ordering is enabled [most of the time it won't be]
12693            if (mOrderResult.size() == 0) {
12694                return;
12695            }
12696            int resultSize = results.size();
12697            for (int i = 0; i < resultSize; i++) {
12698                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12699                final String packageName = info.getPackageName();
12700                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12701                if (savedInfo == null) {
12702                    // package doesn't having ordering
12703                    continue;
12704                }
12705                if (savedInfo.second == info) {
12706                    // circled back to the highest ordered item; remove from order list
12707                    mOrderResult.remove(packageName);
12708                    if (mOrderResult.size() == 0) {
12709                        // no more ordered items
12710                        break;
12711                    }
12712                    continue;
12713                }
12714                // item has a worse order, remove it from the result list
12715                results.remove(i);
12716                resultSize--;
12717                i--;
12718            }
12719        }
12720    }
12721
12722    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12723            new Comparator<ResolveInfo>() {
12724        public int compare(ResolveInfo r1, ResolveInfo r2) {
12725            int v1 = r1.priority;
12726            int v2 = r2.priority;
12727            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12728            if (v1 != v2) {
12729                return (v1 > v2) ? -1 : 1;
12730            }
12731            v1 = r1.preferredOrder;
12732            v2 = r2.preferredOrder;
12733            if (v1 != v2) {
12734                return (v1 > v2) ? -1 : 1;
12735            }
12736            if (r1.isDefault != r2.isDefault) {
12737                return r1.isDefault ? -1 : 1;
12738            }
12739            v1 = r1.match;
12740            v2 = r2.match;
12741            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12742            if (v1 != v2) {
12743                return (v1 > v2) ? -1 : 1;
12744            }
12745            if (r1.system != r2.system) {
12746                return r1.system ? -1 : 1;
12747            }
12748            if (r1.activityInfo != null) {
12749                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12750            }
12751            if (r1.serviceInfo != null) {
12752                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12753            }
12754            if (r1.providerInfo != null) {
12755                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12756            }
12757            return 0;
12758        }
12759    };
12760
12761    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12762            new Comparator<ProviderInfo>() {
12763        public int compare(ProviderInfo p1, ProviderInfo p2) {
12764            final int v1 = p1.initOrder;
12765            final int v2 = p2.initOrder;
12766            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12767        }
12768    };
12769
12770    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12771            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12772            final int[] userIds) {
12773        mHandler.post(new Runnable() {
12774            @Override
12775            public void run() {
12776                try {
12777                    final IActivityManager am = ActivityManager.getService();
12778                    if (am == null) return;
12779                    final int[] resolvedUserIds;
12780                    if (userIds == null) {
12781                        resolvedUserIds = am.getRunningUserIds();
12782                    } else {
12783                        resolvedUserIds = userIds;
12784                    }
12785                    for (int id : resolvedUserIds) {
12786                        final Intent intent = new Intent(action,
12787                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12788                        if (extras != null) {
12789                            intent.putExtras(extras);
12790                        }
12791                        if (targetPkg != null) {
12792                            intent.setPackage(targetPkg);
12793                        }
12794                        // Modify the UID when posting to other users
12795                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12796                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12797                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12798                            intent.putExtra(Intent.EXTRA_UID, uid);
12799                        }
12800                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12801                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12802                        if (DEBUG_BROADCASTS) {
12803                            RuntimeException here = new RuntimeException("here");
12804                            here.fillInStackTrace();
12805                            Slog.d(TAG, "Sending to user " + id + ": "
12806                                    + intent.toShortString(false, true, false, false)
12807                                    + " " + intent.getExtras(), here);
12808                        }
12809                        am.broadcastIntent(null, intent, null, finishedReceiver,
12810                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12811                                null, finishedReceiver != null, false, id);
12812                    }
12813                } catch (RemoteException ex) {
12814                }
12815            }
12816        });
12817    }
12818
12819    /**
12820     * Check if the external storage media is available. This is true if there
12821     * is a mounted external storage medium or if the external storage is
12822     * emulated.
12823     */
12824    private boolean isExternalMediaAvailable() {
12825        return mMediaMounted || Environment.isExternalStorageEmulated();
12826    }
12827
12828    @Override
12829    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12830        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
12831            return null;
12832        }
12833        // writer
12834        synchronized (mPackages) {
12835            if (!isExternalMediaAvailable()) {
12836                // If the external storage is no longer mounted at this point,
12837                // the caller may not have been able to delete all of this
12838                // packages files and can not delete any more.  Bail.
12839                return null;
12840            }
12841            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12842            if (lastPackage != null) {
12843                pkgs.remove(lastPackage);
12844            }
12845            if (pkgs.size() > 0) {
12846                return pkgs.get(0);
12847            }
12848        }
12849        return null;
12850    }
12851
12852    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12853        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12854                userId, andCode ? 1 : 0, packageName);
12855        if (mSystemReady) {
12856            msg.sendToTarget();
12857        } else {
12858            if (mPostSystemReadyMessages == null) {
12859                mPostSystemReadyMessages = new ArrayList<>();
12860            }
12861            mPostSystemReadyMessages.add(msg);
12862        }
12863    }
12864
12865    void startCleaningPackages() {
12866        // reader
12867        if (!isExternalMediaAvailable()) {
12868            return;
12869        }
12870        synchronized (mPackages) {
12871            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12872                return;
12873            }
12874        }
12875        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12876        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12877        IActivityManager am = ActivityManager.getService();
12878        if (am != null) {
12879            int dcsUid = -1;
12880            synchronized (mPackages) {
12881                if (!mDefaultContainerWhitelisted) {
12882                    mDefaultContainerWhitelisted = true;
12883                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
12884                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
12885                }
12886            }
12887            try {
12888                if (dcsUid > 0) {
12889                    am.backgroundWhitelistUid(dcsUid);
12890                }
12891                am.startService(null, intent, null, false, mContext.getOpPackageName(),
12892                        UserHandle.USER_SYSTEM);
12893            } catch (RemoteException e) {
12894            }
12895        }
12896    }
12897
12898    @Override
12899    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12900            int installFlags, String installerPackageName, int userId) {
12901        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12902
12903        final int callingUid = Binder.getCallingUid();
12904        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
12905                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12906
12907        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12908            try {
12909                if (observer != null) {
12910                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12911                }
12912            } catch (RemoteException re) {
12913            }
12914            return;
12915        }
12916
12917        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12918            installFlags |= PackageManager.INSTALL_FROM_ADB;
12919
12920        } else {
12921            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12922            // about installerPackageName.
12923
12924            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12925            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12926        }
12927
12928        UserHandle user;
12929        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12930            user = UserHandle.ALL;
12931        } else {
12932            user = new UserHandle(userId);
12933        }
12934
12935        // Only system components can circumvent runtime permissions when installing.
12936        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12937                && mContext.checkCallingOrSelfPermission(Manifest.permission
12938                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12939            throw new SecurityException("You need the "
12940                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12941                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12942        }
12943
12944        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12945                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12946            throw new IllegalArgumentException(
12947                    "New installs into ASEC containers no longer supported");
12948        }
12949
12950        final File originFile = new File(originPath);
12951        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12952
12953        final Message msg = mHandler.obtainMessage(INIT_COPY);
12954        final VerificationInfo verificationInfo = new VerificationInfo(
12955                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12956        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12957                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12958                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12959                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12960        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12961        msg.obj = params;
12962
12963        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12964                System.identityHashCode(msg.obj));
12965        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12966                System.identityHashCode(msg.obj));
12967
12968        mHandler.sendMessage(msg);
12969    }
12970
12971
12972    /**
12973     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12974     * it is acting on behalf on an enterprise or the user).
12975     *
12976     * Note that the ordering of the conditionals in this method is important. The checks we perform
12977     * are as follows, in this order:
12978     *
12979     * 1) If the install is being performed by a system app, we can trust the app to have set the
12980     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12981     *    what it is.
12982     * 2) If the install is being performed by a device or profile owner app, the install reason
12983     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12984     *    set the install reason correctly. If the app targets an older SDK version where install
12985     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12986     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12987     * 3) In all other cases, the install is being performed by a regular app that is neither part
12988     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12989     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12990     *    set to enterprise policy and if so, change it to unknown instead.
12991     */
12992    private int fixUpInstallReason(String installerPackageName, int installerUid,
12993            int installReason) {
12994        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12995                == PERMISSION_GRANTED) {
12996            // If the install is being performed by a system app, we trust that app to have set the
12997            // install reason correctly.
12998            return installReason;
12999        }
13000
13001        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13002            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13003        if (dpm != null) {
13004            ComponentName owner = null;
13005            try {
13006                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13007                if (owner == null) {
13008                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13009                }
13010            } catch (RemoteException e) {
13011            }
13012            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13013                // If the install is being performed by a device or profile owner, the install
13014                // reason should be enterprise policy.
13015                return PackageManager.INSTALL_REASON_POLICY;
13016            }
13017        }
13018
13019        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13020            // If the install is being performed by a regular app (i.e. neither system app nor
13021            // device or profile owner), we have no reason to believe that the app is acting on
13022            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13023            // change it to unknown instead.
13024            return PackageManager.INSTALL_REASON_UNKNOWN;
13025        }
13026
13027        // If the install is being performed by a regular app and the install reason was set to any
13028        // value but enterprise policy, leave the install reason unchanged.
13029        return installReason;
13030    }
13031
13032    void installStage(String packageName, File stagedDir,
13033            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13034            String installerPackageName, int installerUid, UserHandle user,
13035            Certificate[][] certificates) {
13036        if (DEBUG_EPHEMERAL) {
13037            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13038                Slog.d(TAG, "Ephemeral install of " + packageName);
13039            }
13040        }
13041        final VerificationInfo verificationInfo = new VerificationInfo(
13042                sessionParams.originatingUri, sessionParams.referrerUri,
13043                sessionParams.originatingUid, installerUid);
13044
13045        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13046
13047        final Message msg = mHandler.obtainMessage(INIT_COPY);
13048        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13049                sessionParams.installReason);
13050        final InstallParams params = new InstallParams(origin, null, observer,
13051                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13052                verificationInfo, user, sessionParams.abiOverride,
13053                sessionParams.grantedRuntimePermissions, certificates, installReason);
13054        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13055        msg.obj = params;
13056
13057        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13058                System.identityHashCode(msg.obj));
13059        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13060                System.identityHashCode(msg.obj));
13061
13062        mHandler.sendMessage(msg);
13063    }
13064
13065    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13066            int userId) {
13067        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13068        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13069                false /*startReceiver*/, pkgSetting.appId, userId);
13070
13071        // Send a session commit broadcast
13072        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13073        info.installReason = pkgSetting.getInstallReason(userId);
13074        info.appPackageName = packageName;
13075        sendSessionCommitBroadcast(info, userId);
13076    }
13077
13078    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13079            boolean includeStopped, int appId, int... userIds) {
13080        if (ArrayUtils.isEmpty(userIds)) {
13081            return;
13082        }
13083        Bundle extras = new Bundle(1);
13084        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13085        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13086
13087        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13088                packageName, extras, 0, null, null, userIds);
13089        if (sendBootCompleted) {
13090            mHandler.post(() -> {
13091                        for (int userId : userIds) {
13092                            sendBootCompletedBroadcastToSystemApp(
13093                                    packageName, includeStopped, userId);
13094                        }
13095                    }
13096            );
13097        }
13098    }
13099
13100    /**
13101     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13102     * automatically without needing an explicit launch.
13103     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13104     */
13105    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13106            int userId) {
13107        // If user is not running, the app didn't miss any broadcast
13108        if (!mUserManagerInternal.isUserRunning(userId)) {
13109            return;
13110        }
13111        final IActivityManager am = ActivityManager.getService();
13112        try {
13113            // Deliver LOCKED_BOOT_COMPLETED first
13114            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13115                    .setPackage(packageName);
13116            if (includeStopped) {
13117                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13118            }
13119            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13120            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13121                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13122
13123            // Deliver BOOT_COMPLETED only if user is unlocked
13124            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13125                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13126                if (includeStopped) {
13127                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13128                }
13129                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13130                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13131            }
13132        } catch (RemoteException e) {
13133            throw e.rethrowFromSystemServer();
13134        }
13135    }
13136
13137    @Override
13138    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13139            int userId) {
13140        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13141        PackageSetting pkgSetting;
13142        final int callingUid = Binder.getCallingUid();
13143        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13144                true /* requireFullPermission */, true /* checkShell */,
13145                "setApplicationHiddenSetting for user " + userId);
13146
13147        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13148            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13149            return false;
13150        }
13151
13152        long callingId = Binder.clearCallingIdentity();
13153        try {
13154            boolean sendAdded = false;
13155            boolean sendRemoved = false;
13156            // writer
13157            synchronized (mPackages) {
13158                pkgSetting = mSettings.mPackages.get(packageName);
13159                if (pkgSetting == null) {
13160                    return false;
13161                }
13162                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13163                    return false;
13164                }
13165                // Do not allow "android" is being disabled
13166                if ("android".equals(packageName)) {
13167                    Slog.w(TAG, "Cannot hide package: android");
13168                    return false;
13169                }
13170                // Cannot hide static shared libs as they are considered
13171                // a part of the using app (emulating static linking). Also
13172                // static libs are installed always on internal storage.
13173                PackageParser.Package pkg = mPackages.get(packageName);
13174                if (pkg != null && pkg.staticSharedLibName != null) {
13175                    Slog.w(TAG, "Cannot hide package: " + packageName
13176                            + " providing static shared library: "
13177                            + pkg.staticSharedLibName);
13178                    return false;
13179                }
13180                // Only allow protected packages to hide themselves.
13181                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13182                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13183                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13184                    return false;
13185                }
13186
13187                if (pkgSetting.getHidden(userId) != hidden) {
13188                    pkgSetting.setHidden(hidden, userId);
13189                    mSettings.writePackageRestrictionsLPr(userId);
13190                    if (hidden) {
13191                        sendRemoved = true;
13192                    } else {
13193                        sendAdded = true;
13194                    }
13195                }
13196            }
13197            if (sendAdded) {
13198                sendPackageAddedForUser(packageName, pkgSetting, userId);
13199                return true;
13200            }
13201            if (sendRemoved) {
13202                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13203                        "hiding pkg");
13204                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13205                return true;
13206            }
13207        } finally {
13208            Binder.restoreCallingIdentity(callingId);
13209        }
13210        return false;
13211    }
13212
13213    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13214            int userId) {
13215        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13216        info.removedPackage = packageName;
13217        info.installerPackageName = pkgSetting.installerPackageName;
13218        info.removedUsers = new int[] {userId};
13219        info.broadcastUsers = new int[] {userId};
13220        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13221        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13222    }
13223
13224    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13225        if (pkgList.length > 0) {
13226            Bundle extras = new Bundle(1);
13227            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13228
13229            sendPackageBroadcast(
13230                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13231                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13232                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13233                    new int[] {userId});
13234        }
13235    }
13236
13237    /**
13238     * Returns true if application is not found or there was an error. Otherwise it returns
13239     * the hidden state of the package for the given user.
13240     */
13241    @Override
13242    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13243        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13244        final int callingUid = Binder.getCallingUid();
13245        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13246                true /* requireFullPermission */, false /* checkShell */,
13247                "getApplicationHidden for user " + userId);
13248        PackageSetting ps;
13249        long callingId = Binder.clearCallingIdentity();
13250        try {
13251            // writer
13252            synchronized (mPackages) {
13253                ps = mSettings.mPackages.get(packageName);
13254                if (ps == null) {
13255                    return true;
13256                }
13257                if (filterAppAccessLPr(ps, callingUid, userId)) {
13258                    return true;
13259                }
13260                return ps.getHidden(userId);
13261            }
13262        } finally {
13263            Binder.restoreCallingIdentity(callingId);
13264        }
13265    }
13266
13267    /**
13268     * @hide
13269     */
13270    @Override
13271    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13272            int installReason) {
13273        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13274                null);
13275        PackageSetting pkgSetting;
13276        final int callingUid = Binder.getCallingUid();
13277        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13278                true /* requireFullPermission */, true /* checkShell */,
13279                "installExistingPackage for user " + userId);
13280        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13281            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13282        }
13283
13284        long callingId = Binder.clearCallingIdentity();
13285        try {
13286            boolean installed = false;
13287            final boolean instantApp =
13288                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13289            final boolean fullApp =
13290                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13291
13292            // writer
13293            synchronized (mPackages) {
13294                pkgSetting = mSettings.mPackages.get(packageName);
13295                if (pkgSetting == null) {
13296                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13297                }
13298                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13299                    // only allow the existing package to be used if it's installed as a full
13300                    // application for at least one user
13301                    boolean installAllowed = false;
13302                    for (int checkUserId : sUserManager.getUserIds()) {
13303                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13304                        if (installAllowed) {
13305                            break;
13306                        }
13307                    }
13308                    if (!installAllowed) {
13309                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13310                    }
13311                }
13312                if (!pkgSetting.getInstalled(userId)) {
13313                    pkgSetting.setInstalled(true, userId);
13314                    pkgSetting.setHidden(false, userId);
13315                    pkgSetting.setInstallReason(installReason, userId);
13316                    mSettings.writePackageRestrictionsLPr(userId);
13317                    mSettings.writeKernelMappingLPr(pkgSetting);
13318                    installed = true;
13319                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13320                    // upgrade app from instant to full; we don't allow app downgrade
13321                    installed = true;
13322                }
13323                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13324            }
13325
13326            if (installed) {
13327                if (pkgSetting.pkg != null) {
13328                    synchronized (mInstallLock) {
13329                        // We don't need to freeze for a brand new install
13330                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13331                    }
13332                }
13333                sendPackageAddedForUser(packageName, pkgSetting, userId);
13334                synchronized (mPackages) {
13335                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13336                }
13337            }
13338        } finally {
13339            Binder.restoreCallingIdentity(callingId);
13340        }
13341
13342        return PackageManager.INSTALL_SUCCEEDED;
13343    }
13344
13345    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13346            boolean instantApp, boolean fullApp) {
13347        // no state specified; do nothing
13348        if (!instantApp && !fullApp) {
13349            return;
13350        }
13351        if (userId != UserHandle.USER_ALL) {
13352            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13353                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13354            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13355                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13356            }
13357        } else {
13358            for (int currentUserId : sUserManager.getUserIds()) {
13359                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13360                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13361                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13362                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13363                }
13364            }
13365        }
13366    }
13367
13368    boolean isUserRestricted(int userId, String restrictionKey) {
13369        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13370        if (restrictions.getBoolean(restrictionKey, false)) {
13371            Log.w(TAG, "User is restricted: " + restrictionKey);
13372            return true;
13373        }
13374        return false;
13375    }
13376
13377    @Override
13378    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13379            int userId) {
13380        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13381        final int callingUid = Binder.getCallingUid();
13382        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13383                true /* requireFullPermission */, true /* checkShell */,
13384                "setPackagesSuspended for user " + userId);
13385
13386        if (ArrayUtils.isEmpty(packageNames)) {
13387            return packageNames;
13388        }
13389
13390        // List of package names for whom the suspended state has changed.
13391        List<String> changedPackages = new ArrayList<>(packageNames.length);
13392        // List of package names for whom the suspended state is not set as requested in this
13393        // method.
13394        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13395        long callingId = Binder.clearCallingIdentity();
13396        try {
13397            for (int i = 0; i < packageNames.length; i++) {
13398                String packageName = packageNames[i];
13399                boolean changed = false;
13400                final int appId;
13401                synchronized (mPackages) {
13402                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13403                    if (pkgSetting == null
13404                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13405                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13406                                + "\". Skipping suspending/un-suspending.");
13407                        unactionedPackages.add(packageName);
13408                        continue;
13409                    }
13410                    appId = pkgSetting.appId;
13411                    if (pkgSetting.getSuspended(userId) != suspended) {
13412                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13413                            unactionedPackages.add(packageName);
13414                            continue;
13415                        }
13416                        pkgSetting.setSuspended(suspended, userId);
13417                        mSettings.writePackageRestrictionsLPr(userId);
13418                        changed = true;
13419                        changedPackages.add(packageName);
13420                    }
13421                }
13422
13423                if (changed && suspended) {
13424                    killApplication(packageName, UserHandle.getUid(userId, appId),
13425                            "suspending package");
13426                }
13427            }
13428        } finally {
13429            Binder.restoreCallingIdentity(callingId);
13430        }
13431
13432        if (!changedPackages.isEmpty()) {
13433            sendPackagesSuspendedForUser(changedPackages.toArray(
13434                    new String[changedPackages.size()]), userId, suspended);
13435        }
13436
13437        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13438    }
13439
13440    @Override
13441    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13442        final int callingUid = Binder.getCallingUid();
13443        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13444                true /* requireFullPermission */, false /* checkShell */,
13445                "isPackageSuspendedForUser for user " + userId);
13446        synchronized (mPackages) {
13447            final PackageSetting ps = mSettings.mPackages.get(packageName);
13448            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13449                throw new IllegalArgumentException("Unknown target package: " + packageName);
13450            }
13451            return ps.getSuspended(userId);
13452        }
13453    }
13454
13455    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13456        if (isPackageDeviceAdmin(packageName, userId)) {
13457            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13458                    + "\": has an active device admin");
13459            return false;
13460        }
13461
13462        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13463        if (packageName.equals(activeLauncherPackageName)) {
13464            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13465                    + "\": contains the active launcher");
13466            return false;
13467        }
13468
13469        if (packageName.equals(mRequiredInstallerPackage)) {
13470            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13471                    + "\": required for package installation");
13472            return false;
13473        }
13474
13475        if (packageName.equals(mRequiredUninstallerPackage)) {
13476            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13477                    + "\": required for package uninstallation");
13478            return false;
13479        }
13480
13481        if (packageName.equals(mRequiredVerifierPackage)) {
13482            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13483                    + "\": required for package verification");
13484            return false;
13485        }
13486
13487        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13488            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13489                    + "\": is the default dialer");
13490            return false;
13491        }
13492
13493        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13494            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13495                    + "\": protected package");
13496            return false;
13497        }
13498
13499        // Cannot suspend static shared libs as they are considered
13500        // a part of the using app (emulating static linking). Also
13501        // static libs are installed always on internal storage.
13502        PackageParser.Package pkg = mPackages.get(packageName);
13503        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13504            Slog.w(TAG, "Cannot suspend package: " + packageName
13505                    + " providing static shared library: "
13506                    + pkg.staticSharedLibName);
13507            return false;
13508        }
13509
13510        return true;
13511    }
13512
13513    private String getActiveLauncherPackageName(int userId) {
13514        Intent intent = new Intent(Intent.ACTION_MAIN);
13515        intent.addCategory(Intent.CATEGORY_HOME);
13516        ResolveInfo resolveInfo = resolveIntent(
13517                intent,
13518                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13519                PackageManager.MATCH_DEFAULT_ONLY,
13520                userId);
13521
13522        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13523    }
13524
13525    private String getDefaultDialerPackageName(int userId) {
13526        synchronized (mPackages) {
13527            return mSettings.getDefaultDialerPackageNameLPw(userId);
13528        }
13529    }
13530
13531    @Override
13532    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13533        mContext.enforceCallingOrSelfPermission(
13534                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13535                "Only package verification agents can verify applications");
13536
13537        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13538        final PackageVerificationResponse response = new PackageVerificationResponse(
13539                verificationCode, Binder.getCallingUid());
13540        msg.arg1 = id;
13541        msg.obj = response;
13542        mHandler.sendMessage(msg);
13543    }
13544
13545    @Override
13546    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13547            long millisecondsToDelay) {
13548        mContext.enforceCallingOrSelfPermission(
13549                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13550                "Only package verification agents can extend verification timeouts");
13551
13552        final PackageVerificationState state = mPendingVerification.get(id);
13553        final PackageVerificationResponse response = new PackageVerificationResponse(
13554                verificationCodeAtTimeout, Binder.getCallingUid());
13555
13556        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13557            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13558        }
13559        if (millisecondsToDelay < 0) {
13560            millisecondsToDelay = 0;
13561        }
13562        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13563                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13564            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13565        }
13566
13567        if ((state != null) && !state.timeoutExtended()) {
13568            state.extendTimeout();
13569
13570            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13571            msg.arg1 = id;
13572            msg.obj = response;
13573            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13574        }
13575    }
13576
13577    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13578            int verificationCode, UserHandle user) {
13579        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13580        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13581        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13582        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13583        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13584
13585        mContext.sendBroadcastAsUser(intent, user,
13586                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13587    }
13588
13589    private ComponentName matchComponentForVerifier(String packageName,
13590            List<ResolveInfo> receivers) {
13591        ActivityInfo targetReceiver = null;
13592
13593        final int NR = receivers.size();
13594        for (int i = 0; i < NR; i++) {
13595            final ResolveInfo info = receivers.get(i);
13596            if (info.activityInfo == null) {
13597                continue;
13598            }
13599
13600            if (packageName.equals(info.activityInfo.packageName)) {
13601                targetReceiver = info.activityInfo;
13602                break;
13603            }
13604        }
13605
13606        if (targetReceiver == null) {
13607            return null;
13608        }
13609
13610        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13611    }
13612
13613    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13614            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13615        if (pkgInfo.verifiers.length == 0) {
13616            return null;
13617        }
13618
13619        final int N = pkgInfo.verifiers.length;
13620        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13621        for (int i = 0; i < N; i++) {
13622            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13623
13624            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13625                    receivers);
13626            if (comp == null) {
13627                continue;
13628            }
13629
13630            final int verifierUid = getUidForVerifier(verifierInfo);
13631            if (verifierUid == -1) {
13632                continue;
13633            }
13634
13635            if (DEBUG_VERIFY) {
13636                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13637                        + " with the correct signature");
13638            }
13639            sufficientVerifiers.add(comp);
13640            verificationState.addSufficientVerifier(verifierUid);
13641        }
13642
13643        return sufficientVerifiers;
13644    }
13645
13646    private int getUidForVerifier(VerifierInfo verifierInfo) {
13647        synchronized (mPackages) {
13648            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13649            if (pkg == null) {
13650                return -1;
13651            } else if (pkg.mSignatures.length != 1) {
13652                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13653                        + " has more than one signature; ignoring");
13654                return -1;
13655            }
13656
13657            /*
13658             * If the public key of the package's signature does not match
13659             * our expected public key, then this is a different package and
13660             * we should skip.
13661             */
13662
13663            final byte[] expectedPublicKey;
13664            try {
13665                final Signature verifierSig = pkg.mSignatures[0];
13666                final PublicKey publicKey = verifierSig.getPublicKey();
13667                expectedPublicKey = publicKey.getEncoded();
13668            } catch (CertificateException e) {
13669                return -1;
13670            }
13671
13672            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13673
13674            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13675                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13676                        + " does not have the expected public key; ignoring");
13677                return -1;
13678            }
13679
13680            return pkg.applicationInfo.uid;
13681        }
13682    }
13683
13684    @Override
13685    public void finishPackageInstall(int token, boolean didLaunch) {
13686        enforceSystemOrRoot("Only the system is allowed to finish installs");
13687
13688        if (DEBUG_INSTALL) {
13689            Slog.v(TAG, "BM finishing package install for " + token);
13690        }
13691        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13692
13693        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13694        mHandler.sendMessage(msg);
13695    }
13696
13697    /**
13698     * Get the verification agent timeout.  Used for both the APK verifier and the
13699     * intent filter verifier.
13700     *
13701     * @return verification timeout in milliseconds
13702     */
13703    private long getVerificationTimeout() {
13704        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13705                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13706                DEFAULT_VERIFICATION_TIMEOUT);
13707    }
13708
13709    /**
13710     * Get the default verification agent response code.
13711     *
13712     * @return default verification response code
13713     */
13714    private int getDefaultVerificationResponse(UserHandle user) {
13715        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13716            return PackageManager.VERIFICATION_REJECT;
13717        }
13718        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13719                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13720                DEFAULT_VERIFICATION_RESPONSE);
13721    }
13722
13723    /**
13724     * Check whether or not package verification has been enabled.
13725     *
13726     * @return true if verification should be performed
13727     */
13728    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13729        if (!DEFAULT_VERIFY_ENABLE) {
13730            return false;
13731        }
13732
13733        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13734
13735        // Check if installing from ADB
13736        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13737            // Do not run verification in a test harness environment
13738            if (ActivityManager.isRunningInTestHarness()) {
13739                return false;
13740            }
13741            if (ensureVerifyAppsEnabled) {
13742                return true;
13743            }
13744            // Check if the developer does not want package verification for ADB installs
13745            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13746                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13747                return false;
13748            }
13749        } else {
13750            // only when not installed from ADB, skip verification for instant apps when
13751            // the installer and verifier are the same.
13752            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13753                if (mInstantAppInstallerActivity != null
13754                        && mInstantAppInstallerActivity.packageName.equals(
13755                                mRequiredVerifierPackage)) {
13756                    try {
13757                        mContext.getSystemService(AppOpsManager.class)
13758                                .checkPackage(installerUid, mRequiredVerifierPackage);
13759                        if (DEBUG_VERIFY) {
13760                            Slog.i(TAG, "disable verification for instant app");
13761                        }
13762                        return false;
13763                    } catch (SecurityException ignore) { }
13764                }
13765            }
13766        }
13767
13768        if (ensureVerifyAppsEnabled) {
13769            return true;
13770        }
13771
13772        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13773                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13774    }
13775
13776    @Override
13777    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13778            throws RemoteException {
13779        mContext.enforceCallingOrSelfPermission(
13780                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13781                "Only intentfilter verification agents can verify applications");
13782
13783        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13784        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13785                Binder.getCallingUid(), verificationCode, failedDomains);
13786        msg.arg1 = id;
13787        msg.obj = response;
13788        mHandler.sendMessage(msg);
13789    }
13790
13791    @Override
13792    public int getIntentVerificationStatus(String packageName, int userId) {
13793        final int callingUid = Binder.getCallingUid();
13794        if (UserHandle.getUserId(callingUid) != userId) {
13795            mContext.enforceCallingOrSelfPermission(
13796                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13797                    "getIntentVerificationStatus" + userId);
13798        }
13799        if (getInstantAppPackageName(callingUid) != null) {
13800            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13801        }
13802        synchronized (mPackages) {
13803            final PackageSetting ps = mSettings.mPackages.get(packageName);
13804            if (ps == null
13805                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13806                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13807            }
13808            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13809        }
13810    }
13811
13812    @Override
13813    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13814        mContext.enforceCallingOrSelfPermission(
13815                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13816
13817        boolean result = false;
13818        synchronized (mPackages) {
13819            final PackageSetting ps = mSettings.mPackages.get(packageName);
13820            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13821                return false;
13822            }
13823            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13824        }
13825        if (result) {
13826            scheduleWritePackageRestrictionsLocked(userId);
13827        }
13828        return result;
13829    }
13830
13831    @Override
13832    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13833            String packageName) {
13834        final int callingUid = Binder.getCallingUid();
13835        if (getInstantAppPackageName(callingUid) != null) {
13836            return ParceledListSlice.emptyList();
13837        }
13838        synchronized (mPackages) {
13839            final PackageSetting ps = mSettings.mPackages.get(packageName);
13840            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13841                return ParceledListSlice.emptyList();
13842            }
13843            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13844        }
13845    }
13846
13847    @Override
13848    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13849        if (TextUtils.isEmpty(packageName)) {
13850            return ParceledListSlice.emptyList();
13851        }
13852        final int callingUid = Binder.getCallingUid();
13853        final int callingUserId = UserHandle.getUserId(callingUid);
13854        synchronized (mPackages) {
13855            PackageParser.Package pkg = mPackages.get(packageName);
13856            if (pkg == null || pkg.activities == null) {
13857                return ParceledListSlice.emptyList();
13858            }
13859            if (pkg.mExtras == null) {
13860                return ParceledListSlice.emptyList();
13861            }
13862            final PackageSetting ps = (PackageSetting) pkg.mExtras;
13863            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
13864                return ParceledListSlice.emptyList();
13865            }
13866            final int count = pkg.activities.size();
13867            ArrayList<IntentFilter> result = new ArrayList<>();
13868            for (int n=0; n<count; n++) {
13869                PackageParser.Activity activity = pkg.activities.get(n);
13870                if (activity.intents != null && activity.intents.size() > 0) {
13871                    result.addAll(activity.intents);
13872                }
13873            }
13874            return new ParceledListSlice<>(result);
13875        }
13876    }
13877
13878    @Override
13879    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13880        mContext.enforceCallingOrSelfPermission(
13881                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13882        if (UserHandle.getCallingUserId() != userId) {
13883            mContext.enforceCallingOrSelfPermission(
13884                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13885        }
13886
13887        synchronized (mPackages) {
13888            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13889            if (packageName != null) {
13890                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
13891                        packageName, userId);
13892            }
13893            return result;
13894        }
13895    }
13896
13897    @Override
13898    public String getDefaultBrowserPackageName(int userId) {
13899        if (UserHandle.getCallingUserId() != userId) {
13900            mContext.enforceCallingOrSelfPermission(
13901                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13902        }
13903        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13904            return null;
13905        }
13906        synchronized (mPackages) {
13907            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13908        }
13909    }
13910
13911    /**
13912     * Get the "allow unknown sources" setting.
13913     *
13914     * @return the current "allow unknown sources" setting
13915     */
13916    private int getUnknownSourcesSettings() {
13917        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13918                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13919                -1);
13920    }
13921
13922    @Override
13923    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13924        final int callingUid = Binder.getCallingUid();
13925        if (getInstantAppPackageName(callingUid) != null) {
13926            return;
13927        }
13928        // writer
13929        synchronized (mPackages) {
13930            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13931            if (targetPackageSetting == null
13932                    || filterAppAccessLPr(
13933                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
13934                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13935            }
13936
13937            PackageSetting installerPackageSetting;
13938            if (installerPackageName != null) {
13939                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13940                if (installerPackageSetting == null) {
13941                    throw new IllegalArgumentException("Unknown installer package: "
13942                            + installerPackageName);
13943                }
13944            } else {
13945                installerPackageSetting = null;
13946            }
13947
13948            Signature[] callerSignature;
13949            Object obj = mSettings.getUserIdLPr(callingUid);
13950            if (obj != null) {
13951                if (obj instanceof SharedUserSetting) {
13952                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13953                } else if (obj instanceof PackageSetting) {
13954                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13955                } else {
13956                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
13957                }
13958            } else {
13959                throw new SecurityException("Unknown calling UID: " + callingUid);
13960            }
13961
13962            // Verify: can't set installerPackageName to a package that is
13963            // not signed with the same cert as the caller.
13964            if (installerPackageSetting != null) {
13965                if (compareSignatures(callerSignature,
13966                        installerPackageSetting.signatures.mSignatures)
13967                        != PackageManager.SIGNATURE_MATCH) {
13968                    throw new SecurityException(
13969                            "Caller does not have same cert as new installer package "
13970                            + installerPackageName);
13971                }
13972            }
13973
13974            // Verify: if target already has an installer package, it must
13975            // be signed with the same cert as the caller.
13976            if (targetPackageSetting.installerPackageName != null) {
13977                PackageSetting setting = mSettings.mPackages.get(
13978                        targetPackageSetting.installerPackageName);
13979                // If the currently set package isn't valid, then it's always
13980                // okay to change it.
13981                if (setting != null) {
13982                    if (compareSignatures(callerSignature,
13983                            setting.signatures.mSignatures)
13984                            != PackageManager.SIGNATURE_MATCH) {
13985                        throw new SecurityException(
13986                                "Caller does not have same cert as old installer package "
13987                                + targetPackageSetting.installerPackageName);
13988                    }
13989                }
13990            }
13991
13992            // Okay!
13993            targetPackageSetting.installerPackageName = installerPackageName;
13994            if (installerPackageName != null) {
13995                mSettings.mInstallerPackages.add(installerPackageName);
13996            }
13997            scheduleWriteSettingsLocked();
13998        }
13999    }
14000
14001    @Override
14002    public void setApplicationCategoryHint(String packageName, int categoryHint,
14003            String callerPackageName) {
14004        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14005            throw new SecurityException("Instant applications don't have access to this method");
14006        }
14007        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14008                callerPackageName);
14009        synchronized (mPackages) {
14010            PackageSetting ps = mSettings.mPackages.get(packageName);
14011            if (ps == null) {
14012                throw new IllegalArgumentException("Unknown target package " + packageName);
14013            }
14014            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14015                throw new IllegalArgumentException("Unknown target package " + packageName);
14016            }
14017            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14018                throw new IllegalArgumentException("Calling package " + callerPackageName
14019                        + " is not installer for " + packageName);
14020            }
14021
14022            if (ps.categoryHint != categoryHint) {
14023                ps.categoryHint = categoryHint;
14024                scheduleWriteSettingsLocked();
14025            }
14026        }
14027    }
14028
14029    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14030        // Queue up an async operation since the package installation may take a little while.
14031        mHandler.post(new Runnable() {
14032            public void run() {
14033                mHandler.removeCallbacks(this);
14034                 // Result object to be returned
14035                PackageInstalledInfo res = new PackageInstalledInfo();
14036                res.setReturnCode(currentStatus);
14037                res.uid = -1;
14038                res.pkg = null;
14039                res.removedInfo = null;
14040                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14041                    args.doPreInstall(res.returnCode);
14042                    synchronized (mInstallLock) {
14043                        installPackageTracedLI(args, res);
14044                    }
14045                    args.doPostInstall(res.returnCode, res.uid);
14046                }
14047
14048                // A restore should be performed at this point if (a) the install
14049                // succeeded, (b) the operation is not an update, and (c) the new
14050                // package has not opted out of backup participation.
14051                final boolean update = res.removedInfo != null
14052                        && res.removedInfo.removedPackage != null;
14053                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14054                boolean doRestore = !update
14055                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14056
14057                // Set up the post-install work request bookkeeping.  This will be used
14058                // and cleaned up by the post-install event handling regardless of whether
14059                // there's a restore pass performed.  Token values are >= 1.
14060                int token;
14061                if (mNextInstallToken < 0) mNextInstallToken = 1;
14062                token = mNextInstallToken++;
14063
14064                PostInstallData data = new PostInstallData(args, res);
14065                mRunningInstalls.put(token, data);
14066                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14067
14068                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14069                    // Pass responsibility to the Backup Manager.  It will perform a
14070                    // restore if appropriate, then pass responsibility back to the
14071                    // Package Manager to run the post-install observer callbacks
14072                    // and broadcasts.
14073                    IBackupManager bm = IBackupManager.Stub.asInterface(
14074                            ServiceManager.getService(Context.BACKUP_SERVICE));
14075                    if (bm != null) {
14076                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14077                                + " to BM for possible restore");
14078                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14079                        try {
14080                            // TODO: http://b/22388012
14081                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14082                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14083                            } else {
14084                                doRestore = false;
14085                            }
14086                        } catch (RemoteException e) {
14087                            // can't happen; the backup manager is local
14088                        } catch (Exception e) {
14089                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14090                            doRestore = false;
14091                        }
14092                    } else {
14093                        Slog.e(TAG, "Backup Manager not found!");
14094                        doRestore = false;
14095                    }
14096                }
14097
14098                if (!doRestore) {
14099                    // No restore possible, or the Backup Manager was mysteriously not
14100                    // available -- just fire the post-install work request directly.
14101                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14102
14103                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14104
14105                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14106                    mHandler.sendMessage(msg);
14107                }
14108            }
14109        });
14110    }
14111
14112    /**
14113     * Callback from PackageSettings whenever an app is first transitioned out of the
14114     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14115     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14116     * here whether the app is the target of an ongoing install, and only send the
14117     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14118     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14119     * handling.
14120     */
14121    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14122        // Serialize this with the rest of the install-process message chain.  In the
14123        // restore-at-install case, this Runnable will necessarily run before the
14124        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14125        // are coherent.  In the non-restore case, the app has already completed install
14126        // and been launched through some other means, so it is not in a problematic
14127        // state for observers to see the FIRST_LAUNCH signal.
14128        mHandler.post(new Runnable() {
14129            @Override
14130            public void run() {
14131                for (int i = 0; i < mRunningInstalls.size(); i++) {
14132                    final PostInstallData data = mRunningInstalls.valueAt(i);
14133                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14134                        continue;
14135                    }
14136                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14137                        // right package; but is it for the right user?
14138                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14139                            if (userId == data.res.newUsers[uIndex]) {
14140                                if (DEBUG_BACKUP) {
14141                                    Slog.i(TAG, "Package " + pkgName
14142                                            + " being restored so deferring FIRST_LAUNCH");
14143                                }
14144                                return;
14145                            }
14146                        }
14147                    }
14148                }
14149                // didn't find it, so not being restored
14150                if (DEBUG_BACKUP) {
14151                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14152                }
14153                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14154            }
14155        });
14156    }
14157
14158    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14159        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14160                installerPkg, null, userIds);
14161    }
14162
14163    private abstract class HandlerParams {
14164        private static final int MAX_RETRIES = 4;
14165
14166        /**
14167         * Number of times startCopy() has been attempted and had a non-fatal
14168         * error.
14169         */
14170        private int mRetries = 0;
14171
14172        /** User handle for the user requesting the information or installation. */
14173        private final UserHandle mUser;
14174        String traceMethod;
14175        int traceCookie;
14176
14177        HandlerParams(UserHandle user) {
14178            mUser = user;
14179        }
14180
14181        UserHandle getUser() {
14182            return mUser;
14183        }
14184
14185        HandlerParams setTraceMethod(String traceMethod) {
14186            this.traceMethod = traceMethod;
14187            return this;
14188        }
14189
14190        HandlerParams setTraceCookie(int traceCookie) {
14191            this.traceCookie = traceCookie;
14192            return this;
14193        }
14194
14195        final boolean startCopy() {
14196            boolean res;
14197            try {
14198                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14199
14200                if (++mRetries > MAX_RETRIES) {
14201                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14202                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14203                    handleServiceError();
14204                    return false;
14205                } else {
14206                    handleStartCopy();
14207                    res = true;
14208                }
14209            } catch (RemoteException e) {
14210                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14211                mHandler.sendEmptyMessage(MCS_RECONNECT);
14212                res = false;
14213            }
14214            handleReturnCode();
14215            return res;
14216        }
14217
14218        final void serviceError() {
14219            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14220            handleServiceError();
14221            handleReturnCode();
14222        }
14223
14224        abstract void handleStartCopy() throws RemoteException;
14225        abstract void handleServiceError();
14226        abstract void handleReturnCode();
14227    }
14228
14229    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14230        for (File path : paths) {
14231            try {
14232                mcs.clearDirectory(path.getAbsolutePath());
14233            } catch (RemoteException e) {
14234            }
14235        }
14236    }
14237
14238    static class OriginInfo {
14239        /**
14240         * Location where install is coming from, before it has been
14241         * copied/renamed into place. This could be a single monolithic APK
14242         * file, or a cluster directory. This location may be untrusted.
14243         */
14244        final File file;
14245
14246        /**
14247         * Flag indicating that {@link #file} or {@link #cid} has already been
14248         * staged, meaning downstream users don't need to defensively copy the
14249         * contents.
14250         */
14251        final boolean staged;
14252
14253        /**
14254         * Flag indicating that {@link #file} or {@link #cid} is an already
14255         * installed app that is being moved.
14256         */
14257        final boolean existing;
14258
14259        final String resolvedPath;
14260        final File resolvedFile;
14261
14262        static OriginInfo fromNothing() {
14263            return new OriginInfo(null, false, false);
14264        }
14265
14266        static OriginInfo fromUntrustedFile(File file) {
14267            return new OriginInfo(file, false, false);
14268        }
14269
14270        static OriginInfo fromExistingFile(File file) {
14271            return new OriginInfo(file, false, true);
14272        }
14273
14274        static OriginInfo fromStagedFile(File file) {
14275            return new OriginInfo(file, true, false);
14276        }
14277
14278        private OriginInfo(File file, boolean staged, boolean existing) {
14279            this.file = file;
14280            this.staged = staged;
14281            this.existing = existing;
14282
14283            if (file != null) {
14284                resolvedPath = file.getAbsolutePath();
14285                resolvedFile = file;
14286            } else {
14287                resolvedPath = null;
14288                resolvedFile = null;
14289            }
14290        }
14291    }
14292
14293    static class MoveInfo {
14294        final int moveId;
14295        final String fromUuid;
14296        final String toUuid;
14297        final String packageName;
14298        final String dataAppName;
14299        final int appId;
14300        final String seinfo;
14301        final int targetSdkVersion;
14302
14303        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14304                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14305            this.moveId = moveId;
14306            this.fromUuid = fromUuid;
14307            this.toUuid = toUuid;
14308            this.packageName = packageName;
14309            this.dataAppName = dataAppName;
14310            this.appId = appId;
14311            this.seinfo = seinfo;
14312            this.targetSdkVersion = targetSdkVersion;
14313        }
14314    }
14315
14316    static class VerificationInfo {
14317        /** A constant used to indicate that a uid value is not present. */
14318        public static final int NO_UID = -1;
14319
14320        /** URI referencing where the package was downloaded from. */
14321        final Uri originatingUri;
14322
14323        /** HTTP referrer URI associated with the originatingURI. */
14324        final Uri referrer;
14325
14326        /** UID of the application that the install request originated from. */
14327        final int originatingUid;
14328
14329        /** UID of application requesting the install */
14330        final int installerUid;
14331
14332        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14333            this.originatingUri = originatingUri;
14334            this.referrer = referrer;
14335            this.originatingUid = originatingUid;
14336            this.installerUid = installerUid;
14337        }
14338    }
14339
14340    class InstallParams extends HandlerParams {
14341        final OriginInfo origin;
14342        final MoveInfo move;
14343        final IPackageInstallObserver2 observer;
14344        int installFlags;
14345        final String installerPackageName;
14346        final String volumeUuid;
14347        private InstallArgs mArgs;
14348        private int mRet;
14349        final String packageAbiOverride;
14350        final String[] grantedRuntimePermissions;
14351        final VerificationInfo verificationInfo;
14352        final Certificate[][] certificates;
14353        final int installReason;
14354
14355        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14356                int installFlags, String installerPackageName, String volumeUuid,
14357                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14358                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14359            super(user);
14360            this.origin = origin;
14361            this.move = move;
14362            this.observer = observer;
14363            this.installFlags = installFlags;
14364            this.installerPackageName = installerPackageName;
14365            this.volumeUuid = volumeUuid;
14366            this.verificationInfo = verificationInfo;
14367            this.packageAbiOverride = packageAbiOverride;
14368            this.grantedRuntimePermissions = grantedPermissions;
14369            this.certificates = certificates;
14370            this.installReason = installReason;
14371        }
14372
14373        @Override
14374        public String toString() {
14375            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14376                    + " file=" + origin.file + "}";
14377        }
14378
14379        private int installLocationPolicy(PackageInfoLite pkgLite) {
14380            String packageName = pkgLite.packageName;
14381            int installLocation = pkgLite.installLocation;
14382            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14383            // reader
14384            synchronized (mPackages) {
14385                // Currently installed package which the new package is attempting to replace or
14386                // null if no such package is installed.
14387                PackageParser.Package installedPkg = mPackages.get(packageName);
14388                // Package which currently owns the data which the new package will own if installed.
14389                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14390                // will be null whereas dataOwnerPkg will contain information about the package
14391                // which was uninstalled while keeping its data.
14392                PackageParser.Package dataOwnerPkg = installedPkg;
14393                if (dataOwnerPkg  == null) {
14394                    PackageSetting ps = mSettings.mPackages.get(packageName);
14395                    if (ps != null) {
14396                        dataOwnerPkg = ps.pkg;
14397                    }
14398                }
14399
14400                if (dataOwnerPkg != null) {
14401                    // If installed, the package will get access to data left on the device by its
14402                    // predecessor. As a security measure, this is permited only if this is not a
14403                    // version downgrade or if the predecessor package is marked as debuggable and
14404                    // a downgrade is explicitly requested.
14405                    //
14406                    // On debuggable platform builds, downgrades are permitted even for
14407                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14408                    // not offer security guarantees and thus it's OK to disable some security
14409                    // mechanisms to make debugging/testing easier on those builds. However, even on
14410                    // debuggable builds downgrades of packages are permitted only if requested via
14411                    // installFlags. This is because we aim to keep the behavior of debuggable
14412                    // platform builds as close as possible to the behavior of non-debuggable
14413                    // platform builds.
14414                    final boolean downgradeRequested =
14415                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14416                    final boolean packageDebuggable =
14417                                (dataOwnerPkg.applicationInfo.flags
14418                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14419                    final boolean downgradePermitted =
14420                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14421                    if (!downgradePermitted) {
14422                        try {
14423                            checkDowngrade(dataOwnerPkg, pkgLite);
14424                        } catch (PackageManagerException e) {
14425                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14426                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14427                        }
14428                    }
14429                }
14430
14431                if (installedPkg != null) {
14432                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14433                        // Check for updated system application.
14434                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14435                            if (onSd) {
14436                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14437                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14438                            }
14439                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14440                        } else {
14441                            if (onSd) {
14442                                // Install flag overrides everything.
14443                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14444                            }
14445                            // If current upgrade specifies particular preference
14446                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14447                                // Application explicitly specified internal.
14448                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14449                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14450                                // App explictly prefers external. Let policy decide
14451                            } else {
14452                                // Prefer previous location
14453                                if (isExternal(installedPkg)) {
14454                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14455                                }
14456                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14457                            }
14458                        }
14459                    } else {
14460                        // Invalid install. Return error code
14461                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14462                    }
14463                }
14464            }
14465            // All the special cases have been taken care of.
14466            // Return result based on recommended install location.
14467            if (onSd) {
14468                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14469            }
14470            return pkgLite.recommendedInstallLocation;
14471        }
14472
14473        /*
14474         * Invoke remote method to get package information and install
14475         * location values. Override install location based on default
14476         * policy if needed and then create install arguments based
14477         * on the install location.
14478         */
14479        public void handleStartCopy() throws RemoteException {
14480            int ret = PackageManager.INSTALL_SUCCEEDED;
14481
14482            // If we're already staged, we've firmly committed to an install location
14483            if (origin.staged) {
14484                if (origin.file != null) {
14485                    installFlags |= PackageManager.INSTALL_INTERNAL;
14486                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14487                } else {
14488                    throw new IllegalStateException("Invalid stage location");
14489                }
14490            }
14491
14492            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14493            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14494            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14495            PackageInfoLite pkgLite = null;
14496
14497            if (onInt && onSd) {
14498                // Check if both bits are set.
14499                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14500                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14501            } else if (onSd && ephemeral) {
14502                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14503                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14504            } else {
14505                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14506                        packageAbiOverride);
14507
14508                if (DEBUG_EPHEMERAL && ephemeral) {
14509                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14510                }
14511
14512                /*
14513                 * If we have too little free space, try to free cache
14514                 * before giving up.
14515                 */
14516                if (!origin.staged && pkgLite.recommendedInstallLocation
14517                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14518                    // TODO: focus freeing disk space on the target device
14519                    final StorageManager storage = StorageManager.from(mContext);
14520                    final long lowThreshold = storage.getStorageLowBytes(
14521                            Environment.getDataDirectory());
14522
14523                    final long sizeBytes = mContainerService.calculateInstalledSize(
14524                            origin.resolvedPath, packageAbiOverride);
14525
14526                    try {
14527                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14528                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14529                                installFlags, packageAbiOverride);
14530                    } catch (InstallerException e) {
14531                        Slog.w(TAG, "Failed to free cache", e);
14532                    }
14533
14534                    /*
14535                     * The cache free must have deleted the file we
14536                     * downloaded to install.
14537                     *
14538                     * TODO: fix the "freeCache" call to not delete
14539                     *       the file we care about.
14540                     */
14541                    if (pkgLite.recommendedInstallLocation
14542                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14543                        pkgLite.recommendedInstallLocation
14544                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14545                    }
14546                }
14547            }
14548
14549            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14550                int loc = pkgLite.recommendedInstallLocation;
14551                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14552                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14553                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14554                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14555                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14556                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14557                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14558                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14559                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14560                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14561                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14562                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14563                } else {
14564                    // Override with defaults if needed.
14565                    loc = installLocationPolicy(pkgLite);
14566                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14567                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14568                    } else if (!onSd && !onInt) {
14569                        // Override install location with flags
14570                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14571                            // Set the flag to install on external media.
14572                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14573                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14574                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14575                            if (DEBUG_EPHEMERAL) {
14576                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14577                            }
14578                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14579                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14580                                    |PackageManager.INSTALL_INTERNAL);
14581                        } else {
14582                            // Make sure the flag for installing on external
14583                            // media is unset
14584                            installFlags |= PackageManager.INSTALL_INTERNAL;
14585                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14586                        }
14587                    }
14588                }
14589            }
14590
14591            final InstallArgs args = createInstallArgs(this);
14592            mArgs = args;
14593
14594            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14595                // TODO: http://b/22976637
14596                // Apps installed for "all" users use the device owner to verify the app
14597                UserHandle verifierUser = getUser();
14598                if (verifierUser == UserHandle.ALL) {
14599                    verifierUser = UserHandle.SYSTEM;
14600                }
14601
14602                /*
14603                 * Determine if we have any installed package verifiers. If we
14604                 * do, then we'll defer to them to verify the packages.
14605                 */
14606                final int requiredUid = mRequiredVerifierPackage == null ? -1
14607                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14608                                verifierUser.getIdentifier());
14609                final int installerUid =
14610                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14611                if (!origin.existing && requiredUid != -1
14612                        && isVerificationEnabled(
14613                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14614                    final Intent verification = new Intent(
14615                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14616                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14617                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14618                            PACKAGE_MIME_TYPE);
14619                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14620
14621                    // Query all live verifiers based on current user state
14622                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14623                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14624                            false /*allowDynamicSplits*/);
14625
14626                    if (DEBUG_VERIFY) {
14627                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14628                                + verification.toString() + " with " + pkgLite.verifiers.length
14629                                + " optional verifiers");
14630                    }
14631
14632                    final int verificationId = mPendingVerificationToken++;
14633
14634                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14635
14636                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14637                            installerPackageName);
14638
14639                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14640                            installFlags);
14641
14642                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14643                            pkgLite.packageName);
14644
14645                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14646                            pkgLite.versionCode);
14647
14648                    if (verificationInfo != null) {
14649                        if (verificationInfo.originatingUri != null) {
14650                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14651                                    verificationInfo.originatingUri);
14652                        }
14653                        if (verificationInfo.referrer != null) {
14654                            verification.putExtra(Intent.EXTRA_REFERRER,
14655                                    verificationInfo.referrer);
14656                        }
14657                        if (verificationInfo.originatingUid >= 0) {
14658                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14659                                    verificationInfo.originatingUid);
14660                        }
14661                        if (verificationInfo.installerUid >= 0) {
14662                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14663                                    verificationInfo.installerUid);
14664                        }
14665                    }
14666
14667                    final PackageVerificationState verificationState = new PackageVerificationState(
14668                            requiredUid, args);
14669
14670                    mPendingVerification.append(verificationId, verificationState);
14671
14672                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14673                            receivers, verificationState);
14674
14675                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14676                    final long idleDuration = getVerificationTimeout();
14677
14678                    /*
14679                     * If any sufficient verifiers were listed in the package
14680                     * manifest, attempt to ask them.
14681                     */
14682                    if (sufficientVerifiers != null) {
14683                        final int N = sufficientVerifiers.size();
14684                        if (N == 0) {
14685                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14686                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14687                        } else {
14688                            for (int i = 0; i < N; i++) {
14689                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14690                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14691                                        verifierComponent.getPackageName(), idleDuration,
14692                                        verifierUser.getIdentifier(), false, "package verifier");
14693
14694                                final Intent sufficientIntent = new Intent(verification);
14695                                sufficientIntent.setComponent(verifierComponent);
14696                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14697                            }
14698                        }
14699                    }
14700
14701                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14702                            mRequiredVerifierPackage, receivers);
14703                    if (ret == PackageManager.INSTALL_SUCCEEDED
14704                            && mRequiredVerifierPackage != null) {
14705                        Trace.asyncTraceBegin(
14706                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14707                        /*
14708                         * Send the intent to the required verification agent,
14709                         * but only start the verification timeout after the
14710                         * target BroadcastReceivers have run.
14711                         */
14712                        verification.setComponent(requiredVerifierComponent);
14713                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14714                                mRequiredVerifierPackage, idleDuration,
14715                                verifierUser.getIdentifier(), false, "package verifier");
14716                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14717                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14718                                new BroadcastReceiver() {
14719                                    @Override
14720                                    public void onReceive(Context context, Intent intent) {
14721                                        final Message msg = mHandler
14722                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14723                                        msg.arg1 = verificationId;
14724                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14725                                    }
14726                                }, null, 0, null, null);
14727
14728                        /*
14729                         * We don't want the copy to proceed until verification
14730                         * succeeds, so null out this field.
14731                         */
14732                        mArgs = null;
14733                    }
14734                } else {
14735                    /*
14736                     * No package verification is enabled, so immediately start
14737                     * the remote call to initiate copy using temporary file.
14738                     */
14739                    ret = args.copyApk(mContainerService, true);
14740                }
14741            }
14742
14743            mRet = ret;
14744        }
14745
14746        @Override
14747        void handleReturnCode() {
14748            // If mArgs is null, then MCS couldn't be reached. When it
14749            // reconnects, it will try again to install. At that point, this
14750            // will succeed.
14751            if (mArgs != null) {
14752                processPendingInstall(mArgs, mRet);
14753            }
14754        }
14755
14756        @Override
14757        void handleServiceError() {
14758            mArgs = createInstallArgs(this);
14759            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14760        }
14761    }
14762
14763    private InstallArgs createInstallArgs(InstallParams params) {
14764        if (params.move != null) {
14765            return new MoveInstallArgs(params);
14766        } else {
14767            return new FileInstallArgs(params);
14768        }
14769    }
14770
14771    /**
14772     * Create args that describe an existing installed package. Typically used
14773     * when cleaning up old installs, or used as a move source.
14774     */
14775    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14776            String resourcePath, String[] instructionSets) {
14777        return new FileInstallArgs(codePath, resourcePath, instructionSets);
14778    }
14779
14780    static abstract class InstallArgs {
14781        /** @see InstallParams#origin */
14782        final OriginInfo origin;
14783        /** @see InstallParams#move */
14784        final MoveInfo move;
14785
14786        final IPackageInstallObserver2 observer;
14787        // Always refers to PackageManager flags only
14788        final int installFlags;
14789        final String installerPackageName;
14790        final String volumeUuid;
14791        final UserHandle user;
14792        final String abiOverride;
14793        final String[] installGrantPermissions;
14794        /** If non-null, drop an async trace when the install completes */
14795        final String traceMethod;
14796        final int traceCookie;
14797        final Certificate[][] certificates;
14798        final int installReason;
14799
14800        // The list of instruction sets supported by this app. This is currently
14801        // only used during the rmdex() phase to clean up resources. We can get rid of this
14802        // if we move dex files under the common app path.
14803        /* nullable */ String[] instructionSets;
14804
14805        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14806                int installFlags, String installerPackageName, String volumeUuid,
14807                UserHandle user, String[] instructionSets,
14808                String abiOverride, String[] installGrantPermissions,
14809                String traceMethod, int traceCookie, Certificate[][] certificates,
14810                int installReason) {
14811            this.origin = origin;
14812            this.move = move;
14813            this.installFlags = installFlags;
14814            this.observer = observer;
14815            this.installerPackageName = installerPackageName;
14816            this.volumeUuid = volumeUuid;
14817            this.user = user;
14818            this.instructionSets = instructionSets;
14819            this.abiOverride = abiOverride;
14820            this.installGrantPermissions = installGrantPermissions;
14821            this.traceMethod = traceMethod;
14822            this.traceCookie = traceCookie;
14823            this.certificates = certificates;
14824            this.installReason = installReason;
14825        }
14826
14827        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14828        abstract int doPreInstall(int status);
14829
14830        /**
14831         * Rename package into final resting place. All paths on the given
14832         * scanned package should be updated to reflect the rename.
14833         */
14834        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14835        abstract int doPostInstall(int status, int uid);
14836
14837        /** @see PackageSettingBase#codePathString */
14838        abstract String getCodePath();
14839        /** @see PackageSettingBase#resourcePathString */
14840        abstract String getResourcePath();
14841
14842        // Need installer lock especially for dex file removal.
14843        abstract void cleanUpResourcesLI();
14844        abstract boolean doPostDeleteLI(boolean delete);
14845
14846        /**
14847         * Called before the source arguments are copied. This is used mostly
14848         * for MoveParams when it needs to read the source file to put it in the
14849         * destination.
14850         */
14851        int doPreCopy() {
14852            return PackageManager.INSTALL_SUCCEEDED;
14853        }
14854
14855        /**
14856         * Called after the source arguments are copied. This is used mostly for
14857         * MoveParams when it needs to read the source file to put it in the
14858         * destination.
14859         */
14860        int doPostCopy(int uid) {
14861            return PackageManager.INSTALL_SUCCEEDED;
14862        }
14863
14864        protected boolean isFwdLocked() {
14865            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14866        }
14867
14868        protected boolean isExternalAsec() {
14869            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14870        }
14871
14872        protected boolean isEphemeral() {
14873            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14874        }
14875
14876        UserHandle getUser() {
14877            return user;
14878        }
14879    }
14880
14881    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14882        if (!allCodePaths.isEmpty()) {
14883            if (instructionSets == null) {
14884                throw new IllegalStateException("instructionSet == null");
14885            }
14886            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14887            for (String codePath : allCodePaths) {
14888                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14889                    try {
14890                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14891                    } catch (InstallerException ignored) {
14892                    }
14893                }
14894            }
14895        }
14896    }
14897
14898    /**
14899     * Logic to handle installation of non-ASEC applications, including copying
14900     * and renaming logic.
14901     */
14902    class FileInstallArgs extends InstallArgs {
14903        private File codeFile;
14904        private File resourceFile;
14905
14906        // Example topology:
14907        // /data/app/com.example/base.apk
14908        // /data/app/com.example/split_foo.apk
14909        // /data/app/com.example/lib/arm/libfoo.so
14910        // /data/app/com.example/lib/arm64/libfoo.so
14911        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14912
14913        /** New install */
14914        FileInstallArgs(InstallParams params) {
14915            super(params.origin, params.move, params.observer, params.installFlags,
14916                    params.installerPackageName, params.volumeUuid,
14917                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14918                    params.grantedRuntimePermissions,
14919                    params.traceMethod, params.traceCookie, params.certificates,
14920                    params.installReason);
14921            if (isFwdLocked()) {
14922                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14923            }
14924        }
14925
14926        /** Existing install */
14927        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14928            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14929                    null, null, null, 0, null /*certificates*/,
14930                    PackageManager.INSTALL_REASON_UNKNOWN);
14931            this.codeFile = (codePath != null) ? new File(codePath) : null;
14932            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14933        }
14934
14935        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14936            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14937            try {
14938                return doCopyApk(imcs, temp);
14939            } finally {
14940                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14941            }
14942        }
14943
14944        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14945            if (origin.staged) {
14946                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14947                codeFile = origin.file;
14948                resourceFile = origin.file;
14949                return PackageManager.INSTALL_SUCCEEDED;
14950            }
14951
14952            try {
14953                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14954                final File tempDir =
14955                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14956                codeFile = tempDir;
14957                resourceFile = tempDir;
14958            } catch (IOException e) {
14959                Slog.w(TAG, "Failed to create copy file: " + e);
14960                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14961            }
14962
14963            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14964                @Override
14965                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14966                    if (!FileUtils.isValidExtFilename(name)) {
14967                        throw new IllegalArgumentException("Invalid filename: " + name);
14968                    }
14969                    try {
14970                        final File file = new File(codeFile, name);
14971                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14972                                O_RDWR | O_CREAT, 0644);
14973                        Os.chmod(file.getAbsolutePath(), 0644);
14974                        return new ParcelFileDescriptor(fd);
14975                    } catch (ErrnoException e) {
14976                        throw new RemoteException("Failed to open: " + e.getMessage());
14977                    }
14978                }
14979            };
14980
14981            int ret = PackageManager.INSTALL_SUCCEEDED;
14982            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14983            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14984                Slog.e(TAG, "Failed to copy package");
14985                return ret;
14986            }
14987
14988            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14989            NativeLibraryHelper.Handle handle = null;
14990            try {
14991                handle = NativeLibraryHelper.Handle.create(codeFile);
14992                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14993                        abiOverride);
14994            } catch (IOException e) {
14995                Slog.e(TAG, "Copying native libraries failed", e);
14996                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14997            } finally {
14998                IoUtils.closeQuietly(handle);
14999            }
15000
15001            return ret;
15002        }
15003
15004        int doPreInstall(int status) {
15005            if (status != PackageManager.INSTALL_SUCCEEDED) {
15006                cleanUp();
15007            }
15008            return status;
15009        }
15010
15011        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15012            if (status != PackageManager.INSTALL_SUCCEEDED) {
15013                cleanUp();
15014                return false;
15015            }
15016
15017            final File targetDir = codeFile.getParentFile();
15018            final File beforeCodeFile = codeFile;
15019            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15020
15021            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15022            try {
15023                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15024            } catch (ErrnoException e) {
15025                Slog.w(TAG, "Failed to rename", e);
15026                return false;
15027            }
15028
15029            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15030                Slog.w(TAG, "Failed to restorecon");
15031                return false;
15032            }
15033
15034            // Reflect the rename internally
15035            codeFile = afterCodeFile;
15036            resourceFile = afterCodeFile;
15037
15038            // Reflect the rename in scanned details
15039            try {
15040                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15041            } catch (IOException e) {
15042                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15043                return false;
15044            }
15045            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15046                    afterCodeFile, pkg.baseCodePath));
15047            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15048                    afterCodeFile, pkg.splitCodePaths));
15049
15050            // Reflect the rename in app info
15051            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15052            pkg.setApplicationInfoCodePath(pkg.codePath);
15053            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15054            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15055            pkg.setApplicationInfoResourcePath(pkg.codePath);
15056            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15057            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15058
15059            return true;
15060        }
15061
15062        int doPostInstall(int status, int uid) {
15063            if (status != PackageManager.INSTALL_SUCCEEDED) {
15064                cleanUp();
15065            }
15066            return status;
15067        }
15068
15069        @Override
15070        String getCodePath() {
15071            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15072        }
15073
15074        @Override
15075        String getResourcePath() {
15076            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15077        }
15078
15079        private boolean cleanUp() {
15080            if (codeFile == null || !codeFile.exists()) {
15081                return false;
15082            }
15083
15084            removeCodePathLI(codeFile);
15085
15086            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15087                resourceFile.delete();
15088            }
15089
15090            return true;
15091        }
15092
15093        void cleanUpResourcesLI() {
15094            // Try enumerating all code paths before deleting
15095            List<String> allCodePaths = Collections.EMPTY_LIST;
15096            if (codeFile != null && codeFile.exists()) {
15097                try {
15098                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15099                    allCodePaths = pkg.getAllCodePaths();
15100                } catch (PackageParserException e) {
15101                    // Ignored; we tried our best
15102                }
15103            }
15104
15105            cleanUp();
15106            removeDexFiles(allCodePaths, instructionSets);
15107        }
15108
15109        boolean doPostDeleteLI(boolean delete) {
15110            // XXX err, shouldn't we respect the delete flag?
15111            cleanUpResourcesLI();
15112            return true;
15113        }
15114    }
15115
15116    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15117            PackageManagerException {
15118        if (copyRet < 0) {
15119            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15120                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15121                throw new PackageManagerException(copyRet, message);
15122            }
15123        }
15124    }
15125
15126    /**
15127     * Extract the StorageManagerService "container ID" from the full code path of an
15128     * .apk.
15129     */
15130    static String cidFromCodePath(String fullCodePath) {
15131        int eidx = fullCodePath.lastIndexOf("/");
15132        String subStr1 = fullCodePath.substring(0, eidx);
15133        int sidx = subStr1.lastIndexOf("/");
15134        return subStr1.substring(sidx+1, eidx);
15135    }
15136
15137    /**
15138     * Logic to handle movement of existing installed applications.
15139     */
15140    class MoveInstallArgs extends InstallArgs {
15141        private File codeFile;
15142        private File resourceFile;
15143
15144        /** New install */
15145        MoveInstallArgs(InstallParams params) {
15146            super(params.origin, params.move, params.observer, params.installFlags,
15147                    params.installerPackageName, params.volumeUuid,
15148                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15149                    params.grantedRuntimePermissions,
15150                    params.traceMethod, params.traceCookie, params.certificates,
15151                    params.installReason);
15152        }
15153
15154        int copyApk(IMediaContainerService imcs, boolean temp) {
15155            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15156                    + move.fromUuid + " to " + move.toUuid);
15157            synchronized (mInstaller) {
15158                try {
15159                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15160                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15161                } catch (InstallerException e) {
15162                    Slog.w(TAG, "Failed to move app", e);
15163                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15164                }
15165            }
15166
15167            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15168            resourceFile = codeFile;
15169            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15170
15171            return PackageManager.INSTALL_SUCCEEDED;
15172        }
15173
15174        int doPreInstall(int status) {
15175            if (status != PackageManager.INSTALL_SUCCEEDED) {
15176                cleanUp(move.toUuid);
15177            }
15178            return status;
15179        }
15180
15181        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15182            if (status != PackageManager.INSTALL_SUCCEEDED) {
15183                cleanUp(move.toUuid);
15184                return false;
15185            }
15186
15187            // Reflect the move in app info
15188            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15189            pkg.setApplicationInfoCodePath(pkg.codePath);
15190            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15191            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15192            pkg.setApplicationInfoResourcePath(pkg.codePath);
15193            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15194            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15195
15196            return true;
15197        }
15198
15199        int doPostInstall(int status, int uid) {
15200            if (status == PackageManager.INSTALL_SUCCEEDED) {
15201                cleanUp(move.fromUuid);
15202            } else {
15203                cleanUp(move.toUuid);
15204            }
15205            return status;
15206        }
15207
15208        @Override
15209        String getCodePath() {
15210            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15211        }
15212
15213        @Override
15214        String getResourcePath() {
15215            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15216        }
15217
15218        private boolean cleanUp(String volumeUuid) {
15219            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15220                    move.dataAppName);
15221            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15222            final int[] userIds = sUserManager.getUserIds();
15223            synchronized (mInstallLock) {
15224                // Clean up both app data and code
15225                // All package moves are frozen until finished
15226                for (int userId : userIds) {
15227                    try {
15228                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15229                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15230                    } catch (InstallerException e) {
15231                        Slog.w(TAG, String.valueOf(e));
15232                    }
15233                }
15234                removeCodePathLI(codeFile);
15235            }
15236            return true;
15237        }
15238
15239        void cleanUpResourcesLI() {
15240            throw new UnsupportedOperationException();
15241        }
15242
15243        boolean doPostDeleteLI(boolean delete) {
15244            throw new UnsupportedOperationException();
15245        }
15246    }
15247
15248    static String getAsecPackageName(String packageCid) {
15249        int idx = packageCid.lastIndexOf("-");
15250        if (idx == -1) {
15251            return packageCid;
15252        }
15253        return packageCid.substring(0, idx);
15254    }
15255
15256    // Utility method used to create code paths based on package name and available index.
15257    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15258        String idxStr = "";
15259        int idx = 1;
15260        // Fall back to default value of idx=1 if prefix is not
15261        // part of oldCodePath
15262        if (oldCodePath != null) {
15263            String subStr = oldCodePath;
15264            // Drop the suffix right away
15265            if (suffix != null && subStr.endsWith(suffix)) {
15266                subStr = subStr.substring(0, subStr.length() - suffix.length());
15267            }
15268            // If oldCodePath already contains prefix find out the
15269            // ending index to either increment or decrement.
15270            int sidx = subStr.lastIndexOf(prefix);
15271            if (sidx != -1) {
15272                subStr = subStr.substring(sidx + prefix.length());
15273                if (subStr != null) {
15274                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15275                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15276                    }
15277                    try {
15278                        idx = Integer.parseInt(subStr);
15279                        if (idx <= 1) {
15280                            idx++;
15281                        } else {
15282                            idx--;
15283                        }
15284                    } catch(NumberFormatException e) {
15285                    }
15286                }
15287            }
15288        }
15289        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15290        return prefix + idxStr;
15291    }
15292
15293    private File getNextCodePath(File targetDir, String packageName) {
15294        File result;
15295        SecureRandom random = new SecureRandom();
15296        byte[] bytes = new byte[16];
15297        do {
15298            random.nextBytes(bytes);
15299            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15300            result = new File(targetDir, packageName + "-" + suffix);
15301        } while (result.exists());
15302        return result;
15303    }
15304
15305    // Utility method that returns the relative package path with respect
15306    // to the installation directory. Like say for /data/data/com.test-1.apk
15307    // string com.test-1 is returned.
15308    static String deriveCodePathName(String codePath) {
15309        if (codePath == null) {
15310            return null;
15311        }
15312        final File codeFile = new File(codePath);
15313        final String name = codeFile.getName();
15314        if (codeFile.isDirectory()) {
15315            return name;
15316        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15317            final int lastDot = name.lastIndexOf('.');
15318            return name.substring(0, lastDot);
15319        } else {
15320            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15321            return null;
15322        }
15323    }
15324
15325    static class PackageInstalledInfo {
15326        String name;
15327        int uid;
15328        // The set of users that originally had this package installed.
15329        int[] origUsers;
15330        // The set of users that now have this package installed.
15331        int[] newUsers;
15332        PackageParser.Package pkg;
15333        int returnCode;
15334        String returnMsg;
15335        String installerPackageName;
15336        PackageRemovedInfo removedInfo;
15337        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15338
15339        public void setError(int code, String msg) {
15340            setReturnCode(code);
15341            setReturnMessage(msg);
15342            Slog.w(TAG, msg);
15343        }
15344
15345        public void setError(String msg, PackageParserException e) {
15346            setReturnCode(e.error);
15347            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15348            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15349            for (int i = 0; i < childCount; i++) {
15350                addedChildPackages.valueAt(i).setError(msg, e);
15351            }
15352            Slog.w(TAG, msg, e);
15353        }
15354
15355        public void setError(String msg, PackageManagerException e) {
15356            returnCode = e.error;
15357            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15358            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15359            for (int i = 0; i < childCount; i++) {
15360                addedChildPackages.valueAt(i).setError(msg, e);
15361            }
15362            Slog.w(TAG, msg, e);
15363        }
15364
15365        public void setReturnCode(int returnCode) {
15366            this.returnCode = returnCode;
15367            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15368            for (int i = 0; i < childCount; i++) {
15369                addedChildPackages.valueAt(i).returnCode = returnCode;
15370            }
15371        }
15372
15373        private void setReturnMessage(String returnMsg) {
15374            this.returnMsg = returnMsg;
15375            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15376            for (int i = 0; i < childCount; i++) {
15377                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15378            }
15379        }
15380
15381        // In some error cases we want to convey more info back to the observer
15382        String origPackage;
15383        String origPermission;
15384    }
15385
15386    /*
15387     * Install a non-existing package.
15388     */
15389    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15390            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15391            String volumeUuid, PackageInstalledInfo res, int installReason) {
15392        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15393
15394        // Remember this for later, in case we need to rollback this install
15395        String pkgName = pkg.packageName;
15396
15397        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15398
15399        synchronized(mPackages) {
15400            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15401            if (renamedPackage != null) {
15402                // A package with the same name is already installed, though
15403                // it has been renamed to an older name.  The package we
15404                // are trying to install should be installed as an update to
15405                // the existing one, but that has not been requested, so bail.
15406                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15407                        + " without first uninstalling package running as "
15408                        + renamedPackage);
15409                return;
15410            }
15411            if (mPackages.containsKey(pkgName)) {
15412                // Don't allow installation over an existing package with the same name.
15413                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15414                        + " without first uninstalling.");
15415                return;
15416            }
15417        }
15418
15419        try {
15420            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15421                    System.currentTimeMillis(), user);
15422
15423            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15424
15425            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15426                prepareAppDataAfterInstallLIF(newPackage);
15427
15428            } else {
15429                // Remove package from internal structures, but keep around any
15430                // data that might have already existed
15431                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15432                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15433            }
15434        } catch (PackageManagerException e) {
15435            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15436        }
15437
15438        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15439    }
15440
15441    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15442        try (DigestInputStream digestStream =
15443                new DigestInputStream(new FileInputStream(file), digest)) {
15444            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15445        }
15446    }
15447
15448    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15449            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15450            PackageInstalledInfo res, int installReason) {
15451        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15452
15453        final PackageParser.Package oldPackage;
15454        final PackageSetting ps;
15455        final String pkgName = pkg.packageName;
15456        final int[] allUsers;
15457        final int[] installedUsers;
15458
15459        synchronized(mPackages) {
15460            oldPackage = mPackages.get(pkgName);
15461            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15462
15463            // don't allow upgrade to target a release SDK from a pre-release SDK
15464            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15465                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15466            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15467                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15468            if (oldTargetsPreRelease
15469                    && !newTargetsPreRelease
15470                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15471                Slog.w(TAG, "Can't install package targeting released sdk");
15472                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15473                return;
15474            }
15475
15476            ps = mSettings.mPackages.get(pkgName);
15477
15478            // verify signatures are valid
15479            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15480            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15481                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15482                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15483                            "New package not signed by keys specified by upgrade-keysets: "
15484                                    + pkgName);
15485                    return;
15486                }
15487            } else {
15488                // default to original signature matching
15489                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15490                        != PackageManager.SIGNATURE_MATCH) {
15491                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15492                            "New package has a different signature: " + pkgName);
15493                    return;
15494                }
15495            }
15496
15497            // don't allow a system upgrade unless the upgrade hash matches
15498            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15499                byte[] digestBytes = null;
15500                try {
15501                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15502                    updateDigest(digest, new File(pkg.baseCodePath));
15503                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15504                        for (String path : pkg.splitCodePaths) {
15505                            updateDigest(digest, new File(path));
15506                        }
15507                    }
15508                    digestBytes = digest.digest();
15509                } catch (NoSuchAlgorithmException | IOException e) {
15510                    res.setError(INSTALL_FAILED_INVALID_APK,
15511                            "Could not compute hash: " + pkgName);
15512                    return;
15513                }
15514                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15515                    res.setError(INSTALL_FAILED_INVALID_APK,
15516                            "New package fails restrict-update check: " + pkgName);
15517                    return;
15518                }
15519                // retain upgrade restriction
15520                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15521            }
15522
15523            // Check for shared user id changes
15524            String invalidPackageName =
15525                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15526            if (invalidPackageName != null) {
15527                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15528                        "Package " + invalidPackageName + " tried to change user "
15529                                + oldPackage.mSharedUserId);
15530                return;
15531            }
15532
15533            // check if the new package supports all of the abis which the old package supports
15534            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
15535            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
15536            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
15537                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15538                        "Update to package " + pkgName + " doesn't support multi arch");
15539                return;
15540            }
15541
15542            // In case of rollback, remember per-user/profile install state
15543            allUsers = sUserManager.getUserIds();
15544            installedUsers = ps.queryInstalledUsers(allUsers, true);
15545
15546            // don't allow an upgrade from full to ephemeral
15547            if (isInstantApp) {
15548                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15549                    for (int currentUser : allUsers) {
15550                        if (!ps.getInstantApp(currentUser)) {
15551                            // can't downgrade from full to instant
15552                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15553                                    + " for user: " + currentUser);
15554                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15555                            return;
15556                        }
15557                    }
15558                } else if (!ps.getInstantApp(user.getIdentifier())) {
15559                    // can't downgrade from full to instant
15560                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15561                            + " for user: " + user.getIdentifier());
15562                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15563                    return;
15564                }
15565            }
15566        }
15567
15568        // Update what is removed
15569        res.removedInfo = new PackageRemovedInfo(this);
15570        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15571        res.removedInfo.removedPackage = oldPackage.packageName;
15572        res.removedInfo.installerPackageName = ps.installerPackageName;
15573        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15574        res.removedInfo.isUpdate = true;
15575        res.removedInfo.origUsers = installedUsers;
15576        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15577        for (int i = 0; i < installedUsers.length; i++) {
15578            final int userId = installedUsers[i];
15579            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15580        }
15581
15582        final int childCount = (oldPackage.childPackages != null)
15583                ? oldPackage.childPackages.size() : 0;
15584        for (int i = 0; i < childCount; i++) {
15585            boolean childPackageUpdated = false;
15586            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15587            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15588            if (res.addedChildPackages != null) {
15589                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15590                if (childRes != null) {
15591                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15592                    childRes.removedInfo.removedPackage = childPkg.packageName;
15593                    if (childPs != null) {
15594                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15595                    }
15596                    childRes.removedInfo.isUpdate = true;
15597                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15598                    childPackageUpdated = true;
15599                }
15600            }
15601            if (!childPackageUpdated) {
15602                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15603                childRemovedRes.removedPackage = childPkg.packageName;
15604                if (childPs != null) {
15605                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15606                }
15607                childRemovedRes.isUpdate = false;
15608                childRemovedRes.dataRemoved = true;
15609                synchronized (mPackages) {
15610                    if (childPs != null) {
15611                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15612                    }
15613                }
15614                if (res.removedInfo.removedChildPackages == null) {
15615                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15616                }
15617                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15618            }
15619        }
15620
15621        boolean sysPkg = (isSystemApp(oldPackage));
15622        if (sysPkg) {
15623            // Set the system/privileged/oem/vendor flags as needed
15624            final boolean privileged =
15625                    (oldPackage.applicationInfo.privateFlags
15626                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15627            final boolean oem =
15628                    (oldPackage.applicationInfo.privateFlags
15629                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15630            final boolean vendor =
15631                    (oldPackage.applicationInfo.privateFlags
15632                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
15633            final @ParseFlags int systemParseFlags = parseFlags;
15634            final @ScanFlags int systemScanFlags = scanFlags
15635                    | SCAN_AS_SYSTEM
15636                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
15637                    | (oem ? SCAN_AS_OEM : 0)
15638                    | (vendor ? SCAN_AS_VENDOR : 0);
15639
15640            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
15641                    user, allUsers, installerPackageName, res, installReason);
15642        } else {
15643            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
15644                    user, allUsers, installerPackageName, res, installReason);
15645        }
15646    }
15647
15648    @Override
15649    public List<String> getPreviousCodePaths(String packageName) {
15650        final int callingUid = Binder.getCallingUid();
15651        final List<String> result = new ArrayList<>();
15652        if (getInstantAppPackageName(callingUid) != null) {
15653            return result;
15654        }
15655        final PackageSetting ps = mSettings.mPackages.get(packageName);
15656        if (ps != null
15657                && ps.oldCodePaths != null
15658                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15659            result.addAll(ps.oldCodePaths);
15660        }
15661        return result;
15662    }
15663
15664    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15665            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15666            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
15667            String installerPackageName, PackageInstalledInfo res, int installReason) {
15668        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15669                + deletedPackage);
15670
15671        String pkgName = deletedPackage.packageName;
15672        boolean deletedPkg = true;
15673        boolean addedPkg = false;
15674        boolean updatedSettings = false;
15675        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15676        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15677                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15678
15679        final long origUpdateTime = (pkg.mExtras != null)
15680                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15681
15682        // First delete the existing package while retaining the data directory
15683        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15684                res.removedInfo, true, pkg)) {
15685            // If the existing package wasn't successfully deleted
15686            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15687            deletedPkg = false;
15688        } else {
15689            // Successfully deleted the old package; proceed with replace.
15690
15691            // If deleted package lived in a container, give users a chance to
15692            // relinquish resources before killing.
15693            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15694                if (DEBUG_INSTALL) {
15695                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15696                }
15697                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15698                final ArrayList<String> pkgList = new ArrayList<String>(1);
15699                pkgList.add(deletedPackage.applicationInfo.packageName);
15700                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15701            }
15702
15703            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15704                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15705            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15706
15707            try {
15708                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
15709                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15710                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15711                        installReason);
15712
15713                // Update the in-memory copy of the previous code paths.
15714                PackageSetting ps = mSettings.mPackages.get(pkgName);
15715                if (!killApp) {
15716                    if (ps.oldCodePaths == null) {
15717                        ps.oldCodePaths = new ArraySet<>();
15718                    }
15719                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15720                    if (deletedPackage.splitCodePaths != null) {
15721                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15722                    }
15723                } else {
15724                    ps.oldCodePaths = null;
15725                }
15726                if (ps.childPackageNames != null) {
15727                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15728                        final String childPkgName = ps.childPackageNames.get(i);
15729                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15730                        childPs.oldCodePaths = ps.oldCodePaths;
15731                    }
15732                }
15733                // set instant app status, but, only if it's explicitly specified
15734                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15735                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15736                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15737                prepareAppDataAfterInstallLIF(newPackage);
15738                addedPkg = true;
15739                mDexManager.notifyPackageUpdated(newPackage.packageName,
15740                        newPackage.baseCodePath, newPackage.splitCodePaths);
15741            } catch (PackageManagerException e) {
15742                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15743            }
15744        }
15745
15746        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15747            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15748
15749            // Revert all internal state mutations and added folders for the failed install
15750            if (addedPkg) {
15751                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15752                        res.removedInfo, true, null);
15753            }
15754
15755            // Restore the old package
15756            if (deletedPkg) {
15757                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15758                File restoreFile = new File(deletedPackage.codePath);
15759                // Parse old package
15760                boolean oldExternal = isExternal(deletedPackage);
15761                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15762                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15763                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15764                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15765                try {
15766                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15767                            null);
15768                } catch (PackageManagerException e) {
15769                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15770                            + e.getMessage());
15771                    return;
15772                }
15773
15774                synchronized (mPackages) {
15775                    // Ensure the installer package name up to date
15776                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15777
15778                    // Update permissions for restored package
15779                    mPermissionManager.updatePermissions(
15780                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15781                            mPermissionCallback);
15782
15783                    mSettings.writeLPr();
15784                }
15785
15786                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15787            }
15788        } else {
15789            synchronized (mPackages) {
15790                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15791                if (ps != null) {
15792                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15793                    if (res.removedInfo.removedChildPackages != null) {
15794                        final int childCount = res.removedInfo.removedChildPackages.size();
15795                        // Iterate in reverse as we may modify the collection
15796                        for (int i = childCount - 1; i >= 0; i--) {
15797                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15798                            if (res.addedChildPackages.containsKey(childPackageName)) {
15799                                res.removedInfo.removedChildPackages.removeAt(i);
15800                            } else {
15801                                PackageRemovedInfo childInfo = res.removedInfo
15802                                        .removedChildPackages.valueAt(i);
15803                                childInfo.removedForAllUsers = mPackages.get(
15804                                        childInfo.removedPackage) == null;
15805                            }
15806                        }
15807                    }
15808                }
15809            }
15810        }
15811    }
15812
15813    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15814            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15815            final @ScanFlags int scanFlags, UserHandle user,
15816            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15817            int installReason) {
15818        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15819                + ", old=" + deletedPackage);
15820
15821        final boolean disabledSystem;
15822
15823        // Remove existing system package
15824        removePackageLI(deletedPackage, true);
15825
15826        synchronized (mPackages) {
15827            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15828        }
15829        if (!disabledSystem) {
15830            // We didn't need to disable the .apk as a current system package,
15831            // which means we are replacing another update that is already
15832            // installed.  We need to make sure to delete the older one's .apk.
15833            res.removedInfo.args = createInstallArgsForExisting(0,
15834                    deletedPackage.applicationInfo.getCodePath(),
15835                    deletedPackage.applicationInfo.getResourcePath(),
15836                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15837        } else {
15838            res.removedInfo.args = null;
15839        }
15840
15841        // Successfully disabled the old package. Now proceed with re-installation
15842        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15843                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15844        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15845
15846        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15847        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15848                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15849
15850        PackageParser.Package newPackage = null;
15851        try {
15852            // Add the package to the internal data structures
15853            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
15854
15855            // Set the update and install times
15856            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15857            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15858                    System.currentTimeMillis());
15859
15860            // Update the package dynamic state if succeeded
15861            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15862                // Now that the install succeeded make sure we remove data
15863                // directories for any child package the update removed.
15864                final int deletedChildCount = (deletedPackage.childPackages != null)
15865                        ? deletedPackage.childPackages.size() : 0;
15866                final int newChildCount = (newPackage.childPackages != null)
15867                        ? newPackage.childPackages.size() : 0;
15868                for (int i = 0; i < deletedChildCount; i++) {
15869                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15870                    boolean childPackageDeleted = true;
15871                    for (int j = 0; j < newChildCount; j++) {
15872                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15873                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15874                            childPackageDeleted = false;
15875                            break;
15876                        }
15877                    }
15878                    if (childPackageDeleted) {
15879                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15880                                deletedChildPkg.packageName);
15881                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15882                            PackageRemovedInfo removedChildRes = res.removedInfo
15883                                    .removedChildPackages.get(deletedChildPkg.packageName);
15884                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15885                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15886                        }
15887                    }
15888                }
15889
15890                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15891                        installReason);
15892                prepareAppDataAfterInstallLIF(newPackage);
15893
15894                mDexManager.notifyPackageUpdated(newPackage.packageName,
15895                            newPackage.baseCodePath, newPackage.splitCodePaths);
15896            }
15897        } catch (PackageManagerException e) {
15898            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15899            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15900        }
15901
15902        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15903            // Re installation failed. Restore old information
15904            // Remove new pkg information
15905            if (newPackage != null) {
15906                removeInstalledPackageLI(newPackage, true);
15907            }
15908            // Add back the old system package
15909            try {
15910                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15911            } catch (PackageManagerException e) {
15912                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15913            }
15914
15915            synchronized (mPackages) {
15916                if (disabledSystem) {
15917                    enableSystemPackageLPw(deletedPackage);
15918                }
15919
15920                // Ensure the installer package name up to date
15921                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15922
15923                // Update permissions for restored package
15924                mPermissionManager.updatePermissions(
15925                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15926                        mPermissionCallback);
15927
15928                mSettings.writeLPr();
15929            }
15930
15931            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15932                    + " after failed upgrade");
15933        }
15934    }
15935
15936    /**
15937     * Checks whether the parent or any of the child packages have a change shared
15938     * user. For a package to be a valid update the shred users of the parent and
15939     * the children should match. We may later support changing child shared users.
15940     * @param oldPkg The updated package.
15941     * @param newPkg The update package.
15942     * @return The shared user that change between the versions.
15943     */
15944    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15945            PackageParser.Package newPkg) {
15946        // Check parent shared user
15947        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15948            return newPkg.packageName;
15949        }
15950        // Check child shared users
15951        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15952        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15953        for (int i = 0; i < newChildCount; i++) {
15954            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15955            // If this child was present, did it have the same shared user?
15956            for (int j = 0; j < oldChildCount; j++) {
15957                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15958                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15959                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15960                    return newChildPkg.packageName;
15961                }
15962            }
15963        }
15964        return null;
15965    }
15966
15967    private void removeNativeBinariesLI(PackageSetting ps) {
15968        // Remove the lib path for the parent package
15969        if (ps != null) {
15970            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15971            // Remove the lib path for the child packages
15972            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15973            for (int i = 0; i < childCount; i++) {
15974                PackageSetting childPs = null;
15975                synchronized (mPackages) {
15976                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15977                }
15978                if (childPs != null) {
15979                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15980                            .legacyNativeLibraryPathString);
15981                }
15982            }
15983        }
15984    }
15985
15986    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15987        // Enable the parent package
15988        mSettings.enableSystemPackageLPw(pkg.packageName);
15989        // Enable the child packages
15990        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15991        for (int i = 0; i < childCount; i++) {
15992            PackageParser.Package childPkg = pkg.childPackages.get(i);
15993            mSettings.enableSystemPackageLPw(childPkg.packageName);
15994        }
15995    }
15996
15997    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15998            PackageParser.Package newPkg) {
15999        // Disable the parent package (parent always replaced)
16000        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16001        // Disable the child packages
16002        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16003        for (int i = 0; i < childCount; i++) {
16004            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16005            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16006            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16007        }
16008        return disabled;
16009    }
16010
16011    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16012            String installerPackageName) {
16013        // Enable the parent package
16014        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16015        // Enable the child packages
16016        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16017        for (int i = 0; i < childCount; i++) {
16018            PackageParser.Package childPkg = pkg.childPackages.get(i);
16019            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16020        }
16021    }
16022
16023    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16024            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16025        // Update the parent package setting
16026        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16027                res, user, installReason);
16028        // Update the child packages setting
16029        final int childCount = (newPackage.childPackages != null)
16030                ? newPackage.childPackages.size() : 0;
16031        for (int i = 0; i < childCount; i++) {
16032            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16033            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16034            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16035                    childRes.origUsers, childRes, user, installReason);
16036        }
16037    }
16038
16039    private void updateSettingsInternalLI(PackageParser.Package pkg,
16040            String installerPackageName, int[] allUsers, int[] installedForUsers,
16041            PackageInstalledInfo res, UserHandle user, int installReason) {
16042        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16043
16044        String pkgName = pkg.packageName;
16045        synchronized (mPackages) {
16046            //write settings. the installStatus will be incomplete at this stage.
16047            //note that the new package setting would have already been
16048            //added to mPackages. It hasn't been persisted yet.
16049            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16050            // TODO: Remove this write? It's also written at the end of this method
16051            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16052            mSettings.writeLPr();
16053            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16054        }
16055
16056        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16057        synchronized (mPackages) {
16058// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16059            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16060                    mPermissionCallback);
16061            // For system-bundled packages, we assume that installing an upgraded version
16062            // of the package implies that the user actually wants to run that new code,
16063            // so we enable the package.
16064            PackageSetting ps = mSettings.mPackages.get(pkgName);
16065            final int userId = user.getIdentifier();
16066            if (ps != null) {
16067                if (isSystemApp(pkg)) {
16068                    if (DEBUG_INSTALL) {
16069                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16070                    }
16071                    // Enable system package for requested users
16072                    if (res.origUsers != null) {
16073                        for (int origUserId : res.origUsers) {
16074                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16075                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16076                                        origUserId, installerPackageName);
16077                            }
16078                        }
16079                    }
16080                    // Also convey the prior install/uninstall state
16081                    if (allUsers != null && installedForUsers != null) {
16082                        for (int currentUserId : allUsers) {
16083                            final boolean installed = ArrayUtils.contains(
16084                                    installedForUsers, currentUserId);
16085                            if (DEBUG_INSTALL) {
16086                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16087                            }
16088                            ps.setInstalled(installed, currentUserId);
16089                        }
16090                        // these install state changes will be persisted in the
16091                        // upcoming call to mSettings.writeLPr().
16092                    }
16093                }
16094                // It's implied that when a user requests installation, they want the app to be
16095                // installed and enabled.
16096                if (userId != UserHandle.USER_ALL) {
16097                    ps.setInstalled(true, userId);
16098                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16099                }
16100
16101                // When replacing an existing package, preserve the original install reason for all
16102                // users that had the package installed before.
16103                final Set<Integer> previousUserIds = new ArraySet<>();
16104                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16105                    final int installReasonCount = res.removedInfo.installReasons.size();
16106                    for (int i = 0; i < installReasonCount; i++) {
16107                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16108                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16109                        ps.setInstallReason(previousInstallReason, previousUserId);
16110                        previousUserIds.add(previousUserId);
16111                    }
16112                }
16113
16114                // Set install reason for users that are having the package newly installed.
16115                if (userId == UserHandle.USER_ALL) {
16116                    for (int currentUserId : sUserManager.getUserIds()) {
16117                        if (!previousUserIds.contains(currentUserId)) {
16118                            ps.setInstallReason(installReason, currentUserId);
16119                        }
16120                    }
16121                } else if (!previousUserIds.contains(userId)) {
16122                    ps.setInstallReason(installReason, userId);
16123                }
16124                mSettings.writeKernelMappingLPr(ps);
16125            }
16126            res.name = pkgName;
16127            res.uid = pkg.applicationInfo.uid;
16128            res.pkg = pkg;
16129            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16130            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16131            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16132            //to update install status
16133            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16134            mSettings.writeLPr();
16135            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16136        }
16137
16138        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16139    }
16140
16141    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16142        try {
16143            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16144            installPackageLI(args, res);
16145        } finally {
16146            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16147        }
16148    }
16149
16150    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16151        final int installFlags = args.installFlags;
16152        final String installerPackageName = args.installerPackageName;
16153        final String volumeUuid = args.volumeUuid;
16154        final File tmpPackageFile = new File(args.getCodePath());
16155        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16156        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16157                || (args.volumeUuid != null));
16158        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16159        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16160        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16161        final boolean virtualPreload =
16162                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16163        boolean replace = false;
16164        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16165        if (args.move != null) {
16166            // moving a complete application; perform an initial scan on the new install location
16167            scanFlags |= SCAN_INITIAL;
16168        }
16169        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16170            scanFlags |= SCAN_DONT_KILL_APP;
16171        }
16172        if (instantApp) {
16173            scanFlags |= SCAN_AS_INSTANT_APP;
16174        }
16175        if (fullApp) {
16176            scanFlags |= SCAN_AS_FULL_APP;
16177        }
16178        if (virtualPreload) {
16179            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16180        }
16181
16182        // Result object to be returned
16183        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16184        res.installerPackageName = installerPackageName;
16185
16186        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16187
16188        // Sanity check
16189        if (instantApp && (forwardLocked || onExternal)) {
16190            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16191                    + " external=" + onExternal);
16192            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16193            return;
16194        }
16195
16196        // Retrieve PackageSettings and parse package
16197        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16198                | PackageParser.PARSE_ENFORCE_CODE
16199                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16200                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16201                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16202                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16203        PackageParser pp = new PackageParser();
16204        pp.setSeparateProcesses(mSeparateProcesses);
16205        pp.setDisplayMetrics(mMetrics);
16206        pp.setCallback(mPackageParserCallback);
16207
16208        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16209        final PackageParser.Package pkg;
16210        try {
16211            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16212        } catch (PackageParserException e) {
16213            res.setError("Failed parse during installPackageLI", e);
16214            return;
16215        } finally {
16216            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16217        }
16218
16219        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16220        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16221            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
16222            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16223                    "Instant app package must target O");
16224            return;
16225        }
16226        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16227            Slog.w(TAG, "Instant app package " + pkg.packageName
16228                    + " does not target targetSandboxVersion 2");
16229            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16230                    "Instant app package must use targetSanboxVersion 2");
16231            return;
16232        }
16233
16234        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16235            // Static shared libraries have synthetic package names
16236            renameStaticSharedLibraryPackage(pkg);
16237
16238            // No static shared libs on external storage
16239            if (onExternal) {
16240                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16241                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16242                        "Packages declaring static-shared libs cannot be updated");
16243                return;
16244            }
16245        }
16246
16247        // If we are installing a clustered package add results for the children
16248        if (pkg.childPackages != null) {
16249            synchronized (mPackages) {
16250                final int childCount = pkg.childPackages.size();
16251                for (int i = 0; i < childCount; i++) {
16252                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16253                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16254                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16255                    childRes.pkg = childPkg;
16256                    childRes.name = childPkg.packageName;
16257                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16258                    if (childPs != null) {
16259                        childRes.origUsers = childPs.queryInstalledUsers(
16260                                sUserManager.getUserIds(), true);
16261                    }
16262                    if ((mPackages.containsKey(childPkg.packageName))) {
16263                        childRes.removedInfo = new PackageRemovedInfo(this);
16264                        childRes.removedInfo.removedPackage = childPkg.packageName;
16265                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16266                    }
16267                    if (res.addedChildPackages == null) {
16268                        res.addedChildPackages = new ArrayMap<>();
16269                    }
16270                    res.addedChildPackages.put(childPkg.packageName, childRes);
16271                }
16272            }
16273        }
16274
16275        // If package doesn't declare API override, mark that we have an install
16276        // time CPU ABI override.
16277        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16278            pkg.cpuAbiOverride = args.abiOverride;
16279        }
16280
16281        String pkgName = res.name = pkg.packageName;
16282        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16283            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16284                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16285                return;
16286            }
16287        }
16288
16289        try {
16290            // either use what we've been given or parse directly from the APK
16291            if (args.certificates != null) {
16292                try {
16293                    PackageParser.populateCertificates(pkg, args.certificates);
16294                } catch (PackageParserException e) {
16295                    // there was something wrong with the certificates we were given;
16296                    // try to pull them from the APK
16297                    PackageParser.collectCertificates(pkg, parseFlags);
16298                }
16299            } else {
16300                PackageParser.collectCertificates(pkg, parseFlags);
16301            }
16302        } catch (PackageParserException e) {
16303            res.setError("Failed collect during installPackageLI", e);
16304            return;
16305        }
16306
16307        // Get rid of all references to package scan path via parser.
16308        pp = null;
16309        String oldCodePath = null;
16310        boolean systemApp = false;
16311        synchronized (mPackages) {
16312            // Check if installing already existing package
16313            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16314                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16315                if (pkg.mOriginalPackages != null
16316                        && pkg.mOriginalPackages.contains(oldName)
16317                        && mPackages.containsKey(oldName)) {
16318                    // This package is derived from an original package,
16319                    // and this device has been updating from that original
16320                    // name.  We must continue using the original name, so
16321                    // rename the new package here.
16322                    pkg.setPackageName(oldName);
16323                    pkgName = pkg.packageName;
16324                    replace = true;
16325                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16326                            + oldName + " pkgName=" + pkgName);
16327                } else if (mPackages.containsKey(pkgName)) {
16328                    // This package, under its official name, already exists
16329                    // on the device; we should replace it.
16330                    replace = true;
16331                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16332                }
16333
16334                // Child packages are installed through the parent package
16335                if (pkg.parentPackage != null) {
16336                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16337                            "Package " + pkg.packageName + " is child of package "
16338                                    + pkg.parentPackage.parentPackage + ". Child packages "
16339                                    + "can be updated only through the parent package.");
16340                    return;
16341                }
16342
16343                if (replace) {
16344                    // Prevent apps opting out from runtime permissions
16345                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16346                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16347                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16348                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16349                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16350                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16351                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16352                                        + " doesn't support runtime permissions but the old"
16353                                        + " target SDK " + oldTargetSdk + " does.");
16354                        return;
16355                    }
16356                    // Prevent apps from downgrading their targetSandbox.
16357                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16358                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16359                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16360                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16361                                "Package " + pkg.packageName + " new target sandbox "
16362                                + newTargetSandbox + " is incompatible with the previous value of"
16363                                + oldTargetSandbox + ".");
16364                        return;
16365                    }
16366
16367                    // Prevent installing of child packages
16368                    if (oldPackage.parentPackage != null) {
16369                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16370                                "Package " + pkg.packageName + " is child of package "
16371                                        + oldPackage.parentPackage + ". Child packages "
16372                                        + "can be updated only through the parent package.");
16373                        return;
16374                    }
16375                }
16376            }
16377
16378            PackageSetting ps = mSettings.mPackages.get(pkgName);
16379            if (ps != null) {
16380                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16381
16382                // Static shared libs have same package with different versions where
16383                // we internally use a synthetic package name to allow multiple versions
16384                // of the same package, therefore we need to compare signatures against
16385                // the package setting for the latest library version.
16386                PackageSetting signatureCheckPs = ps;
16387                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16388                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16389                    if (libraryEntry != null) {
16390                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16391                    }
16392                }
16393
16394                // Quick sanity check that we're signed correctly if updating;
16395                // we'll check this again later when scanning, but we want to
16396                // bail early here before tripping over redefined permissions.
16397                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16398                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16399                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16400                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16401                                + pkg.packageName + " upgrade keys do not match the "
16402                                + "previously installed version");
16403                        return;
16404                    }
16405                } else {
16406                    try {
16407                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16408                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16409                        final boolean compatMatch = verifySignatures(
16410                                signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover);
16411                        // The new KeySets will be re-added later in the scanning process.
16412                        if (compatMatch) {
16413                            synchronized (mPackages) {
16414                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16415                            }
16416                        }
16417                    } catch (PackageManagerException e) {
16418                        res.setError(e.error, e.getMessage());
16419                        return;
16420                    }
16421                }
16422
16423                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16424                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16425                    systemApp = (ps.pkg.applicationInfo.flags &
16426                            ApplicationInfo.FLAG_SYSTEM) != 0;
16427                }
16428                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16429            }
16430
16431            int N = pkg.permissions.size();
16432            for (int i = N-1; i >= 0; i--) {
16433                final PackageParser.Permission perm = pkg.permissions.get(i);
16434                final BasePermission bp =
16435                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16436
16437                // Don't allow anyone but the system to define ephemeral permissions.
16438                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16439                        && !systemApp) {
16440                    Slog.w(TAG, "Non-System package " + pkg.packageName
16441                            + " attempting to delcare ephemeral permission "
16442                            + perm.info.name + "; Removing ephemeral.");
16443                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16444                }
16445
16446                // Check whether the newly-scanned package wants to define an already-defined perm
16447                if (bp != null) {
16448                    // If the defining package is signed with our cert, it's okay.  This
16449                    // also includes the "updating the same package" case, of course.
16450                    // "updating same package" could also involve key-rotation.
16451                    final boolean sigsOk;
16452                    final String sourcePackageName = bp.getSourcePackageName();
16453                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16454                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16455                    if (sourcePackageName.equals(pkg.packageName)
16456                            && (ksms.shouldCheckUpgradeKeySetLocked(
16457                                    sourcePackageSetting, scanFlags))) {
16458                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16459                    } else {
16460                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16461                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16462                    }
16463                    if (!sigsOk) {
16464                        // If the owning package is the system itself, we log but allow
16465                        // install to proceed; we fail the install on all other permission
16466                        // redefinitions.
16467                        if (!sourcePackageName.equals("android")) {
16468                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16469                                    + pkg.packageName + " attempting to redeclare permission "
16470                                    + perm.info.name + " already owned by " + sourcePackageName);
16471                            res.origPermission = perm.info.name;
16472                            res.origPackage = sourcePackageName;
16473                            return;
16474                        } else {
16475                            Slog.w(TAG, "Package " + pkg.packageName
16476                                    + " attempting to redeclare system permission "
16477                                    + perm.info.name + "; ignoring new declaration");
16478                            pkg.permissions.remove(i);
16479                        }
16480                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16481                        // Prevent apps to change protection level to dangerous from any other
16482                        // type as this would allow a privilege escalation where an app adds a
16483                        // normal/signature permission in other app's group and later redefines
16484                        // it as dangerous leading to the group auto-grant.
16485                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16486                                == PermissionInfo.PROTECTION_DANGEROUS) {
16487                            if (bp != null && !bp.isRuntime()) {
16488                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16489                                        + "non-runtime permission " + perm.info.name
16490                                        + " to runtime; keeping old protection level");
16491                                perm.info.protectionLevel = bp.getProtectionLevel();
16492                            }
16493                        }
16494                    }
16495                }
16496            }
16497        }
16498
16499        if (systemApp) {
16500            if (onExternal) {
16501                // Abort update; system app can't be replaced with app on sdcard
16502                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16503                        "Cannot install updates to system apps on sdcard");
16504                return;
16505            } else if (instantApp) {
16506                // Abort update; system app can't be replaced with an instant app
16507                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16508                        "Cannot update a system app with an instant app");
16509                return;
16510            }
16511        }
16512
16513        if (args.move != null) {
16514            // We did an in-place move, so dex is ready to roll
16515            scanFlags |= SCAN_NO_DEX;
16516            scanFlags |= SCAN_MOVE;
16517
16518            synchronized (mPackages) {
16519                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16520                if (ps == null) {
16521                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16522                            "Missing settings for moved package " + pkgName);
16523                }
16524
16525                // We moved the entire application as-is, so bring over the
16526                // previously derived ABI information.
16527                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16528                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16529            }
16530
16531        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16532            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16533            scanFlags |= SCAN_NO_DEX;
16534
16535            try {
16536                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16537                    args.abiOverride : pkg.cpuAbiOverride);
16538                final boolean extractNativeLibs = !pkg.isLibrary();
16539                derivePackageAbi(pkg, abiOverride, extractNativeLibs, mAppLib32InstallDir);
16540            } catch (PackageManagerException pme) {
16541                Slog.e(TAG, "Error deriving application ABI", pme);
16542                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16543                return;
16544            }
16545
16546            // Shared libraries for the package need to be updated.
16547            synchronized (mPackages) {
16548                try {
16549                    updateSharedLibrariesLPr(pkg, null);
16550                } catch (PackageManagerException e) {
16551                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16552                }
16553            }
16554        }
16555
16556        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16557            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16558            return;
16559        }
16560
16561        if (!instantApp) {
16562            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16563        } else {
16564            if (DEBUG_DOMAIN_VERIFICATION) {
16565                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16566            }
16567        }
16568
16569        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16570                "installPackageLI")) {
16571            if (replace) {
16572                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16573                    // Static libs have a synthetic package name containing the version
16574                    // and cannot be updated as an update would get a new package name,
16575                    // unless this is the exact same version code which is useful for
16576                    // development.
16577                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16578                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16579                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16580                                + "static-shared libs cannot be updated");
16581                        return;
16582                    }
16583                }
16584                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
16585                        installerPackageName, res, args.installReason);
16586            } else {
16587                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16588                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16589            }
16590        }
16591
16592        // Check whether we need to dexopt the app.
16593        //
16594        // NOTE: it is IMPORTANT to call dexopt:
16595        //   - after doRename which will sync the package data from PackageParser.Package and its
16596        //     corresponding ApplicationInfo.
16597        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
16598        //     uid of the application (pkg.applicationInfo.uid).
16599        //     This update happens in place!
16600        //
16601        // We only need to dexopt if the package meets ALL of the following conditions:
16602        //   1) it is not forward locked.
16603        //   2) it is not on on an external ASEC container.
16604        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16605        //
16606        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16607        // complete, so we skip this step during installation. Instead, we'll take extra time
16608        // the first time the instant app starts. It's preferred to do it this way to provide
16609        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16610        // middle of running an instant app. The default behaviour can be overridden
16611        // via gservices.
16612        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
16613                && !forwardLocked
16614                && !pkg.applicationInfo.isExternalAsec()
16615                && (!instantApp || Global.getInt(mContext.getContentResolver(),
16616                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16617
16618        if (performDexopt) {
16619            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16620            // Do not run PackageDexOptimizer through the local performDexOpt
16621            // method because `pkg` may not be in `mPackages` yet.
16622            //
16623            // Also, don't fail application installs if the dexopt step fails.
16624            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16625                    REASON_INSTALL,
16626                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
16627            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16628                    null /* instructionSets */,
16629                    getOrCreateCompilerPackageStats(pkg),
16630                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16631                    dexoptOptions);
16632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16633        }
16634
16635        // Notify BackgroundDexOptService that the package has been changed.
16636        // If this is an update of a package which used to fail to compile,
16637        // BackgroundDexOptService will remove it from its blacklist.
16638        // TODO: Layering violation
16639        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16640
16641        synchronized (mPackages) {
16642            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16643            if (ps != null) {
16644                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16645                ps.setUpdateAvailable(false /*updateAvailable*/);
16646            }
16647
16648            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16649            for (int i = 0; i < childCount; i++) {
16650                PackageParser.Package childPkg = pkg.childPackages.get(i);
16651                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16652                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16653                if (childPs != null) {
16654                    childRes.newUsers = childPs.queryInstalledUsers(
16655                            sUserManager.getUserIds(), true);
16656                }
16657            }
16658
16659            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16660                updateSequenceNumberLP(ps, res.newUsers);
16661                updateInstantAppInstallerLocked(pkgName);
16662            }
16663        }
16664    }
16665
16666    private void startIntentFilterVerifications(int userId, boolean replacing,
16667            PackageParser.Package pkg) {
16668        if (mIntentFilterVerifierComponent == null) {
16669            Slog.w(TAG, "No IntentFilter verification will not be done as "
16670                    + "there is no IntentFilterVerifier available!");
16671            return;
16672        }
16673
16674        final int verifierUid = getPackageUid(
16675                mIntentFilterVerifierComponent.getPackageName(),
16676                MATCH_DEBUG_TRIAGED_MISSING,
16677                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16678
16679        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16680        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16681        mHandler.sendMessage(msg);
16682
16683        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16684        for (int i = 0; i < childCount; i++) {
16685            PackageParser.Package childPkg = pkg.childPackages.get(i);
16686            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16687            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16688            mHandler.sendMessage(msg);
16689        }
16690    }
16691
16692    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16693            PackageParser.Package pkg) {
16694        int size = pkg.activities.size();
16695        if (size == 0) {
16696            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16697                    "No activity, so no need to verify any IntentFilter!");
16698            return;
16699        }
16700
16701        final boolean hasDomainURLs = hasDomainURLs(pkg);
16702        if (!hasDomainURLs) {
16703            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16704                    "No domain URLs, so no need to verify any IntentFilter!");
16705            return;
16706        }
16707
16708        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16709                + " if any IntentFilter from the " + size
16710                + " Activities needs verification ...");
16711
16712        int count = 0;
16713        final String packageName = pkg.packageName;
16714
16715        synchronized (mPackages) {
16716            // If this is a new install and we see that we've already run verification for this
16717            // package, we have nothing to do: it means the state was restored from backup.
16718            if (!replacing) {
16719                IntentFilterVerificationInfo ivi =
16720                        mSettings.getIntentFilterVerificationLPr(packageName);
16721                if (ivi != null) {
16722                    if (DEBUG_DOMAIN_VERIFICATION) {
16723                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16724                                + ivi.getStatusString());
16725                    }
16726                    return;
16727                }
16728            }
16729
16730            // If any filters need to be verified, then all need to be.
16731            boolean needToVerify = false;
16732            for (PackageParser.Activity a : pkg.activities) {
16733                for (ActivityIntentInfo filter : a.intents) {
16734                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16735                        if (DEBUG_DOMAIN_VERIFICATION) {
16736                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16737                        }
16738                        needToVerify = true;
16739                        break;
16740                    }
16741                }
16742            }
16743
16744            if (needToVerify) {
16745                final int verificationId = mIntentFilterVerificationToken++;
16746                for (PackageParser.Activity a : pkg.activities) {
16747                    for (ActivityIntentInfo filter : a.intents) {
16748                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16749                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16750                                    "Verification needed for IntentFilter:" + filter.toString());
16751                            mIntentFilterVerifier.addOneIntentFilterVerification(
16752                                    verifierUid, userId, verificationId, filter, packageName);
16753                            count++;
16754                        }
16755                    }
16756                }
16757            }
16758        }
16759
16760        if (count > 0) {
16761            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16762                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16763                    +  " for userId:" + userId);
16764            mIntentFilterVerifier.startVerifications(userId);
16765        } else {
16766            if (DEBUG_DOMAIN_VERIFICATION) {
16767                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16768            }
16769        }
16770    }
16771
16772    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16773        final ComponentName cn  = filter.activity.getComponentName();
16774        final String packageName = cn.getPackageName();
16775
16776        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16777                packageName);
16778        if (ivi == null) {
16779            return true;
16780        }
16781        int status = ivi.getStatus();
16782        switch (status) {
16783            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16784            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16785                return true;
16786
16787            default:
16788                // Nothing to do
16789                return false;
16790        }
16791    }
16792
16793    private static boolean isMultiArch(ApplicationInfo info) {
16794        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16795    }
16796
16797    private static boolean isExternal(PackageParser.Package pkg) {
16798        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16799    }
16800
16801    private static boolean isExternal(PackageSetting ps) {
16802        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16803    }
16804
16805    private static boolean isSystemApp(PackageParser.Package pkg) {
16806        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16807    }
16808
16809    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16810        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16811    }
16812
16813    private static boolean isOemApp(PackageParser.Package pkg) {
16814        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16815    }
16816
16817    private static boolean isVendorApp(PackageParser.Package pkg) {
16818        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16819    }
16820
16821    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16822        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16823    }
16824
16825    private static boolean isSystemApp(PackageSetting ps) {
16826        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16827    }
16828
16829    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16830        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16831    }
16832
16833    private int packageFlagsToInstallFlags(PackageSetting ps) {
16834        int installFlags = 0;
16835        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16836            // This existing package was an external ASEC install when we have
16837            // the external flag without a UUID
16838            installFlags |= PackageManager.INSTALL_EXTERNAL;
16839        }
16840        if (ps.isForwardLocked()) {
16841            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16842        }
16843        return installFlags;
16844    }
16845
16846    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16847        if (isExternal(pkg)) {
16848            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16849                return mSettings.getExternalVersion();
16850            } else {
16851                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16852            }
16853        } else {
16854            return mSettings.getInternalVersion();
16855        }
16856    }
16857
16858    private void deleteTempPackageFiles() {
16859        final FilenameFilter filter = new FilenameFilter() {
16860            public boolean accept(File dir, String name) {
16861                return name.startsWith("vmdl") && name.endsWith(".tmp");
16862            }
16863        };
16864        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16865            file.delete();
16866        }
16867    }
16868
16869    @Override
16870    public void deletePackageAsUser(String packageName, int versionCode,
16871            IPackageDeleteObserver observer, int userId, int flags) {
16872        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
16873                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
16874    }
16875
16876    @Override
16877    public void deletePackageVersioned(VersionedPackage versionedPackage,
16878            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16879        final int callingUid = Binder.getCallingUid();
16880        mContext.enforceCallingOrSelfPermission(
16881                android.Manifest.permission.DELETE_PACKAGES, null);
16882        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
16883        Preconditions.checkNotNull(versionedPackage);
16884        Preconditions.checkNotNull(observer);
16885        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
16886                PackageManager.VERSION_CODE_HIGHEST,
16887                Integer.MAX_VALUE, "versionCode must be >= -1");
16888
16889        final String packageName = versionedPackage.getPackageName();
16890        final int versionCode = versionedPackage.getVersionCode();
16891        final String internalPackageName;
16892        synchronized (mPackages) {
16893            // Normalize package name to handle renamed packages and static libs
16894            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
16895                    versionedPackage.getVersionCode());
16896        }
16897
16898        final int uid = Binder.getCallingUid();
16899        if (!isOrphaned(internalPackageName)
16900                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
16901            try {
16902                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16903                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16904                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16905                observer.onUserActionRequired(intent);
16906            } catch (RemoteException re) {
16907            }
16908            return;
16909        }
16910        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16911        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16912        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16913            mContext.enforceCallingOrSelfPermission(
16914                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16915                    "deletePackage for user " + userId);
16916        }
16917
16918        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16919            try {
16920                observer.onPackageDeleted(packageName,
16921                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16922            } catch (RemoteException re) {
16923            }
16924            return;
16925        }
16926
16927        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
16928            try {
16929                observer.onPackageDeleted(packageName,
16930                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16931            } catch (RemoteException re) {
16932            }
16933            return;
16934        }
16935
16936        if (DEBUG_REMOVE) {
16937            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
16938                    + " deleteAllUsers: " + deleteAllUsers + " version="
16939                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
16940                    ? "VERSION_CODE_HIGHEST" : versionCode));
16941        }
16942        // Queue up an async operation since the package deletion may take a little while.
16943        mHandler.post(new Runnable() {
16944            public void run() {
16945                mHandler.removeCallbacks(this);
16946                int returnCode;
16947                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
16948                boolean doDeletePackage = true;
16949                if (ps != null) {
16950                    final boolean targetIsInstantApp =
16951                            ps.getInstantApp(UserHandle.getUserId(callingUid));
16952                    doDeletePackage = !targetIsInstantApp
16953                            || canViewInstantApps;
16954                }
16955                if (doDeletePackage) {
16956                    if (!deleteAllUsers) {
16957                        returnCode = deletePackageX(internalPackageName, versionCode,
16958                                userId, deleteFlags);
16959                    } else {
16960                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
16961                                internalPackageName, users);
16962                        // If nobody is blocking uninstall, proceed with delete for all users
16963                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16964                            returnCode = deletePackageX(internalPackageName, versionCode,
16965                                    userId, deleteFlags);
16966                        } else {
16967                            // Otherwise uninstall individually for users with blockUninstalls=false
16968                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16969                            for (int userId : users) {
16970                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16971                                    returnCode = deletePackageX(internalPackageName, versionCode,
16972                                            userId, userFlags);
16973                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16974                                        Slog.w(TAG, "Package delete failed for user " + userId
16975                                                + ", returnCode " + returnCode);
16976                                    }
16977                                }
16978                            }
16979                            // The app has only been marked uninstalled for certain users.
16980                            // We still need to report that delete was blocked
16981                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16982                        }
16983                    }
16984                } else {
16985                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16986                }
16987                try {
16988                    observer.onPackageDeleted(packageName, returnCode, null);
16989                } catch (RemoteException e) {
16990                    Log.i(TAG, "Observer no longer exists.");
16991                } //end catch
16992            } //end run
16993        });
16994    }
16995
16996    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
16997        if (pkg.staticSharedLibName != null) {
16998            return pkg.manifestPackageName;
16999        }
17000        return pkg.packageName;
17001    }
17002
17003    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17004        // Handle renamed packages
17005        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17006        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17007
17008        // Is this a static library?
17009        SparseArray<SharedLibraryEntry> versionedLib =
17010                mStaticLibsByDeclaringPackage.get(packageName);
17011        if (versionedLib == null || versionedLib.size() <= 0) {
17012            return packageName;
17013        }
17014
17015        // Figure out which lib versions the caller can see
17016        SparseIntArray versionsCallerCanSee = null;
17017        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17018        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17019                && callingAppId != Process.ROOT_UID) {
17020            versionsCallerCanSee = new SparseIntArray();
17021            String libName = versionedLib.valueAt(0).info.getName();
17022            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17023            if (uidPackages != null) {
17024                for (String uidPackage : uidPackages) {
17025                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17026                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17027                    if (libIdx >= 0) {
17028                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17029                        versionsCallerCanSee.append(libVersion, libVersion);
17030                    }
17031                }
17032            }
17033        }
17034
17035        // Caller can see nothing - done
17036        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17037            return packageName;
17038        }
17039
17040        // Find the version the caller can see and the app version code
17041        SharedLibraryEntry highestVersion = null;
17042        final int versionCount = versionedLib.size();
17043        for (int i = 0; i < versionCount; i++) {
17044            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17045            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17046                    libEntry.info.getVersion()) < 0) {
17047                continue;
17048            }
17049            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
17050            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17051                if (libVersionCode == versionCode) {
17052                    return libEntry.apk;
17053                }
17054            } else if (highestVersion == null) {
17055                highestVersion = libEntry;
17056            } else if (libVersionCode  > highestVersion.info
17057                    .getDeclaringPackage().getVersionCode()) {
17058                highestVersion = libEntry;
17059            }
17060        }
17061
17062        if (highestVersion != null) {
17063            return highestVersion.apk;
17064        }
17065
17066        return packageName;
17067    }
17068
17069    boolean isCallerVerifier(int callingUid) {
17070        final int callingUserId = UserHandle.getUserId(callingUid);
17071        return mRequiredVerifierPackage != null &&
17072                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17073    }
17074
17075    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17076        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17077              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17078            return true;
17079        }
17080        final int callingUserId = UserHandle.getUserId(callingUid);
17081        // If the caller installed the pkgName, then allow it to silently uninstall.
17082        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17083            return true;
17084        }
17085
17086        // Allow package verifier to silently uninstall.
17087        if (mRequiredVerifierPackage != null &&
17088                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17089            return true;
17090        }
17091
17092        // Allow package uninstaller to silently uninstall.
17093        if (mRequiredUninstallerPackage != null &&
17094                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17095            return true;
17096        }
17097
17098        // Allow storage manager to silently uninstall.
17099        if (mStorageManagerPackage != null &&
17100                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17101            return true;
17102        }
17103
17104        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17105        // uninstall for device owner provisioning.
17106        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17107                == PERMISSION_GRANTED) {
17108            return true;
17109        }
17110
17111        return false;
17112    }
17113
17114    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17115        int[] result = EMPTY_INT_ARRAY;
17116        for (int userId : userIds) {
17117            if (getBlockUninstallForUser(packageName, userId)) {
17118                result = ArrayUtils.appendInt(result, userId);
17119            }
17120        }
17121        return result;
17122    }
17123
17124    @Override
17125    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17126        final int callingUid = Binder.getCallingUid();
17127        if (getInstantAppPackageName(callingUid) != null
17128                && !isCallerSameApp(packageName, callingUid)) {
17129            return false;
17130        }
17131        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17132    }
17133
17134    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17135        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17136                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17137        try {
17138            if (dpm != null) {
17139                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17140                        /* callingUserOnly =*/ false);
17141                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17142                        : deviceOwnerComponentName.getPackageName();
17143                // Does the package contains the device owner?
17144                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17145                // this check is probably not needed, since DO should be registered as a device
17146                // admin on some user too. (Original bug for this: b/17657954)
17147                if (packageName.equals(deviceOwnerPackageName)) {
17148                    return true;
17149                }
17150                // Does it contain a device admin for any user?
17151                int[] users;
17152                if (userId == UserHandle.USER_ALL) {
17153                    users = sUserManager.getUserIds();
17154                } else {
17155                    users = new int[]{userId};
17156                }
17157                for (int i = 0; i < users.length; ++i) {
17158                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17159                        return true;
17160                    }
17161                }
17162            }
17163        } catch (RemoteException e) {
17164        }
17165        return false;
17166    }
17167
17168    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17169        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17170    }
17171
17172    /**
17173     *  This method is an internal method that could be get invoked either
17174     *  to delete an installed package or to clean up a failed installation.
17175     *  After deleting an installed package, a broadcast is sent to notify any
17176     *  listeners that the package has been removed. For cleaning up a failed
17177     *  installation, the broadcast is not necessary since the package's
17178     *  installation wouldn't have sent the initial broadcast either
17179     *  The key steps in deleting a package are
17180     *  deleting the package information in internal structures like mPackages,
17181     *  deleting the packages base directories through installd
17182     *  updating mSettings to reflect current status
17183     *  persisting settings for later use
17184     *  sending a broadcast if necessary
17185     */
17186    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17187        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17188        final boolean res;
17189
17190        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17191                ? UserHandle.USER_ALL : userId;
17192
17193        if (isPackageDeviceAdmin(packageName, removeUser)) {
17194            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17195            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17196        }
17197
17198        PackageSetting uninstalledPs = null;
17199        PackageParser.Package pkg = null;
17200
17201        // for the uninstall-updates case and restricted profiles, remember the per-
17202        // user handle installed state
17203        int[] allUsers;
17204        synchronized (mPackages) {
17205            uninstalledPs = mSettings.mPackages.get(packageName);
17206            if (uninstalledPs == null) {
17207                Slog.w(TAG, "Not removing non-existent package " + packageName);
17208                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17209            }
17210
17211            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17212                    && uninstalledPs.versionCode != versionCode) {
17213                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17214                        + uninstalledPs.versionCode + " != " + versionCode);
17215                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17216            }
17217
17218            // Static shared libs can be declared by any package, so let us not
17219            // allow removing a package if it provides a lib others depend on.
17220            pkg = mPackages.get(packageName);
17221
17222            allUsers = sUserManager.getUserIds();
17223
17224            if (pkg != null && pkg.staticSharedLibName != null) {
17225                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17226                        pkg.staticSharedLibVersion);
17227                if (libEntry != null) {
17228                    for (int currUserId : allUsers) {
17229                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17230                            continue;
17231                        }
17232                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17233                                libEntry.info, 0, currUserId);
17234                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17235                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17236                                    + " hosting lib " + libEntry.info.getName() + " version "
17237                                    + libEntry.info.getVersion() + " used by " + libClientPackages
17238                                    + " for user " + currUserId);
17239                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17240                        }
17241                    }
17242                }
17243            }
17244
17245            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17246        }
17247
17248        final int freezeUser;
17249        if (isUpdatedSystemApp(uninstalledPs)
17250                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17251            // We're downgrading a system app, which will apply to all users, so
17252            // freeze them all during the downgrade
17253            freezeUser = UserHandle.USER_ALL;
17254        } else {
17255            freezeUser = removeUser;
17256        }
17257
17258        synchronized (mInstallLock) {
17259            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17260            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17261                    deleteFlags, "deletePackageX")) {
17262                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17263                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17264            }
17265            synchronized (mPackages) {
17266                if (res) {
17267                    if (pkg != null) {
17268                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17269                    }
17270                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17271                    updateInstantAppInstallerLocked(packageName);
17272                }
17273            }
17274        }
17275
17276        if (res) {
17277            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17278            info.sendPackageRemovedBroadcasts(killApp);
17279            info.sendSystemPackageUpdatedBroadcasts();
17280            info.sendSystemPackageAppearedBroadcasts();
17281        }
17282        // Force a gc here.
17283        Runtime.getRuntime().gc();
17284        // Delete the resources here after sending the broadcast to let
17285        // other processes clean up before deleting resources.
17286        if (info.args != null) {
17287            synchronized (mInstallLock) {
17288                info.args.doPostDeleteLI(true);
17289            }
17290        }
17291
17292        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17293    }
17294
17295    static class PackageRemovedInfo {
17296        final PackageSender packageSender;
17297        String removedPackage;
17298        String installerPackageName;
17299        int uid = -1;
17300        int removedAppId = -1;
17301        int[] origUsers;
17302        int[] removedUsers = null;
17303        int[] broadcastUsers = null;
17304        SparseArray<Integer> installReasons;
17305        boolean isRemovedPackageSystemUpdate = false;
17306        boolean isUpdate;
17307        boolean dataRemoved;
17308        boolean removedForAllUsers;
17309        boolean isStaticSharedLib;
17310        // Clean up resources deleted packages.
17311        InstallArgs args = null;
17312        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17313        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17314
17315        PackageRemovedInfo(PackageSender packageSender) {
17316            this.packageSender = packageSender;
17317        }
17318
17319        void sendPackageRemovedBroadcasts(boolean killApp) {
17320            sendPackageRemovedBroadcastInternal(killApp);
17321            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17322            for (int i = 0; i < childCount; i++) {
17323                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17324                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17325            }
17326        }
17327
17328        void sendSystemPackageUpdatedBroadcasts() {
17329            if (isRemovedPackageSystemUpdate) {
17330                sendSystemPackageUpdatedBroadcastsInternal();
17331                final int childCount = (removedChildPackages != null)
17332                        ? removedChildPackages.size() : 0;
17333                for (int i = 0; i < childCount; i++) {
17334                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17335                    if (childInfo.isRemovedPackageSystemUpdate) {
17336                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17337                    }
17338                }
17339            }
17340        }
17341
17342        void sendSystemPackageAppearedBroadcasts() {
17343            final int packageCount = (appearedChildPackages != null)
17344                    ? appearedChildPackages.size() : 0;
17345            for (int i = 0; i < packageCount; i++) {
17346                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17347                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17348                    true /*sendBootCompleted*/, false /*startReceiver*/,
17349                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17350            }
17351        }
17352
17353        private void sendSystemPackageUpdatedBroadcastsInternal() {
17354            Bundle extras = new Bundle(2);
17355            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17356            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17357            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17358                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17359            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17360                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17361            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17362                null, null, 0, removedPackage, null, null);
17363            if (installerPackageName != null) {
17364                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17365                        removedPackage, extras, 0 /*flags*/,
17366                        installerPackageName, null, null);
17367                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17368                        removedPackage, extras, 0 /*flags*/,
17369                        installerPackageName, null, null);
17370            }
17371        }
17372
17373        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17374            // Don't send static shared library removal broadcasts as these
17375            // libs are visible only the the apps that depend on them an one
17376            // cannot remove the library if it has a dependency.
17377            if (isStaticSharedLib) {
17378                return;
17379            }
17380            Bundle extras = new Bundle(2);
17381            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17382            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17383            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17384            if (isUpdate || isRemovedPackageSystemUpdate) {
17385                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17386            }
17387            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17388            if (removedPackage != null) {
17389                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17390                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
17391                if (installerPackageName != null) {
17392                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17393                            removedPackage, extras, 0 /*flags*/,
17394                            installerPackageName, null, broadcastUsers);
17395                }
17396                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17397                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17398                        removedPackage, extras,
17399                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17400                        null, null, broadcastUsers);
17401                }
17402            }
17403            if (removedAppId >= 0) {
17404                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17405                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17406                    null, null, broadcastUsers);
17407            }
17408        }
17409
17410        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17411            removedUsers = userIds;
17412            if (removedUsers == null) {
17413                broadcastUsers = null;
17414                return;
17415            }
17416
17417            broadcastUsers = EMPTY_INT_ARRAY;
17418            for (int i = userIds.length - 1; i >= 0; --i) {
17419                final int userId = userIds[i];
17420                if (deletedPackageSetting.getInstantApp(userId)) {
17421                    continue;
17422                }
17423                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17424            }
17425        }
17426    }
17427
17428    /*
17429     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17430     * flag is not set, the data directory is removed as well.
17431     * make sure this flag is set for partially installed apps. If not its meaningless to
17432     * delete a partially installed application.
17433     */
17434    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17435            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17436        String packageName = ps.name;
17437        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17438        // Retrieve object to delete permissions for shared user later on
17439        final PackageParser.Package deletedPkg;
17440        final PackageSetting deletedPs;
17441        // reader
17442        synchronized (mPackages) {
17443            deletedPkg = mPackages.get(packageName);
17444            deletedPs = mSettings.mPackages.get(packageName);
17445            if (outInfo != null) {
17446                outInfo.removedPackage = packageName;
17447                outInfo.installerPackageName = ps.installerPackageName;
17448                outInfo.isStaticSharedLib = deletedPkg != null
17449                        && deletedPkg.staticSharedLibName != null;
17450                outInfo.populateUsers(deletedPs == null ? null
17451                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17452            }
17453        }
17454
17455        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
17456
17457        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17458            final PackageParser.Package resolvedPkg;
17459            if (deletedPkg != null) {
17460                resolvedPkg = deletedPkg;
17461            } else {
17462                // We don't have a parsed package when it lives on an ejected
17463                // adopted storage device, so fake something together
17464                resolvedPkg = new PackageParser.Package(ps.name);
17465                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17466            }
17467            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17468                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17469            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17470            if (outInfo != null) {
17471                outInfo.dataRemoved = true;
17472            }
17473            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17474        }
17475
17476        int removedAppId = -1;
17477
17478        // writer
17479        synchronized (mPackages) {
17480            boolean installedStateChanged = false;
17481            if (deletedPs != null) {
17482                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17483                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17484                    clearDefaultBrowserIfNeeded(packageName);
17485                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17486                    removedAppId = mSettings.removePackageLPw(packageName);
17487                    if (outInfo != null) {
17488                        outInfo.removedAppId = removedAppId;
17489                    }
17490                    mPermissionManager.updatePermissions(
17491                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17492                    if (deletedPs.sharedUser != null) {
17493                        // Remove permissions associated with package. Since runtime
17494                        // permissions are per user we have to kill the removed package
17495                        // or packages running under the shared user of the removed
17496                        // package if revoking the permissions requested only by the removed
17497                        // package is successful and this causes a change in gids.
17498                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17499                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17500                                    userId);
17501                            if (userIdToKill == UserHandle.USER_ALL
17502                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17503                                // If gids changed for this user, kill all affected packages.
17504                                mHandler.post(new Runnable() {
17505                                    @Override
17506                                    public void run() {
17507                                        // This has to happen with no lock held.
17508                                        killApplication(deletedPs.name, deletedPs.appId,
17509                                                KILL_APP_REASON_GIDS_CHANGED);
17510                                    }
17511                                });
17512                                break;
17513                            }
17514                        }
17515                    }
17516                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17517                }
17518                // make sure to preserve per-user disabled state if this removal was just
17519                // a downgrade of a system app to the factory package
17520                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17521                    if (DEBUG_REMOVE) {
17522                        Slog.d(TAG, "Propagating install state across downgrade");
17523                    }
17524                    for (int userId : allUserHandles) {
17525                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17526                        if (DEBUG_REMOVE) {
17527                            Slog.d(TAG, "    user " + userId + " => " + installed);
17528                        }
17529                        if (installed != ps.getInstalled(userId)) {
17530                            installedStateChanged = true;
17531                        }
17532                        ps.setInstalled(installed, userId);
17533                    }
17534                }
17535            }
17536            // can downgrade to reader
17537            if (writeSettings) {
17538                // Save settings now
17539                mSettings.writeLPr();
17540            }
17541            if (installedStateChanged) {
17542                mSettings.writeKernelMappingLPr(ps);
17543            }
17544        }
17545        if (removedAppId != -1) {
17546            // A user ID was deleted here. Go through all users and remove it
17547            // from KeyStore.
17548            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17549        }
17550    }
17551
17552    static boolean locationIsPrivileged(String path) {
17553        try {
17554            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
17555            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
17556            return path.startsWith(privilegedAppDir.getCanonicalPath())
17557                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath());
17558        } catch (IOException e) {
17559            Slog.e(TAG, "Unable to access code path " + path);
17560        }
17561        return false;
17562    }
17563
17564    static boolean locationIsOem(String path) {
17565        try {
17566            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
17567        } catch (IOException e) {
17568            Slog.e(TAG, "Unable to access code path " + path);
17569        }
17570        return false;
17571    }
17572
17573    static boolean locationIsVendor(String path) {
17574        try {
17575            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath());
17576        } catch (IOException e) {
17577            Slog.e(TAG, "Unable to access code path " + path);
17578        }
17579        return false;
17580    }
17581
17582    /*
17583     * Tries to delete system package.
17584     */
17585    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17586            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17587            boolean writeSettings) {
17588        if (deletedPs.parentPackageName != null) {
17589            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17590            return false;
17591        }
17592
17593        final boolean applyUserRestrictions
17594                = (allUserHandles != null) && (outInfo.origUsers != null);
17595        final PackageSetting disabledPs;
17596        // Confirm if the system package has been updated
17597        // An updated system app can be deleted. This will also have to restore
17598        // the system pkg from system partition
17599        // reader
17600        synchronized (mPackages) {
17601            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17602        }
17603
17604        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17605                + " disabledPs=" + disabledPs);
17606
17607        if (disabledPs == null) {
17608            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17609            return false;
17610        } else if (DEBUG_REMOVE) {
17611            Slog.d(TAG, "Deleting system pkg from data partition");
17612        }
17613
17614        if (DEBUG_REMOVE) {
17615            if (applyUserRestrictions) {
17616                Slog.d(TAG, "Remembering install states:");
17617                for (int userId : allUserHandles) {
17618                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17619                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17620                }
17621            }
17622        }
17623
17624        // Delete the updated package
17625        outInfo.isRemovedPackageSystemUpdate = true;
17626        if (outInfo.removedChildPackages != null) {
17627            final int childCount = (deletedPs.childPackageNames != null)
17628                    ? deletedPs.childPackageNames.size() : 0;
17629            for (int i = 0; i < childCount; i++) {
17630                String childPackageName = deletedPs.childPackageNames.get(i);
17631                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17632                        .contains(childPackageName)) {
17633                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17634                            childPackageName);
17635                    if (childInfo != null) {
17636                        childInfo.isRemovedPackageSystemUpdate = true;
17637                    }
17638                }
17639            }
17640        }
17641
17642        if (disabledPs.versionCode < deletedPs.versionCode) {
17643            // Delete data for downgrades
17644            flags &= ~PackageManager.DELETE_KEEP_DATA;
17645        } else {
17646            // Preserve data by setting flag
17647            flags |= PackageManager.DELETE_KEEP_DATA;
17648        }
17649
17650        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17651                outInfo, writeSettings, disabledPs.pkg);
17652        if (!ret) {
17653            return false;
17654        }
17655
17656        // writer
17657        synchronized (mPackages) {
17658            // NOTE: The system package always needs to be enabled; even if it's for
17659            // a compressed stub. If we don't, installing the system package fails
17660            // during scan [scanning checks the disabled packages]. We will reverse
17661            // this later, after we've "installed" the stub.
17662            // Reinstate the old system package
17663            enableSystemPackageLPw(disabledPs.pkg);
17664            // Remove any native libraries from the upgraded package.
17665            removeNativeBinariesLI(deletedPs);
17666        }
17667
17668        // Install the system package
17669        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17670        try {
17671            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
17672                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17673        } catch (PackageManagerException e) {
17674            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17675                    + e.getMessage());
17676            return false;
17677        } finally {
17678            if (disabledPs.pkg.isStub) {
17679                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
17680            }
17681        }
17682        return true;
17683    }
17684
17685    /**
17686     * Installs a package that's already on the system partition.
17687     */
17688    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
17689            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
17690            @Nullable PermissionsState origPermissionState, boolean writeSettings)
17691                    throws PackageManagerException {
17692        @ParseFlags int parseFlags =
17693                mDefParseFlags
17694                | PackageParser.PARSE_MUST_BE_APK
17695                | PackageParser.PARSE_IS_SYSTEM_DIR;
17696        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
17697        if (isPrivileged || locationIsPrivileged(codePathString)) {
17698            scanFlags |= SCAN_AS_PRIVILEGED;
17699        }
17700        if (locationIsOem(codePathString)) {
17701            scanFlags |= SCAN_AS_OEM;
17702        }
17703        if (locationIsVendor(codePathString)) {
17704            scanFlags |= SCAN_AS_VENDOR;
17705        }
17706
17707        final File codePath = new File(codePathString);
17708        final PackageParser.Package pkg =
17709                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
17710
17711        try {
17712            // update shared libraries for the newly re-installed system package
17713            updateSharedLibrariesLPr(pkg, null);
17714        } catch (PackageManagerException e) {
17715            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17716        }
17717
17718        prepareAppDataAfterInstallLIF(pkg);
17719
17720        // writer
17721        synchronized (mPackages) {
17722            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
17723
17724            // Propagate the permissions state as we do not want to drop on the floor
17725            // runtime permissions. The update permissions method below will take
17726            // care of removing obsolete permissions and grant install permissions.
17727            if (origPermissionState != null) {
17728                ps.getPermissionsState().copyFrom(origPermissionState);
17729            }
17730            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
17731                    mPermissionCallback);
17732
17733            final boolean applyUserRestrictions
17734                    = (allUserHandles != null) && (origUserHandles != null);
17735            if (applyUserRestrictions) {
17736                boolean installedStateChanged = false;
17737                if (DEBUG_REMOVE) {
17738                    Slog.d(TAG, "Propagating install state across reinstall");
17739                }
17740                for (int userId : allUserHandles) {
17741                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
17742                    if (DEBUG_REMOVE) {
17743                        Slog.d(TAG, "    user " + userId + " => " + installed);
17744                    }
17745                    if (installed != ps.getInstalled(userId)) {
17746                        installedStateChanged = true;
17747                    }
17748                    ps.setInstalled(installed, userId);
17749
17750                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17751                }
17752                // Regardless of writeSettings we need to ensure that this restriction
17753                // state propagation is persisted
17754                mSettings.writeAllUsersPackageRestrictionsLPr();
17755                if (installedStateChanged) {
17756                    mSettings.writeKernelMappingLPr(ps);
17757                }
17758            }
17759            // can downgrade to reader here
17760            if (writeSettings) {
17761                mSettings.writeLPr();
17762            }
17763        }
17764        return pkg;
17765    }
17766
17767    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17768            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17769            PackageRemovedInfo outInfo, boolean writeSettings,
17770            PackageParser.Package replacingPackage) {
17771        synchronized (mPackages) {
17772            if (outInfo != null) {
17773                outInfo.uid = ps.appId;
17774            }
17775
17776            if (outInfo != null && outInfo.removedChildPackages != null) {
17777                final int childCount = (ps.childPackageNames != null)
17778                        ? ps.childPackageNames.size() : 0;
17779                for (int i = 0; i < childCount; i++) {
17780                    String childPackageName = ps.childPackageNames.get(i);
17781                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17782                    if (childPs == null) {
17783                        return false;
17784                    }
17785                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17786                            childPackageName);
17787                    if (childInfo != null) {
17788                        childInfo.uid = childPs.appId;
17789                    }
17790                }
17791            }
17792        }
17793
17794        // Delete package data from internal structures and also remove data if flag is set
17795        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17796
17797        // Delete the child packages data
17798        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17799        for (int i = 0; i < childCount; i++) {
17800            PackageSetting childPs;
17801            synchronized (mPackages) {
17802                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17803            }
17804            if (childPs != null) {
17805                PackageRemovedInfo childOutInfo = (outInfo != null
17806                        && outInfo.removedChildPackages != null)
17807                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17808                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17809                        && (replacingPackage != null
17810                        && !replacingPackage.hasChildPackage(childPs.name))
17811                        ? flags & ~DELETE_KEEP_DATA : flags;
17812                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17813                        deleteFlags, writeSettings);
17814            }
17815        }
17816
17817        // Delete application code and resources only for parent packages
17818        if (ps.parentPackageName == null) {
17819            if (deleteCodeAndResources && (outInfo != null)) {
17820                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17821                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17822                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17823            }
17824        }
17825
17826        return true;
17827    }
17828
17829    @Override
17830    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17831            int userId) {
17832        mContext.enforceCallingOrSelfPermission(
17833                android.Manifest.permission.DELETE_PACKAGES, null);
17834        synchronized (mPackages) {
17835            // Cannot block uninstall of static shared libs as they are
17836            // considered a part of the using app (emulating static linking).
17837            // Also static libs are installed always on internal storage.
17838            PackageParser.Package pkg = mPackages.get(packageName);
17839            if (pkg != null && pkg.staticSharedLibName != null) {
17840                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17841                        + " providing static shared library: " + pkg.staticSharedLibName);
17842                return false;
17843            }
17844            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
17845            mSettings.writePackageRestrictionsLPr(userId);
17846        }
17847        return true;
17848    }
17849
17850    @Override
17851    public boolean getBlockUninstallForUser(String packageName, int userId) {
17852        synchronized (mPackages) {
17853            final PackageSetting ps = mSettings.mPackages.get(packageName);
17854            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
17855                return false;
17856            }
17857            return mSettings.getBlockUninstallLPr(userId, packageName);
17858        }
17859    }
17860
17861    @Override
17862    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17863        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
17864        synchronized (mPackages) {
17865            PackageSetting ps = mSettings.mPackages.get(packageName);
17866            if (ps == null) {
17867                Log.w(TAG, "Package doesn't exist: " + packageName);
17868                return false;
17869            }
17870            if (systemUserApp) {
17871                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17872            } else {
17873                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17874            }
17875            mSettings.writeLPr();
17876        }
17877        return true;
17878    }
17879
17880    /*
17881     * This method handles package deletion in general
17882     */
17883    private boolean deletePackageLIF(String packageName, UserHandle user,
17884            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17885            PackageRemovedInfo outInfo, boolean writeSettings,
17886            PackageParser.Package replacingPackage) {
17887        if (packageName == null) {
17888            Slog.w(TAG, "Attempt to delete null packageName.");
17889            return false;
17890        }
17891
17892        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17893
17894        PackageSetting ps;
17895        synchronized (mPackages) {
17896            ps = mSettings.mPackages.get(packageName);
17897            if (ps == null) {
17898                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17899                return false;
17900            }
17901
17902            if (ps.parentPackageName != null && (!isSystemApp(ps)
17903                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17904                if (DEBUG_REMOVE) {
17905                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17906                            + ((user == null) ? UserHandle.USER_ALL : user));
17907                }
17908                final int removedUserId = (user != null) ? user.getIdentifier()
17909                        : UserHandle.USER_ALL;
17910                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17911                    return false;
17912                }
17913                markPackageUninstalledForUserLPw(ps, user);
17914                scheduleWritePackageRestrictionsLocked(user);
17915                return true;
17916            }
17917        }
17918
17919        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17920                && user.getIdentifier() != UserHandle.USER_ALL)) {
17921            // The caller is asking that the package only be deleted for a single
17922            // user.  To do this, we just mark its uninstalled state and delete
17923            // its data. If this is a system app, we only allow this to happen if
17924            // they have set the special DELETE_SYSTEM_APP which requests different
17925            // semantics than normal for uninstalling system apps.
17926            markPackageUninstalledForUserLPw(ps, user);
17927
17928            if (!isSystemApp(ps)) {
17929                // Do not uninstall the APK if an app should be cached
17930                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17931                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17932                    // Other user still have this package installed, so all
17933                    // we need to do is clear this user's data and save that
17934                    // it is uninstalled.
17935                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17936                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17937                        return false;
17938                    }
17939                    scheduleWritePackageRestrictionsLocked(user);
17940                    return true;
17941                } else {
17942                    // We need to set it back to 'installed' so the uninstall
17943                    // broadcasts will be sent correctly.
17944                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17945                    ps.setInstalled(true, user.getIdentifier());
17946                    mSettings.writeKernelMappingLPr(ps);
17947                }
17948            } else {
17949                // This is a system app, so we assume that the
17950                // other users still have this package installed, so all
17951                // we need to do is clear this user's data and save that
17952                // it is uninstalled.
17953                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17954                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17955                    return false;
17956                }
17957                scheduleWritePackageRestrictionsLocked(user);
17958                return true;
17959            }
17960        }
17961
17962        // If we are deleting a composite package for all users, keep track
17963        // of result for each child.
17964        if (ps.childPackageNames != null && outInfo != null) {
17965            synchronized (mPackages) {
17966                final int childCount = ps.childPackageNames.size();
17967                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17968                for (int i = 0; i < childCount; i++) {
17969                    String childPackageName = ps.childPackageNames.get(i);
17970                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
17971                    childInfo.removedPackage = childPackageName;
17972                    childInfo.installerPackageName = ps.installerPackageName;
17973                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17974                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17975                    if (childPs != null) {
17976                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17977                    }
17978                }
17979            }
17980        }
17981
17982        boolean ret = false;
17983        if (isSystemApp(ps)) {
17984            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17985            // When an updated system application is deleted we delete the existing resources
17986            // as well and fall back to existing code in system partition
17987            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17988        } else {
17989            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17990            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17991                    outInfo, writeSettings, replacingPackage);
17992        }
17993
17994        // Take a note whether we deleted the package for all users
17995        if (outInfo != null) {
17996            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17997            if (outInfo.removedChildPackages != null) {
17998                synchronized (mPackages) {
17999                    final int childCount = outInfo.removedChildPackages.size();
18000                    for (int i = 0; i < childCount; i++) {
18001                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18002                        if (childInfo != null) {
18003                            childInfo.removedForAllUsers = mPackages.get(
18004                                    childInfo.removedPackage) == null;
18005                        }
18006                    }
18007                }
18008            }
18009            // If we uninstalled an update to a system app there may be some
18010            // child packages that appeared as they are declared in the system
18011            // app but were not declared in the update.
18012            if (isSystemApp(ps)) {
18013                synchronized (mPackages) {
18014                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18015                    final int childCount = (updatedPs.childPackageNames != null)
18016                            ? updatedPs.childPackageNames.size() : 0;
18017                    for (int i = 0; i < childCount; i++) {
18018                        String childPackageName = updatedPs.childPackageNames.get(i);
18019                        if (outInfo.removedChildPackages == null
18020                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18021                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18022                            if (childPs == null) {
18023                                continue;
18024                            }
18025                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18026                            installRes.name = childPackageName;
18027                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18028                            installRes.pkg = mPackages.get(childPackageName);
18029                            installRes.uid = childPs.pkg.applicationInfo.uid;
18030                            if (outInfo.appearedChildPackages == null) {
18031                                outInfo.appearedChildPackages = new ArrayMap<>();
18032                            }
18033                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18034                        }
18035                    }
18036                }
18037            }
18038        }
18039
18040        return ret;
18041    }
18042
18043    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18044        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18045                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18046        for (int nextUserId : userIds) {
18047            if (DEBUG_REMOVE) {
18048                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18049            }
18050            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18051                    false /*installed*/,
18052                    true /*stopped*/,
18053                    true /*notLaunched*/,
18054                    false /*hidden*/,
18055                    false /*suspended*/,
18056                    false /*instantApp*/,
18057                    false /*virtualPreload*/,
18058                    null /*lastDisableAppCaller*/,
18059                    null /*enabledComponents*/,
18060                    null /*disabledComponents*/,
18061                    ps.readUserState(nextUserId).domainVerificationStatus,
18062                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18063        }
18064        mSettings.writeKernelMappingLPr(ps);
18065    }
18066
18067    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18068            PackageRemovedInfo outInfo) {
18069        final PackageParser.Package pkg;
18070        synchronized (mPackages) {
18071            pkg = mPackages.get(ps.name);
18072        }
18073
18074        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18075                : new int[] {userId};
18076        for (int nextUserId : userIds) {
18077            if (DEBUG_REMOVE) {
18078                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18079                        + nextUserId);
18080            }
18081
18082            destroyAppDataLIF(pkg, userId,
18083                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18084            destroyAppProfilesLIF(pkg, userId);
18085            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18086            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18087            schedulePackageCleaning(ps.name, nextUserId, false);
18088            synchronized (mPackages) {
18089                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18090                    scheduleWritePackageRestrictionsLocked(nextUserId);
18091                }
18092                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18093            }
18094        }
18095
18096        if (outInfo != null) {
18097            outInfo.removedPackage = ps.name;
18098            outInfo.installerPackageName = ps.installerPackageName;
18099            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18100            outInfo.removedAppId = ps.appId;
18101            outInfo.removedUsers = userIds;
18102            outInfo.broadcastUsers = userIds;
18103        }
18104
18105        return true;
18106    }
18107
18108    private final class ClearStorageConnection implements ServiceConnection {
18109        IMediaContainerService mContainerService;
18110
18111        @Override
18112        public void onServiceConnected(ComponentName name, IBinder service) {
18113            synchronized (this) {
18114                mContainerService = IMediaContainerService.Stub
18115                        .asInterface(Binder.allowBlocking(service));
18116                notifyAll();
18117            }
18118        }
18119
18120        @Override
18121        public void onServiceDisconnected(ComponentName name) {
18122        }
18123    }
18124
18125    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18126        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18127
18128        final boolean mounted;
18129        if (Environment.isExternalStorageEmulated()) {
18130            mounted = true;
18131        } else {
18132            final String status = Environment.getExternalStorageState();
18133
18134            mounted = status.equals(Environment.MEDIA_MOUNTED)
18135                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18136        }
18137
18138        if (!mounted) {
18139            return;
18140        }
18141
18142        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18143        int[] users;
18144        if (userId == UserHandle.USER_ALL) {
18145            users = sUserManager.getUserIds();
18146        } else {
18147            users = new int[] { userId };
18148        }
18149        final ClearStorageConnection conn = new ClearStorageConnection();
18150        if (mContext.bindServiceAsUser(
18151                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18152            try {
18153                for (int curUser : users) {
18154                    long timeout = SystemClock.uptimeMillis() + 5000;
18155                    synchronized (conn) {
18156                        long now;
18157                        while (conn.mContainerService == null &&
18158                                (now = SystemClock.uptimeMillis()) < timeout) {
18159                            try {
18160                                conn.wait(timeout - now);
18161                            } catch (InterruptedException e) {
18162                            }
18163                        }
18164                    }
18165                    if (conn.mContainerService == null) {
18166                        return;
18167                    }
18168
18169                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18170                    clearDirectory(conn.mContainerService,
18171                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18172                    if (allData) {
18173                        clearDirectory(conn.mContainerService,
18174                                userEnv.buildExternalStorageAppDataDirs(packageName));
18175                        clearDirectory(conn.mContainerService,
18176                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18177                    }
18178                }
18179            } finally {
18180                mContext.unbindService(conn);
18181            }
18182        }
18183    }
18184
18185    @Override
18186    public void clearApplicationProfileData(String packageName) {
18187        enforceSystemOrRoot("Only the system can clear all profile data");
18188
18189        final PackageParser.Package pkg;
18190        synchronized (mPackages) {
18191            pkg = mPackages.get(packageName);
18192        }
18193
18194        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18195            synchronized (mInstallLock) {
18196                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18197            }
18198        }
18199    }
18200
18201    @Override
18202    public void clearApplicationUserData(final String packageName,
18203            final IPackageDataObserver observer, final int userId) {
18204        mContext.enforceCallingOrSelfPermission(
18205                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18206
18207        final int callingUid = Binder.getCallingUid();
18208        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18209                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18210
18211        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18212        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18213        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18214            throw new SecurityException("Cannot clear data for a protected package: "
18215                    + packageName);
18216        }
18217        // Queue up an async operation since the package deletion may take a little while.
18218        mHandler.post(new Runnable() {
18219            public void run() {
18220                mHandler.removeCallbacks(this);
18221                final boolean succeeded;
18222                if (!filterApp) {
18223                    try (PackageFreezer freezer = freezePackage(packageName,
18224                            "clearApplicationUserData")) {
18225                        synchronized (mInstallLock) {
18226                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18227                        }
18228                        clearExternalStorageDataSync(packageName, userId, true);
18229                        synchronized (mPackages) {
18230                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18231                                    packageName, userId);
18232                        }
18233                    }
18234                    if (succeeded) {
18235                        // invoke DeviceStorageMonitor's update method to clear any notifications
18236                        DeviceStorageMonitorInternal dsm = LocalServices
18237                                .getService(DeviceStorageMonitorInternal.class);
18238                        if (dsm != null) {
18239                            dsm.checkMemory();
18240                        }
18241                    }
18242                } else {
18243                    succeeded = false;
18244                }
18245                if (observer != null) {
18246                    try {
18247                        observer.onRemoveCompleted(packageName, succeeded);
18248                    } catch (RemoteException e) {
18249                        Log.i(TAG, "Observer no longer exists.");
18250                    }
18251                } //end if observer
18252            } //end run
18253        });
18254    }
18255
18256    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18257        if (packageName == null) {
18258            Slog.w(TAG, "Attempt to delete null packageName.");
18259            return false;
18260        }
18261
18262        // Try finding details about the requested package
18263        PackageParser.Package pkg;
18264        synchronized (mPackages) {
18265            pkg = mPackages.get(packageName);
18266            if (pkg == null) {
18267                final PackageSetting ps = mSettings.mPackages.get(packageName);
18268                if (ps != null) {
18269                    pkg = ps.pkg;
18270                }
18271            }
18272
18273            if (pkg == null) {
18274                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18275                return false;
18276            }
18277
18278            PackageSetting ps = (PackageSetting) pkg.mExtras;
18279            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18280        }
18281
18282        clearAppDataLIF(pkg, userId,
18283                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18284
18285        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18286        removeKeystoreDataIfNeeded(userId, appId);
18287
18288        UserManagerInternal umInternal = getUserManagerInternal();
18289        final int flags;
18290        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18291            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18292        } else if (umInternal.isUserRunning(userId)) {
18293            flags = StorageManager.FLAG_STORAGE_DE;
18294        } else {
18295            flags = 0;
18296        }
18297        prepareAppDataContentsLIF(pkg, userId, flags);
18298
18299        return true;
18300    }
18301
18302    /**
18303     * Reverts user permission state changes (permissions and flags) in
18304     * all packages for a given user.
18305     *
18306     * @param userId The device user for which to do a reset.
18307     */
18308    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18309        final int packageCount = mPackages.size();
18310        for (int i = 0; i < packageCount; i++) {
18311            PackageParser.Package pkg = mPackages.valueAt(i);
18312            PackageSetting ps = (PackageSetting) pkg.mExtras;
18313            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18314        }
18315    }
18316
18317    private void resetNetworkPolicies(int userId) {
18318        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18319    }
18320
18321    /**
18322     * Reverts user permission state changes (permissions and flags).
18323     *
18324     * @param ps The package for which to reset.
18325     * @param userId The device user for which to do a reset.
18326     */
18327    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18328            final PackageSetting ps, final int userId) {
18329        if (ps.pkg == null) {
18330            return;
18331        }
18332
18333        // These are flags that can change base on user actions.
18334        final int userSettableMask = FLAG_PERMISSION_USER_SET
18335                | FLAG_PERMISSION_USER_FIXED
18336                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18337                | FLAG_PERMISSION_REVIEW_REQUIRED;
18338
18339        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18340                | FLAG_PERMISSION_POLICY_FIXED;
18341
18342        boolean writeInstallPermissions = false;
18343        boolean writeRuntimePermissions = false;
18344
18345        final int permissionCount = ps.pkg.requestedPermissions.size();
18346        for (int i = 0; i < permissionCount; i++) {
18347            final String permName = ps.pkg.requestedPermissions.get(i);
18348            final BasePermission bp =
18349                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18350            if (bp == null) {
18351                continue;
18352            }
18353
18354            // If shared user we just reset the state to which only this app contributed.
18355            if (ps.sharedUser != null) {
18356                boolean used = false;
18357                final int packageCount = ps.sharedUser.packages.size();
18358                for (int j = 0; j < packageCount; j++) {
18359                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18360                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18361                            && pkg.pkg.requestedPermissions.contains(permName)) {
18362                        used = true;
18363                        break;
18364                    }
18365                }
18366                if (used) {
18367                    continue;
18368                }
18369            }
18370
18371            final PermissionsState permissionsState = ps.getPermissionsState();
18372
18373            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18374
18375            // Always clear the user settable flags.
18376            final boolean hasInstallState =
18377                    permissionsState.getInstallPermissionState(permName) != null;
18378            // If permission review is enabled and this is a legacy app, mark the
18379            // permission as requiring a review as this is the initial state.
18380            int flags = 0;
18381            if (mSettings.mPermissions.mPermissionReviewRequired
18382                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18383                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18384            }
18385            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18386                if (hasInstallState) {
18387                    writeInstallPermissions = true;
18388                } else {
18389                    writeRuntimePermissions = true;
18390                }
18391            }
18392
18393            // Below is only runtime permission handling.
18394            if (!bp.isRuntime()) {
18395                continue;
18396            }
18397
18398            // Never clobber system or policy.
18399            if ((oldFlags & policyOrSystemFlags) != 0) {
18400                continue;
18401            }
18402
18403            // If this permission was granted by default, make sure it is.
18404            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18405                if (permissionsState.grantRuntimePermission(bp, userId)
18406                        != PERMISSION_OPERATION_FAILURE) {
18407                    writeRuntimePermissions = true;
18408                }
18409            // If permission review is enabled the permissions for a legacy apps
18410            // are represented as constantly granted runtime ones, so don't revoke.
18411            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18412                // Otherwise, reset the permission.
18413                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18414                switch (revokeResult) {
18415                    case PERMISSION_OPERATION_SUCCESS:
18416                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18417                        writeRuntimePermissions = true;
18418                        final int appId = ps.appId;
18419                        mHandler.post(new Runnable() {
18420                            @Override
18421                            public void run() {
18422                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18423                            }
18424                        });
18425                    } break;
18426                }
18427            }
18428        }
18429
18430        // Synchronously write as we are taking permissions away.
18431        if (writeRuntimePermissions) {
18432            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18433        }
18434
18435        // Synchronously write as we are taking permissions away.
18436        if (writeInstallPermissions) {
18437            mSettings.writeLPr();
18438        }
18439    }
18440
18441    /**
18442     * Remove entries from the keystore daemon. Will only remove it if the
18443     * {@code appId} is valid.
18444     */
18445    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18446        if (appId < 0) {
18447            return;
18448        }
18449
18450        final KeyStore keyStore = KeyStore.getInstance();
18451        if (keyStore != null) {
18452            if (userId == UserHandle.USER_ALL) {
18453                for (final int individual : sUserManager.getUserIds()) {
18454                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18455                }
18456            } else {
18457                keyStore.clearUid(UserHandle.getUid(userId, appId));
18458            }
18459        } else {
18460            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18461        }
18462    }
18463
18464    @Override
18465    public void deleteApplicationCacheFiles(final String packageName,
18466            final IPackageDataObserver observer) {
18467        final int userId = UserHandle.getCallingUserId();
18468        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18469    }
18470
18471    @Override
18472    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18473            final IPackageDataObserver observer) {
18474        final int callingUid = Binder.getCallingUid();
18475        mContext.enforceCallingOrSelfPermission(
18476                android.Manifest.permission.DELETE_CACHE_FILES, null);
18477        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18478                /* requireFullPermission= */ true, /* checkShell= */ false,
18479                "delete application cache files");
18480        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18481                android.Manifest.permission.ACCESS_INSTANT_APPS);
18482
18483        final PackageParser.Package pkg;
18484        synchronized (mPackages) {
18485            pkg = mPackages.get(packageName);
18486        }
18487
18488        // Queue up an async operation since the package deletion may take a little while.
18489        mHandler.post(new Runnable() {
18490            public void run() {
18491                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18492                boolean doClearData = true;
18493                if (ps != null) {
18494                    final boolean targetIsInstantApp =
18495                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18496                    doClearData = !targetIsInstantApp
18497                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18498                }
18499                if (doClearData) {
18500                    synchronized (mInstallLock) {
18501                        final int flags = StorageManager.FLAG_STORAGE_DE
18502                                | StorageManager.FLAG_STORAGE_CE;
18503                        // We're only clearing cache files, so we don't care if the
18504                        // app is unfrozen and still able to run
18505                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18506                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18507                    }
18508                    clearExternalStorageDataSync(packageName, userId, false);
18509                }
18510                if (observer != null) {
18511                    try {
18512                        observer.onRemoveCompleted(packageName, true);
18513                    } catch (RemoteException e) {
18514                        Log.i(TAG, "Observer no longer exists.");
18515                    }
18516                }
18517            }
18518        });
18519    }
18520
18521    @Override
18522    public void getPackageSizeInfo(final String packageName, int userHandle,
18523            final IPackageStatsObserver observer) {
18524        throw new UnsupportedOperationException(
18525                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18526    }
18527
18528    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18529        final PackageSetting ps;
18530        synchronized (mPackages) {
18531            ps = mSettings.mPackages.get(packageName);
18532            if (ps == null) {
18533                Slog.w(TAG, "Failed to find settings for " + packageName);
18534                return false;
18535            }
18536        }
18537
18538        final String[] packageNames = { packageName };
18539        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18540        final String[] codePaths = { ps.codePathString };
18541
18542        try {
18543            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18544                    ps.appId, ceDataInodes, codePaths, stats);
18545
18546            // For now, ignore code size of packages on system partition
18547            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18548                stats.codeSize = 0;
18549            }
18550
18551            // External clients expect these to be tracked separately
18552            stats.dataSize -= stats.cacheSize;
18553
18554        } catch (InstallerException e) {
18555            Slog.w(TAG, String.valueOf(e));
18556            return false;
18557        }
18558
18559        return true;
18560    }
18561
18562    private int getUidTargetSdkVersionLockedLPr(int uid) {
18563        Object obj = mSettings.getUserIdLPr(uid);
18564        if (obj instanceof SharedUserSetting) {
18565            final SharedUserSetting sus = (SharedUserSetting) obj;
18566            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18567            final Iterator<PackageSetting> it = sus.packages.iterator();
18568            while (it.hasNext()) {
18569                final PackageSetting ps = it.next();
18570                if (ps.pkg != null) {
18571                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18572                    if (v < vers) vers = v;
18573                }
18574            }
18575            return vers;
18576        } else if (obj instanceof PackageSetting) {
18577            final PackageSetting ps = (PackageSetting) obj;
18578            if (ps.pkg != null) {
18579                return ps.pkg.applicationInfo.targetSdkVersion;
18580            }
18581        }
18582        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18583    }
18584
18585    @Override
18586    public void addPreferredActivity(IntentFilter filter, int match,
18587            ComponentName[] set, ComponentName activity, int userId) {
18588        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18589                "Adding preferred");
18590    }
18591
18592    private void addPreferredActivityInternal(IntentFilter filter, int match,
18593            ComponentName[] set, ComponentName activity, boolean always, int userId,
18594            String opname) {
18595        // writer
18596        int callingUid = Binder.getCallingUid();
18597        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18598                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18599        if (filter.countActions() == 0) {
18600            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18601            return;
18602        }
18603        synchronized (mPackages) {
18604            if (mContext.checkCallingOrSelfPermission(
18605                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18606                    != PackageManager.PERMISSION_GRANTED) {
18607                if (getUidTargetSdkVersionLockedLPr(callingUid)
18608                        < Build.VERSION_CODES.FROYO) {
18609                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18610                            + callingUid);
18611                    return;
18612                }
18613                mContext.enforceCallingOrSelfPermission(
18614                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18615            }
18616
18617            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18618            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18619                    + userId + ":");
18620            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18621            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18622            scheduleWritePackageRestrictionsLocked(userId);
18623            postPreferredActivityChangedBroadcast(userId);
18624        }
18625    }
18626
18627    private void postPreferredActivityChangedBroadcast(int userId) {
18628        mHandler.post(() -> {
18629            final IActivityManager am = ActivityManager.getService();
18630            if (am == null) {
18631                return;
18632            }
18633
18634            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18635            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18636            try {
18637                am.broadcastIntent(null, intent, null, null,
18638                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18639                        null, false, false, userId);
18640            } catch (RemoteException e) {
18641            }
18642        });
18643    }
18644
18645    @Override
18646    public void replacePreferredActivity(IntentFilter filter, int match,
18647            ComponentName[] set, ComponentName activity, int userId) {
18648        if (filter.countActions() != 1) {
18649            throw new IllegalArgumentException(
18650                    "replacePreferredActivity expects filter to have only 1 action.");
18651        }
18652        if (filter.countDataAuthorities() != 0
18653                || filter.countDataPaths() != 0
18654                || filter.countDataSchemes() > 1
18655                || filter.countDataTypes() != 0) {
18656            throw new IllegalArgumentException(
18657                    "replacePreferredActivity expects filter to have no data authorities, " +
18658                    "paths, or types; and at most one scheme.");
18659        }
18660
18661        final int callingUid = Binder.getCallingUid();
18662        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18663                true /* requireFullPermission */, false /* checkShell */,
18664                "replace preferred activity");
18665        synchronized (mPackages) {
18666            if (mContext.checkCallingOrSelfPermission(
18667                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18668                    != PackageManager.PERMISSION_GRANTED) {
18669                if (getUidTargetSdkVersionLockedLPr(callingUid)
18670                        < Build.VERSION_CODES.FROYO) {
18671                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18672                            + Binder.getCallingUid());
18673                    return;
18674                }
18675                mContext.enforceCallingOrSelfPermission(
18676                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18677            }
18678
18679            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18680            if (pir != null) {
18681                // Get all of the existing entries that exactly match this filter.
18682                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18683                if (existing != null && existing.size() == 1) {
18684                    PreferredActivity cur = existing.get(0);
18685                    if (DEBUG_PREFERRED) {
18686                        Slog.i(TAG, "Checking replace of preferred:");
18687                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18688                        if (!cur.mPref.mAlways) {
18689                            Slog.i(TAG, "  -- CUR; not mAlways!");
18690                        } else {
18691                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18692                            Slog.i(TAG, "  -- CUR: mSet="
18693                                    + Arrays.toString(cur.mPref.mSetComponents));
18694                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18695                            Slog.i(TAG, "  -- NEW: mMatch="
18696                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18697                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18698                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18699                        }
18700                    }
18701                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18702                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18703                            && cur.mPref.sameSet(set)) {
18704                        // Setting the preferred activity to what it happens to be already
18705                        if (DEBUG_PREFERRED) {
18706                            Slog.i(TAG, "Replacing with same preferred activity "
18707                                    + cur.mPref.mShortComponent + " for user "
18708                                    + userId + ":");
18709                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18710                        }
18711                        return;
18712                    }
18713                }
18714
18715                if (existing != null) {
18716                    if (DEBUG_PREFERRED) {
18717                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18718                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18719                    }
18720                    for (int i = 0; i < existing.size(); i++) {
18721                        PreferredActivity pa = existing.get(i);
18722                        if (DEBUG_PREFERRED) {
18723                            Slog.i(TAG, "Removing existing preferred activity "
18724                                    + pa.mPref.mComponent + ":");
18725                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18726                        }
18727                        pir.removeFilter(pa);
18728                    }
18729                }
18730            }
18731            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18732                    "Replacing preferred");
18733        }
18734    }
18735
18736    @Override
18737    public void clearPackagePreferredActivities(String packageName) {
18738        final int callingUid = Binder.getCallingUid();
18739        if (getInstantAppPackageName(callingUid) != null) {
18740            return;
18741        }
18742        // writer
18743        synchronized (mPackages) {
18744            PackageParser.Package pkg = mPackages.get(packageName);
18745            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
18746                if (mContext.checkCallingOrSelfPermission(
18747                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18748                        != PackageManager.PERMISSION_GRANTED) {
18749                    if (getUidTargetSdkVersionLockedLPr(callingUid)
18750                            < Build.VERSION_CODES.FROYO) {
18751                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18752                                + callingUid);
18753                        return;
18754                    }
18755                    mContext.enforceCallingOrSelfPermission(
18756                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18757                }
18758            }
18759            final PackageSetting ps = mSettings.getPackageLPr(packageName);
18760            if (ps != null
18761                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
18762                return;
18763            }
18764            int user = UserHandle.getCallingUserId();
18765            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18766                scheduleWritePackageRestrictionsLocked(user);
18767            }
18768        }
18769    }
18770
18771    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18772    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18773        ArrayList<PreferredActivity> removed = null;
18774        boolean changed = false;
18775        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18776            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18777            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18778            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18779                continue;
18780            }
18781            Iterator<PreferredActivity> it = pir.filterIterator();
18782            while (it.hasNext()) {
18783                PreferredActivity pa = it.next();
18784                // Mark entry for removal only if it matches the package name
18785                // and the entry is of type "always".
18786                if (packageName == null ||
18787                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18788                                && pa.mPref.mAlways)) {
18789                    if (removed == null) {
18790                        removed = new ArrayList<PreferredActivity>();
18791                    }
18792                    removed.add(pa);
18793                }
18794            }
18795            if (removed != null) {
18796                for (int j=0; j<removed.size(); j++) {
18797                    PreferredActivity pa = removed.get(j);
18798                    pir.removeFilter(pa);
18799                }
18800                changed = true;
18801            }
18802        }
18803        if (changed) {
18804            postPreferredActivityChangedBroadcast(userId);
18805        }
18806        return changed;
18807    }
18808
18809    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18810    private void clearIntentFilterVerificationsLPw(int userId) {
18811        final int packageCount = mPackages.size();
18812        for (int i = 0; i < packageCount; i++) {
18813            PackageParser.Package pkg = mPackages.valueAt(i);
18814            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18815        }
18816    }
18817
18818    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18819    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18820        if (userId == UserHandle.USER_ALL) {
18821            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18822                    sUserManager.getUserIds())) {
18823                for (int oneUserId : sUserManager.getUserIds()) {
18824                    scheduleWritePackageRestrictionsLocked(oneUserId);
18825                }
18826            }
18827        } else {
18828            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18829                scheduleWritePackageRestrictionsLocked(userId);
18830            }
18831        }
18832    }
18833
18834    /** Clears state for all users, and touches intent filter verification policy */
18835    void clearDefaultBrowserIfNeeded(String packageName) {
18836        for (int oneUserId : sUserManager.getUserIds()) {
18837            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
18838        }
18839    }
18840
18841    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
18842        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
18843        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
18844            if (packageName.equals(defaultBrowserPackageName)) {
18845                setDefaultBrowserPackageName(null, userId);
18846            }
18847        }
18848    }
18849
18850    @Override
18851    public void resetApplicationPreferences(int userId) {
18852        mContext.enforceCallingOrSelfPermission(
18853                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18854        final long identity = Binder.clearCallingIdentity();
18855        // writer
18856        try {
18857            synchronized (mPackages) {
18858                clearPackagePreferredActivitiesLPw(null, userId);
18859                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18860                // TODO: We have to reset the default SMS and Phone. This requires
18861                // significant refactoring to keep all default apps in the package
18862                // manager (cleaner but more work) or have the services provide
18863                // callbacks to the package manager to request a default app reset.
18864                applyFactoryDefaultBrowserLPw(userId);
18865                clearIntentFilterVerificationsLPw(userId);
18866                primeDomainVerificationsLPw(userId);
18867                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18868                scheduleWritePackageRestrictionsLocked(userId);
18869            }
18870            resetNetworkPolicies(userId);
18871        } finally {
18872            Binder.restoreCallingIdentity(identity);
18873        }
18874    }
18875
18876    @Override
18877    public int getPreferredActivities(List<IntentFilter> outFilters,
18878            List<ComponentName> outActivities, String packageName) {
18879        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
18880            return 0;
18881        }
18882        int num = 0;
18883        final int userId = UserHandle.getCallingUserId();
18884        // reader
18885        synchronized (mPackages) {
18886            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18887            if (pir != null) {
18888                final Iterator<PreferredActivity> it = pir.filterIterator();
18889                while (it.hasNext()) {
18890                    final PreferredActivity pa = it.next();
18891                    if (packageName == null
18892                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18893                                    && pa.mPref.mAlways)) {
18894                        if (outFilters != null) {
18895                            outFilters.add(new IntentFilter(pa));
18896                        }
18897                        if (outActivities != null) {
18898                            outActivities.add(pa.mPref.mComponent);
18899                        }
18900                    }
18901                }
18902            }
18903        }
18904
18905        return num;
18906    }
18907
18908    @Override
18909    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18910            int userId) {
18911        int callingUid = Binder.getCallingUid();
18912        if (callingUid != Process.SYSTEM_UID) {
18913            throw new SecurityException(
18914                    "addPersistentPreferredActivity can only be run by the system");
18915        }
18916        if (filter.countActions() == 0) {
18917            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18918            return;
18919        }
18920        synchronized (mPackages) {
18921            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18922                    ":");
18923            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18924            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18925                    new PersistentPreferredActivity(filter, activity));
18926            scheduleWritePackageRestrictionsLocked(userId);
18927            postPreferredActivityChangedBroadcast(userId);
18928        }
18929    }
18930
18931    @Override
18932    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18933        int callingUid = Binder.getCallingUid();
18934        if (callingUid != Process.SYSTEM_UID) {
18935            throw new SecurityException(
18936                    "clearPackagePersistentPreferredActivities can only be run by the system");
18937        }
18938        ArrayList<PersistentPreferredActivity> removed = null;
18939        boolean changed = false;
18940        synchronized (mPackages) {
18941            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18942                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18943                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18944                        .valueAt(i);
18945                if (userId != thisUserId) {
18946                    continue;
18947                }
18948                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18949                while (it.hasNext()) {
18950                    PersistentPreferredActivity ppa = it.next();
18951                    // Mark entry for removal only if it matches the package name.
18952                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18953                        if (removed == null) {
18954                            removed = new ArrayList<PersistentPreferredActivity>();
18955                        }
18956                        removed.add(ppa);
18957                    }
18958                }
18959                if (removed != null) {
18960                    for (int j=0; j<removed.size(); j++) {
18961                        PersistentPreferredActivity ppa = removed.get(j);
18962                        ppir.removeFilter(ppa);
18963                    }
18964                    changed = true;
18965                }
18966            }
18967
18968            if (changed) {
18969                scheduleWritePackageRestrictionsLocked(userId);
18970                postPreferredActivityChangedBroadcast(userId);
18971            }
18972        }
18973    }
18974
18975    /**
18976     * Common machinery for picking apart a restored XML blob and passing
18977     * it to a caller-supplied functor to be applied to the running system.
18978     */
18979    private void restoreFromXml(XmlPullParser parser, int userId,
18980            String expectedStartTag, BlobXmlRestorer functor)
18981            throws IOException, XmlPullParserException {
18982        int type;
18983        while ((type = parser.next()) != XmlPullParser.START_TAG
18984                && type != XmlPullParser.END_DOCUMENT) {
18985        }
18986        if (type != XmlPullParser.START_TAG) {
18987            // oops didn't find a start tag?!
18988            if (DEBUG_BACKUP) {
18989                Slog.e(TAG, "Didn't find start tag during restore");
18990            }
18991            return;
18992        }
18993Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18994        // this is supposed to be TAG_PREFERRED_BACKUP
18995        if (!expectedStartTag.equals(parser.getName())) {
18996            if (DEBUG_BACKUP) {
18997                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18998            }
18999            return;
19000        }
19001
19002        // skip interfering stuff, then we're aligned with the backing implementation
19003        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19004Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19005        functor.apply(parser, userId);
19006    }
19007
19008    private interface BlobXmlRestorer {
19009        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19010    }
19011
19012    /**
19013     * Non-Binder method, support for the backup/restore mechanism: write the
19014     * full set of preferred activities in its canonical XML format.  Returns the
19015     * XML output as a byte array, or null if there is none.
19016     */
19017    @Override
19018    public byte[] getPreferredActivityBackup(int userId) {
19019        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19020            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19021        }
19022
19023        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19024        try {
19025            final XmlSerializer serializer = new FastXmlSerializer();
19026            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19027            serializer.startDocument(null, true);
19028            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19029
19030            synchronized (mPackages) {
19031                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19032            }
19033
19034            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19035            serializer.endDocument();
19036            serializer.flush();
19037        } catch (Exception e) {
19038            if (DEBUG_BACKUP) {
19039                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19040            }
19041            return null;
19042        }
19043
19044        return dataStream.toByteArray();
19045    }
19046
19047    @Override
19048    public void restorePreferredActivities(byte[] backup, int userId) {
19049        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19050            throw new SecurityException("Only the system may call restorePreferredActivities()");
19051        }
19052
19053        try {
19054            final XmlPullParser parser = Xml.newPullParser();
19055            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19056            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19057                    new BlobXmlRestorer() {
19058                        @Override
19059                        public void apply(XmlPullParser parser, int userId)
19060                                throws XmlPullParserException, IOException {
19061                            synchronized (mPackages) {
19062                                mSettings.readPreferredActivitiesLPw(parser, userId);
19063                            }
19064                        }
19065                    } );
19066        } catch (Exception e) {
19067            if (DEBUG_BACKUP) {
19068                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19069            }
19070        }
19071    }
19072
19073    /**
19074     * Non-Binder method, support for the backup/restore mechanism: write the
19075     * default browser (etc) settings in its canonical XML format.  Returns the default
19076     * browser XML representation as a byte array, or null if there is none.
19077     */
19078    @Override
19079    public byte[] getDefaultAppsBackup(int userId) {
19080        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19081            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19082        }
19083
19084        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19085        try {
19086            final XmlSerializer serializer = new FastXmlSerializer();
19087            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19088            serializer.startDocument(null, true);
19089            serializer.startTag(null, TAG_DEFAULT_APPS);
19090
19091            synchronized (mPackages) {
19092                mSettings.writeDefaultAppsLPr(serializer, userId);
19093            }
19094
19095            serializer.endTag(null, TAG_DEFAULT_APPS);
19096            serializer.endDocument();
19097            serializer.flush();
19098        } catch (Exception e) {
19099            if (DEBUG_BACKUP) {
19100                Slog.e(TAG, "Unable to write default apps for backup", e);
19101            }
19102            return null;
19103        }
19104
19105        return dataStream.toByteArray();
19106    }
19107
19108    @Override
19109    public void restoreDefaultApps(byte[] backup, int userId) {
19110        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19111            throw new SecurityException("Only the system may call restoreDefaultApps()");
19112        }
19113
19114        try {
19115            final XmlPullParser parser = Xml.newPullParser();
19116            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19117            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19118                    new BlobXmlRestorer() {
19119                        @Override
19120                        public void apply(XmlPullParser parser, int userId)
19121                                throws XmlPullParserException, IOException {
19122                            synchronized (mPackages) {
19123                                mSettings.readDefaultAppsLPw(parser, userId);
19124                            }
19125                        }
19126                    } );
19127        } catch (Exception e) {
19128            if (DEBUG_BACKUP) {
19129                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19130            }
19131        }
19132    }
19133
19134    @Override
19135    public byte[] getIntentFilterVerificationBackup(int userId) {
19136        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19137            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19138        }
19139
19140        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19141        try {
19142            final XmlSerializer serializer = new FastXmlSerializer();
19143            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19144            serializer.startDocument(null, true);
19145            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19146
19147            synchronized (mPackages) {
19148                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19149            }
19150
19151            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19152            serializer.endDocument();
19153            serializer.flush();
19154        } catch (Exception e) {
19155            if (DEBUG_BACKUP) {
19156                Slog.e(TAG, "Unable to write default apps for backup", e);
19157            }
19158            return null;
19159        }
19160
19161        return dataStream.toByteArray();
19162    }
19163
19164    @Override
19165    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19166        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19167            throw new SecurityException("Only the system may call restorePreferredActivities()");
19168        }
19169
19170        try {
19171            final XmlPullParser parser = Xml.newPullParser();
19172            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19173            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19174                    new BlobXmlRestorer() {
19175                        @Override
19176                        public void apply(XmlPullParser parser, int userId)
19177                                throws XmlPullParserException, IOException {
19178                            synchronized (mPackages) {
19179                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19180                                mSettings.writeLPr();
19181                            }
19182                        }
19183                    } );
19184        } catch (Exception e) {
19185            if (DEBUG_BACKUP) {
19186                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19187            }
19188        }
19189    }
19190
19191    @Override
19192    public byte[] getPermissionGrantBackup(int userId) {
19193        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19194            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19195        }
19196
19197        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19198        try {
19199            final XmlSerializer serializer = new FastXmlSerializer();
19200            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19201            serializer.startDocument(null, true);
19202            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19203
19204            synchronized (mPackages) {
19205                serializeRuntimePermissionGrantsLPr(serializer, userId);
19206            }
19207
19208            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19209            serializer.endDocument();
19210            serializer.flush();
19211        } catch (Exception e) {
19212            if (DEBUG_BACKUP) {
19213                Slog.e(TAG, "Unable to write default apps for backup", e);
19214            }
19215            return null;
19216        }
19217
19218        return dataStream.toByteArray();
19219    }
19220
19221    @Override
19222    public void restorePermissionGrants(byte[] backup, int userId) {
19223        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19224            throw new SecurityException("Only the system may call restorePermissionGrants()");
19225        }
19226
19227        try {
19228            final XmlPullParser parser = Xml.newPullParser();
19229            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19230            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19231                    new BlobXmlRestorer() {
19232                        @Override
19233                        public void apply(XmlPullParser parser, int userId)
19234                                throws XmlPullParserException, IOException {
19235                            synchronized (mPackages) {
19236                                processRestoredPermissionGrantsLPr(parser, userId);
19237                            }
19238                        }
19239                    } );
19240        } catch (Exception e) {
19241            if (DEBUG_BACKUP) {
19242                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19243            }
19244        }
19245    }
19246
19247    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19248            throws IOException {
19249        serializer.startTag(null, TAG_ALL_GRANTS);
19250
19251        final int N = mSettings.mPackages.size();
19252        for (int i = 0; i < N; i++) {
19253            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19254            boolean pkgGrantsKnown = false;
19255
19256            PermissionsState packagePerms = ps.getPermissionsState();
19257
19258            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19259                final int grantFlags = state.getFlags();
19260                // only look at grants that are not system/policy fixed
19261                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19262                    final boolean isGranted = state.isGranted();
19263                    // And only back up the user-twiddled state bits
19264                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19265                        final String packageName = mSettings.mPackages.keyAt(i);
19266                        if (!pkgGrantsKnown) {
19267                            serializer.startTag(null, TAG_GRANT);
19268                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19269                            pkgGrantsKnown = true;
19270                        }
19271
19272                        final boolean userSet =
19273                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19274                        final boolean userFixed =
19275                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19276                        final boolean revoke =
19277                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19278
19279                        serializer.startTag(null, TAG_PERMISSION);
19280                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19281                        if (isGranted) {
19282                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19283                        }
19284                        if (userSet) {
19285                            serializer.attribute(null, ATTR_USER_SET, "true");
19286                        }
19287                        if (userFixed) {
19288                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19289                        }
19290                        if (revoke) {
19291                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19292                        }
19293                        serializer.endTag(null, TAG_PERMISSION);
19294                    }
19295                }
19296            }
19297
19298            if (pkgGrantsKnown) {
19299                serializer.endTag(null, TAG_GRANT);
19300            }
19301        }
19302
19303        serializer.endTag(null, TAG_ALL_GRANTS);
19304    }
19305
19306    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19307            throws XmlPullParserException, IOException {
19308        String pkgName = null;
19309        int outerDepth = parser.getDepth();
19310        int type;
19311        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19312                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19313            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19314                continue;
19315            }
19316
19317            final String tagName = parser.getName();
19318            if (tagName.equals(TAG_GRANT)) {
19319                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19320                if (DEBUG_BACKUP) {
19321                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19322                }
19323            } else if (tagName.equals(TAG_PERMISSION)) {
19324
19325                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19326                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19327
19328                int newFlagSet = 0;
19329                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19330                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19331                }
19332                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19333                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19334                }
19335                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19336                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19337                }
19338                if (DEBUG_BACKUP) {
19339                    Slog.v(TAG, "  + Restoring grant:"
19340                            + " pkg=" + pkgName
19341                            + " perm=" + permName
19342                            + " granted=" + isGranted
19343                            + " bits=0x" + Integer.toHexString(newFlagSet));
19344                }
19345                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19346                if (ps != null) {
19347                    // Already installed so we apply the grant immediately
19348                    if (DEBUG_BACKUP) {
19349                        Slog.v(TAG, "        + already installed; applying");
19350                    }
19351                    PermissionsState perms = ps.getPermissionsState();
19352                    BasePermission bp =
19353                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19354                    if (bp != null) {
19355                        if (isGranted) {
19356                            perms.grantRuntimePermission(bp, userId);
19357                        }
19358                        if (newFlagSet != 0) {
19359                            perms.updatePermissionFlags(
19360                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19361                        }
19362                    }
19363                } else {
19364                    // Need to wait for post-restore install to apply the grant
19365                    if (DEBUG_BACKUP) {
19366                        Slog.v(TAG, "        - not yet installed; saving for later");
19367                    }
19368                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19369                            isGranted, newFlagSet, userId);
19370                }
19371            } else {
19372                PackageManagerService.reportSettingsProblem(Log.WARN,
19373                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19374                XmlUtils.skipCurrentTag(parser);
19375            }
19376        }
19377
19378        scheduleWriteSettingsLocked();
19379        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19380    }
19381
19382    @Override
19383    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19384            int sourceUserId, int targetUserId, int flags) {
19385        mContext.enforceCallingOrSelfPermission(
19386                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19387        int callingUid = Binder.getCallingUid();
19388        enforceOwnerRights(ownerPackage, callingUid);
19389        PackageManagerServiceUtils.enforceShellRestriction(
19390                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19391        if (intentFilter.countActions() == 0) {
19392            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19393            return;
19394        }
19395        synchronized (mPackages) {
19396            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19397                    ownerPackage, targetUserId, flags);
19398            CrossProfileIntentResolver resolver =
19399                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19400            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19401            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19402            if (existing != null) {
19403                int size = existing.size();
19404                for (int i = 0; i < size; i++) {
19405                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19406                        return;
19407                    }
19408                }
19409            }
19410            resolver.addFilter(newFilter);
19411            scheduleWritePackageRestrictionsLocked(sourceUserId);
19412        }
19413    }
19414
19415    @Override
19416    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19417        mContext.enforceCallingOrSelfPermission(
19418                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19419        final int callingUid = Binder.getCallingUid();
19420        enforceOwnerRights(ownerPackage, callingUid);
19421        PackageManagerServiceUtils.enforceShellRestriction(
19422                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19423        synchronized (mPackages) {
19424            CrossProfileIntentResolver resolver =
19425                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19426            ArraySet<CrossProfileIntentFilter> set =
19427                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19428            for (CrossProfileIntentFilter filter : set) {
19429                if (filter.getOwnerPackage().equals(ownerPackage)) {
19430                    resolver.removeFilter(filter);
19431                }
19432            }
19433            scheduleWritePackageRestrictionsLocked(sourceUserId);
19434        }
19435    }
19436
19437    // Enforcing that callingUid is owning pkg on userId
19438    private void enforceOwnerRights(String pkg, int callingUid) {
19439        // The system owns everything.
19440        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19441            return;
19442        }
19443        final int callingUserId = UserHandle.getUserId(callingUid);
19444        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19445        if (pi == null) {
19446            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19447                    + callingUserId);
19448        }
19449        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19450            throw new SecurityException("Calling uid " + callingUid
19451                    + " does not own package " + pkg);
19452        }
19453    }
19454
19455    @Override
19456    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19457        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19458            return null;
19459        }
19460        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19461    }
19462
19463    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19464        UserManagerService ums = UserManagerService.getInstance();
19465        if (ums != null) {
19466            final UserInfo parent = ums.getProfileParent(userId);
19467            final int launcherUid = (parent != null) ? parent.id : userId;
19468            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19469            if (launcherComponent != null) {
19470                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19471                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19472                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19473                        .setPackage(launcherComponent.getPackageName());
19474                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19475            }
19476        }
19477    }
19478
19479    /**
19480     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19481     * then reports the most likely home activity or null if there are more than one.
19482     */
19483    private ComponentName getDefaultHomeActivity(int userId) {
19484        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19485        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19486        if (cn != null) {
19487            return cn;
19488        }
19489
19490        // Find the launcher with the highest priority and return that component if there are no
19491        // other home activity with the same priority.
19492        int lastPriority = Integer.MIN_VALUE;
19493        ComponentName lastComponent = null;
19494        final int size = allHomeCandidates.size();
19495        for (int i = 0; i < size; i++) {
19496            final ResolveInfo ri = allHomeCandidates.get(i);
19497            if (ri.priority > lastPriority) {
19498                lastComponent = ri.activityInfo.getComponentName();
19499                lastPriority = ri.priority;
19500            } else if (ri.priority == lastPriority) {
19501                // Two components found with same priority.
19502                lastComponent = null;
19503            }
19504        }
19505        return lastComponent;
19506    }
19507
19508    private Intent getHomeIntent() {
19509        Intent intent = new Intent(Intent.ACTION_MAIN);
19510        intent.addCategory(Intent.CATEGORY_HOME);
19511        intent.addCategory(Intent.CATEGORY_DEFAULT);
19512        return intent;
19513    }
19514
19515    private IntentFilter getHomeFilter() {
19516        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19517        filter.addCategory(Intent.CATEGORY_HOME);
19518        filter.addCategory(Intent.CATEGORY_DEFAULT);
19519        return filter;
19520    }
19521
19522    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19523            int userId) {
19524        Intent intent  = getHomeIntent();
19525        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19526                PackageManager.GET_META_DATA, userId);
19527        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19528                true, false, false, userId);
19529
19530        allHomeCandidates.clear();
19531        if (list != null) {
19532            for (ResolveInfo ri : list) {
19533                allHomeCandidates.add(ri);
19534            }
19535        }
19536        return (preferred == null || preferred.activityInfo == null)
19537                ? null
19538                : new ComponentName(preferred.activityInfo.packageName,
19539                        preferred.activityInfo.name);
19540    }
19541
19542    @Override
19543    public void setHomeActivity(ComponentName comp, int userId) {
19544        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19545            return;
19546        }
19547        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19548        getHomeActivitiesAsUser(homeActivities, userId);
19549
19550        boolean found = false;
19551
19552        final int size = homeActivities.size();
19553        final ComponentName[] set = new ComponentName[size];
19554        for (int i = 0; i < size; i++) {
19555            final ResolveInfo candidate = homeActivities.get(i);
19556            final ActivityInfo info = candidate.activityInfo;
19557            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19558            set[i] = activityName;
19559            if (!found && activityName.equals(comp)) {
19560                found = true;
19561            }
19562        }
19563        if (!found) {
19564            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19565                    + userId);
19566        }
19567        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19568                set, comp, userId);
19569    }
19570
19571    private @Nullable String getSetupWizardPackageName() {
19572        final Intent intent = new Intent(Intent.ACTION_MAIN);
19573        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19574
19575        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19576                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19577                        | MATCH_DISABLED_COMPONENTS,
19578                UserHandle.myUserId());
19579        if (matches.size() == 1) {
19580            return matches.get(0).getComponentInfo().packageName;
19581        } else {
19582            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19583                    + ": matches=" + matches);
19584            return null;
19585        }
19586    }
19587
19588    private @Nullable String getStorageManagerPackageName() {
19589        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19590
19591        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19592                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19593                        | MATCH_DISABLED_COMPONENTS,
19594                UserHandle.myUserId());
19595        if (matches.size() == 1) {
19596            return matches.get(0).getComponentInfo().packageName;
19597        } else {
19598            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19599                    + matches.size() + ": matches=" + matches);
19600            return null;
19601        }
19602    }
19603
19604    @Override
19605    public void setApplicationEnabledSetting(String appPackageName,
19606            int newState, int flags, int userId, String callingPackage) {
19607        if (!sUserManager.exists(userId)) return;
19608        if (callingPackage == null) {
19609            callingPackage = Integer.toString(Binder.getCallingUid());
19610        }
19611        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19612    }
19613
19614    @Override
19615    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19616        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19617        synchronized (mPackages) {
19618            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19619            if (pkgSetting != null) {
19620                pkgSetting.setUpdateAvailable(updateAvailable);
19621            }
19622        }
19623    }
19624
19625    @Override
19626    public void setComponentEnabledSetting(ComponentName componentName,
19627            int newState, int flags, int userId) {
19628        if (!sUserManager.exists(userId)) return;
19629        setEnabledSetting(componentName.getPackageName(),
19630                componentName.getClassName(), newState, flags, userId, null);
19631    }
19632
19633    private void setEnabledSetting(final String packageName, String className, int newState,
19634            final int flags, int userId, String callingPackage) {
19635        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19636              || newState == COMPONENT_ENABLED_STATE_ENABLED
19637              || newState == COMPONENT_ENABLED_STATE_DISABLED
19638              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19639              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19640            throw new IllegalArgumentException("Invalid new component state: "
19641                    + newState);
19642        }
19643        PackageSetting pkgSetting;
19644        final int callingUid = Binder.getCallingUid();
19645        final int permission;
19646        if (callingUid == Process.SYSTEM_UID) {
19647            permission = PackageManager.PERMISSION_GRANTED;
19648        } else {
19649            permission = mContext.checkCallingOrSelfPermission(
19650                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19651        }
19652        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19653                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19654        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19655        boolean sendNow = false;
19656        boolean isApp = (className == null);
19657        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19658        String componentName = isApp ? packageName : className;
19659        int packageUid = -1;
19660        ArrayList<String> components;
19661
19662        // reader
19663        synchronized (mPackages) {
19664            pkgSetting = mSettings.mPackages.get(packageName);
19665            if (pkgSetting == null) {
19666                if (!isCallerInstantApp) {
19667                    if (className == null) {
19668                        throw new IllegalArgumentException("Unknown package: " + packageName);
19669                    }
19670                    throw new IllegalArgumentException(
19671                            "Unknown component: " + packageName + "/" + className);
19672                } else {
19673                    // throw SecurityException to prevent leaking package information
19674                    throw new SecurityException(
19675                            "Attempt to change component state; "
19676                            + "pid=" + Binder.getCallingPid()
19677                            + ", uid=" + callingUid
19678                            + (className == null
19679                                    ? ", package=" + packageName
19680                                    : ", component=" + packageName + "/" + className));
19681                }
19682            }
19683        }
19684
19685        // Limit who can change which apps
19686        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
19687            // Don't allow apps that don't have permission to modify other apps
19688            if (!allowedByPermission
19689                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
19690                throw new SecurityException(
19691                        "Attempt to change component state; "
19692                        + "pid=" + Binder.getCallingPid()
19693                        + ", uid=" + callingUid
19694                        + (className == null
19695                                ? ", package=" + packageName
19696                                : ", component=" + packageName + "/" + className));
19697            }
19698            // Don't allow changing protected packages.
19699            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19700                throw new SecurityException("Cannot disable a protected package: " + packageName);
19701            }
19702        }
19703
19704        synchronized (mPackages) {
19705            if (callingUid == Process.SHELL_UID
19706                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19707                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19708                // unless it is a test package.
19709                int oldState = pkgSetting.getEnabled(userId);
19710                if (className == null
19711                        &&
19712                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19713                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19714                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19715                        &&
19716                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19717                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
19718                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19719                    // ok
19720                } else {
19721                    throw new SecurityException(
19722                            "Shell cannot change component state for " + packageName + "/"
19723                                    + className + " to " + newState);
19724                }
19725            }
19726        }
19727        if (className == null) {
19728            // We're dealing with an application/package level state change
19729            synchronized (mPackages) {
19730                if (pkgSetting.getEnabled(userId) == newState) {
19731                    // Nothing to do
19732                    return;
19733                }
19734            }
19735            // If we're enabling a system stub, there's a little more work to do.
19736            // Prior to enabling the package, we need to decompress the APK(s) to the
19737            // data partition and then replace the version on the system partition.
19738            final PackageParser.Package deletedPkg = pkgSetting.pkg;
19739            final boolean isSystemStub = deletedPkg.isStub
19740                    && deletedPkg.isSystem();
19741            if (isSystemStub
19742                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19743                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
19744                final File codePath = decompressPackage(deletedPkg);
19745                if (codePath == null) {
19746                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
19747                    return;
19748                }
19749                // TODO remove direct parsing of the package object during internal cleanup
19750                // of scan package
19751                // We need to call parse directly here for no other reason than we need
19752                // the new package in order to disable the old one [we use the information
19753                // for some internal optimization to optionally create a new package setting
19754                // object on replace]. However, we can't get the package from the scan
19755                // because the scan modifies live structures and we need to remove the
19756                // old [system] package from the system before a scan can be attempted.
19757                // Once scan is indempotent we can remove this parse and use the package
19758                // object we scanned, prior to adding it to package settings.
19759                final PackageParser pp = new PackageParser();
19760                pp.setSeparateProcesses(mSeparateProcesses);
19761                pp.setDisplayMetrics(mMetrics);
19762                pp.setCallback(mPackageParserCallback);
19763                final PackageParser.Package tmpPkg;
19764                try {
19765                    final @ParseFlags int parseFlags = mDefParseFlags
19766                            | PackageParser.PARSE_MUST_BE_APK
19767                            | PackageParser.PARSE_IS_SYSTEM_DIR;
19768                    tmpPkg = pp.parsePackage(codePath, parseFlags);
19769                } catch (PackageParserException e) {
19770                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
19771                    return;
19772                }
19773                synchronized (mInstallLock) {
19774                    // Disable the stub and remove any package entries
19775                    removePackageLI(deletedPkg, true);
19776                    synchronized (mPackages) {
19777                        disableSystemPackageLPw(deletedPkg, tmpPkg);
19778                    }
19779                    final PackageParser.Package pkg;
19780                    try (PackageFreezer freezer =
19781                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19782                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
19783                                | PackageParser.PARSE_ENFORCE_CODE;
19784                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
19785                                0 /*currentTime*/, null /*user*/);
19786                        prepareAppDataAfterInstallLIF(pkg);
19787                        synchronized (mPackages) {
19788                            try {
19789                                updateSharedLibrariesLPr(pkg, null);
19790                            } catch (PackageManagerException e) {
19791                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
19792                            }
19793                            mPermissionManager.updatePermissions(
19794                                    pkg.packageName, pkg, true, mPackages.values(),
19795                                    mPermissionCallback);
19796                            mSettings.writeLPr();
19797                        }
19798                    } catch (PackageManagerException e) {
19799                        // Whoops! Something went wrong; try to roll back to the stub
19800                        Slog.w(TAG, "Failed to install compressed system package:"
19801                                + pkgSetting.name, e);
19802                        // Remove the failed install
19803                        removeCodePathLI(codePath);
19804
19805                        // Install the system package
19806                        try (PackageFreezer freezer =
19807                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19808                            synchronized (mPackages) {
19809                                // NOTE: The system package always needs to be enabled; even
19810                                // if it's for a compressed stub. If we don't, installing the
19811                                // system package fails during scan [scanning checks the disabled
19812                                // packages]. We will reverse this later, after we've "installed"
19813                                // the stub.
19814                                // This leaves us in a fragile state; the stub should never be
19815                                // enabled, so, cross your fingers and hope nothing goes wrong
19816                                // until we can disable the package later.
19817                                enableSystemPackageLPw(deletedPkg);
19818                            }
19819                            installPackageFromSystemLIF(deletedPkg.codePath,
19820                                    false /*isPrivileged*/, null /*allUserHandles*/,
19821                                    null /*origUserHandles*/, null /*origPermissionsState*/,
19822                                    true /*writeSettings*/);
19823                        } catch (PackageManagerException pme) {
19824                            Slog.w(TAG, "Failed to restore system package:"
19825                                    + deletedPkg.packageName, pme);
19826                        } finally {
19827                            synchronized (mPackages) {
19828                                mSettings.disableSystemPackageLPw(
19829                                        deletedPkg.packageName, true /*replaced*/);
19830                                mSettings.writeLPr();
19831                            }
19832                        }
19833                        return;
19834                    }
19835                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
19836                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19837                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19838                    mDexManager.notifyPackageUpdated(pkg.packageName,
19839                            pkg.baseCodePath, pkg.splitCodePaths);
19840                }
19841            }
19842            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19843                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19844                // Don't care about who enables an app.
19845                callingPackage = null;
19846            }
19847            synchronized (mPackages) {
19848                pkgSetting.setEnabled(newState, userId, callingPackage);
19849            }
19850        } else {
19851            synchronized (mPackages) {
19852                // We're dealing with a component level state change
19853                // First, verify that this is a valid class name.
19854                PackageParser.Package pkg = pkgSetting.pkg;
19855                if (pkg == null || !pkg.hasComponentClassName(className)) {
19856                    if (pkg != null &&
19857                            pkg.applicationInfo.targetSdkVersion >=
19858                                    Build.VERSION_CODES.JELLY_BEAN) {
19859                        throw new IllegalArgumentException("Component class " + className
19860                                + " does not exist in " + packageName);
19861                    } else {
19862                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19863                                + className + " does not exist in " + packageName);
19864                    }
19865                }
19866                switch (newState) {
19867                    case COMPONENT_ENABLED_STATE_ENABLED:
19868                        if (!pkgSetting.enableComponentLPw(className, userId)) {
19869                            return;
19870                        }
19871                        break;
19872                    case COMPONENT_ENABLED_STATE_DISABLED:
19873                        if (!pkgSetting.disableComponentLPw(className, userId)) {
19874                            return;
19875                        }
19876                        break;
19877                    case COMPONENT_ENABLED_STATE_DEFAULT:
19878                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
19879                            return;
19880                        }
19881                        break;
19882                    default:
19883                        Slog.e(TAG, "Invalid new component state: " + newState);
19884                        return;
19885                }
19886            }
19887        }
19888        synchronized (mPackages) {
19889            scheduleWritePackageRestrictionsLocked(userId);
19890            updateSequenceNumberLP(pkgSetting, new int[] { userId });
19891            final long callingId = Binder.clearCallingIdentity();
19892            try {
19893                updateInstantAppInstallerLocked(packageName);
19894            } finally {
19895                Binder.restoreCallingIdentity(callingId);
19896            }
19897            components = mPendingBroadcasts.get(userId, packageName);
19898            final boolean newPackage = components == null;
19899            if (newPackage) {
19900                components = new ArrayList<String>();
19901            }
19902            if (!components.contains(componentName)) {
19903                components.add(componentName);
19904            }
19905            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19906                sendNow = true;
19907                // Purge entry from pending broadcast list if another one exists already
19908                // since we are sending one right away.
19909                mPendingBroadcasts.remove(userId, packageName);
19910            } else {
19911                if (newPackage) {
19912                    mPendingBroadcasts.put(userId, packageName, components);
19913                }
19914                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19915                    // Schedule a message
19916                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19917                }
19918            }
19919        }
19920
19921        long callingId = Binder.clearCallingIdentity();
19922        try {
19923            if (sendNow) {
19924                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19925                sendPackageChangedBroadcast(packageName,
19926                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19927            }
19928        } finally {
19929            Binder.restoreCallingIdentity(callingId);
19930        }
19931    }
19932
19933    @Override
19934    public void flushPackageRestrictionsAsUser(int userId) {
19935        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19936            return;
19937        }
19938        if (!sUserManager.exists(userId)) {
19939            return;
19940        }
19941        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19942                false /* checkShell */, "flushPackageRestrictions");
19943        synchronized (mPackages) {
19944            mSettings.writePackageRestrictionsLPr(userId);
19945            mDirtyUsers.remove(userId);
19946            if (mDirtyUsers.isEmpty()) {
19947                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19948            }
19949        }
19950    }
19951
19952    private void sendPackageChangedBroadcast(String packageName,
19953            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19954        if (DEBUG_INSTALL)
19955            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19956                    + componentNames);
19957        Bundle extras = new Bundle(4);
19958        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19959        String nameList[] = new String[componentNames.size()];
19960        componentNames.toArray(nameList);
19961        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19962        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19963        extras.putInt(Intent.EXTRA_UID, packageUid);
19964        // If this is not reporting a change of the overall package, then only send it
19965        // to registered receivers.  We don't want to launch a swath of apps for every
19966        // little component state change.
19967        final int flags = !componentNames.contains(packageName)
19968                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19969        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19970                new int[] {UserHandle.getUserId(packageUid)});
19971    }
19972
19973    @Override
19974    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19975        if (!sUserManager.exists(userId)) return;
19976        final int callingUid = Binder.getCallingUid();
19977        if (getInstantAppPackageName(callingUid) != null) {
19978            return;
19979        }
19980        final int permission = mContext.checkCallingOrSelfPermission(
19981                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19982        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19983        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19984                true /* requireFullPermission */, true /* checkShell */, "stop package");
19985        // writer
19986        synchronized (mPackages) {
19987            final PackageSetting ps = mSettings.mPackages.get(packageName);
19988            if (!filterAppAccessLPr(ps, callingUid, userId)
19989                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19990                            allowedByPermission, callingUid, userId)) {
19991                scheduleWritePackageRestrictionsLocked(userId);
19992            }
19993        }
19994    }
19995
19996    @Override
19997    public String getInstallerPackageName(String packageName) {
19998        final int callingUid = Binder.getCallingUid();
19999        if (getInstantAppPackageName(callingUid) != null) {
20000            return null;
20001        }
20002        // reader
20003        synchronized (mPackages) {
20004            final PackageSetting ps = mSettings.mPackages.get(packageName);
20005            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20006                return null;
20007            }
20008            return mSettings.getInstallerPackageNameLPr(packageName);
20009        }
20010    }
20011
20012    public boolean isOrphaned(String packageName) {
20013        // reader
20014        synchronized (mPackages) {
20015            return mSettings.isOrphaned(packageName);
20016        }
20017    }
20018
20019    @Override
20020    public int getApplicationEnabledSetting(String packageName, int userId) {
20021        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20022        int callingUid = Binder.getCallingUid();
20023        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20024                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20025        // reader
20026        synchronized (mPackages) {
20027            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20028                return COMPONENT_ENABLED_STATE_DISABLED;
20029            }
20030            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20031        }
20032    }
20033
20034    @Override
20035    public int getComponentEnabledSetting(ComponentName component, int userId) {
20036        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20037        int callingUid = Binder.getCallingUid();
20038        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20039                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20040        synchronized (mPackages) {
20041            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20042                    component, TYPE_UNKNOWN, userId)) {
20043                return COMPONENT_ENABLED_STATE_DISABLED;
20044            }
20045            return mSettings.getComponentEnabledSettingLPr(component, userId);
20046        }
20047    }
20048
20049    @Override
20050    public void enterSafeMode() {
20051        enforceSystemOrRoot("Only the system can request entering safe mode");
20052
20053        if (!mSystemReady) {
20054            mSafeMode = true;
20055        }
20056    }
20057
20058    @Override
20059    public void systemReady() {
20060        enforceSystemOrRoot("Only the system can claim the system is ready");
20061
20062        mSystemReady = true;
20063        final ContentResolver resolver = mContext.getContentResolver();
20064        ContentObserver co = new ContentObserver(mHandler) {
20065            @Override
20066            public void onChange(boolean selfChange) {
20067                mEphemeralAppsDisabled =
20068                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20069                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20070            }
20071        };
20072        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20073                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20074                false, co, UserHandle.USER_SYSTEM);
20075        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20076                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20077        co.onChange(true);
20078
20079        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20080        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20081        // it is done.
20082        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20083            @Override
20084            public void onChange(boolean selfChange) {
20085                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20086                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20087                        oobEnabled == 1 ? "true" : "false");
20088            }
20089        };
20090        mContext.getContentResolver().registerContentObserver(
20091                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20092                UserHandle.USER_SYSTEM);
20093        // At boot, restore the value from the setting, which persists across reboot.
20094        privAppOobObserver.onChange(true);
20095
20096        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20097        // disabled after already being started.
20098        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20099                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20100
20101        // Read the compatibilty setting when the system is ready.
20102        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20103                mContext.getContentResolver(),
20104                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20105        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20106        if (DEBUG_SETTINGS) {
20107            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20108        }
20109
20110        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20111
20112        synchronized (mPackages) {
20113            // Verify that all of the preferred activity components actually
20114            // exist.  It is possible for applications to be updated and at
20115            // that point remove a previously declared activity component that
20116            // had been set as a preferred activity.  We try to clean this up
20117            // the next time we encounter that preferred activity, but it is
20118            // possible for the user flow to never be able to return to that
20119            // situation so here we do a sanity check to make sure we haven't
20120            // left any junk around.
20121            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20122            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20123                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20124                removed.clear();
20125                for (PreferredActivity pa : pir.filterSet()) {
20126                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20127                        removed.add(pa);
20128                    }
20129                }
20130                if (removed.size() > 0) {
20131                    for (int r=0; r<removed.size(); r++) {
20132                        PreferredActivity pa = removed.get(r);
20133                        Slog.w(TAG, "Removing dangling preferred activity: "
20134                                + pa.mPref.mComponent);
20135                        pir.removeFilter(pa);
20136                    }
20137                    mSettings.writePackageRestrictionsLPr(
20138                            mSettings.mPreferredActivities.keyAt(i));
20139                }
20140            }
20141
20142            for (int userId : UserManagerService.getInstance().getUserIds()) {
20143                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20144                    grantPermissionsUserIds = ArrayUtils.appendInt(
20145                            grantPermissionsUserIds, userId);
20146                }
20147            }
20148        }
20149        sUserManager.systemReady();
20150
20151        // If we upgraded grant all default permissions before kicking off.
20152        for (int userId : grantPermissionsUserIds) {
20153            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
20154        }
20155
20156        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20157            // If we did not grant default permissions, we preload from this the
20158            // default permission exceptions lazily to ensure we don't hit the
20159            // disk on a new user creation.
20160            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20161        }
20162
20163        // Now that we've scanned all packages, and granted any default
20164        // permissions, ensure permissions are updated. Beware of dragons if you
20165        // try optimizing this.
20166        synchronized (mPackages) {
20167            mPermissionManager.updateAllPermissions(
20168                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20169                    mPermissionCallback);
20170        }
20171
20172        // Kick off any messages waiting for system ready
20173        if (mPostSystemReadyMessages != null) {
20174            for (Message msg : mPostSystemReadyMessages) {
20175                msg.sendToTarget();
20176            }
20177            mPostSystemReadyMessages = null;
20178        }
20179
20180        // Watch for external volumes that come and go over time
20181        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20182        storage.registerListener(mStorageListener);
20183
20184        mInstallerService.systemReady();
20185        mPackageDexOptimizer.systemReady();
20186
20187        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20188                StorageManagerInternal.class);
20189        StorageManagerInternal.addExternalStoragePolicy(
20190                new StorageManagerInternal.ExternalStorageMountPolicy() {
20191            @Override
20192            public int getMountMode(int uid, String packageName) {
20193                if (Process.isIsolated(uid)) {
20194                    return Zygote.MOUNT_EXTERNAL_NONE;
20195                }
20196                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20197                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20198                }
20199                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20200                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20201                }
20202                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20203                    return Zygote.MOUNT_EXTERNAL_READ;
20204                }
20205                return Zygote.MOUNT_EXTERNAL_WRITE;
20206            }
20207
20208            @Override
20209            public boolean hasExternalStorage(int uid, String packageName) {
20210                return true;
20211            }
20212        });
20213
20214        // Now that we're mostly running, clean up stale users and apps
20215        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20216        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20217
20218        mPermissionManager.systemReady();
20219    }
20220
20221    public void waitForAppDataPrepared() {
20222        if (mPrepareAppDataFuture == null) {
20223            return;
20224        }
20225        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20226        mPrepareAppDataFuture = null;
20227    }
20228
20229    @Override
20230    public boolean isSafeMode() {
20231        // allow instant applications
20232        return mSafeMode;
20233    }
20234
20235    @Override
20236    public boolean hasSystemUidErrors() {
20237        // allow instant applications
20238        return mHasSystemUidErrors;
20239    }
20240
20241    static String arrayToString(int[] array) {
20242        StringBuffer buf = new StringBuffer(128);
20243        buf.append('[');
20244        if (array != null) {
20245            for (int i=0; i<array.length; i++) {
20246                if (i > 0) buf.append(", ");
20247                buf.append(array[i]);
20248            }
20249        }
20250        buf.append(']');
20251        return buf.toString();
20252    }
20253
20254    @Override
20255    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20256            FileDescriptor err, String[] args, ShellCallback callback,
20257            ResultReceiver resultReceiver) {
20258        (new PackageManagerShellCommand(this)).exec(
20259                this, in, out, err, args, callback, resultReceiver);
20260    }
20261
20262    @Override
20263    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20264        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20265
20266        DumpState dumpState = new DumpState();
20267        boolean fullPreferred = false;
20268        boolean checkin = false;
20269
20270        String packageName = null;
20271        ArraySet<String> permissionNames = null;
20272
20273        int opti = 0;
20274        while (opti < args.length) {
20275            String opt = args[opti];
20276            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20277                break;
20278            }
20279            opti++;
20280
20281            if ("-a".equals(opt)) {
20282                // Right now we only know how to print all.
20283            } else if ("-h".equals(opt)) {
20284                pw.println("Package manager dump options:");
20285                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20286                pw.println("    --checkin: dump for a checkin");
20287                pw.println("    -f: print details of intent filters");
20288                pw.println("    -h: print this help");
20289                pw.println("  cmd may be one of:");
20290                pw.println("    l[ibraries]: list known shared libraries");
20291                pw.println("    f[eatures]: list device features");
20292                pw.println("    k[eysets]: print known keysets");
20293                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20294                pw.println("    perm[issions]: dump permissions");
20295                pw.println("    permission [name ...]: dump declaration and use of given permission");
20296                pw.println("    pref[erred]: print preferred package settings");
20297                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20298                pw.println("    prov[iders]: dump content providers");
20299                pw.println("    p[ackages]: dump installed packages");
20300                pw.println("    s[hared-users]: dump shared user IDs");
20301                pw.println("    m[essages]: print collected runtime messages");
20302                pw.println("    v[erifiers]: print package verifier info");
20303                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20304                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20305                pw.println("    version: print database version info");
20306                pw.println("    write: write current settings now");
20307                pw.println("    installs: details about install sessions");
20308                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20309                pw.println("    dexopt: dump dexopt state");
20310                pw.println("    compiler-stats: dump compiler statistics");
20311                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20312                pw.println("    <package.name>: info about given package");
20313                return;
20314            } else if ("--checkin".equals(opt)) {
20315                checkin = true;
20316            } else if ("-f".equals(opt)) {
20317                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20318            } else if ("--proto".equals(opt)) {
20319                dumpProto(fd);
20320                return;
20321            } else {
20322                pw.println("Unknown argument: " + opt + "; use -h for help");
20323            }
20324        }
20325
20326        // Is the caller requesting to dump a particular piece of data?
20327        if (opti < args.length) {
20328            String cmd = args[opti];
20329            opti++;
20330            // Is this a package name?
20331            if ("android".equals(cmd) || cmd.contains(".")) {
20332                packageName = cmd;
20333                // When dumping a single package, we always dump all of its
20334                // filter information since the amount of data will be reasonable.
20335                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20336            } else if ("check-permission".equals(cmd)) {
20337                if (opti >= args.length) {
20338                    pw.println("Error: check-permission missing permission argument");
20339                    return;
20340                }
20341                String perm = args[opti];
20342                opti++;
20343                if (opti >= args.length) {
20344                    pw.println("Error: check-permission missing package argument");
20345                    return;
20346                }
20347
20348                String pkg = args[opti];
20349                opti++;
20350                int user = UserHandle.getUserId(Binder.getCallingUid());
20351                if (opti < args.length) {
20352                    try {
20353                        user = Integer.parseInt(args[opti]);
20354                    } catch (NumberFormatException e) {
20355                        pw.println("Error: check-permission user argument is not a number: "
20356                                + args[opti]);
20357                        return;
20358                    }
20359                }
20360
20361                // Normalize package name to handle renamed packages and static libs
20362                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20363
20364                pw.println(checkPermission(perm, pkg, user));
20365                return;
20366            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20367                dumpState.setDump(DumpState.DUMP_LIBS);
20368            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20369                dumpState.setDump(DumpState.DUMP_FEATURES);
20370            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20371                if (opti >= args.length) {
20372                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20373                            | DumpState.DUMP_SERVICE_RESOLVERS
20374                            | DumpState.DUMP_RECEIVER_RESOLVERS
20375                            | DumpState.DUMP_CONTENT_RESOLVERS);
20376                } else {
20377                    while (opti < args.length) {
20378                        String name = args[opti];
20379                        if ("a".equals(name) || "activity".equals(name)) {
20380                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20381                        } else if ("s".equals(name) || "service".equals(name)) {
20382                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20383                        } else if ("r".equals(name) || "receiver".equals(name)) {
20384                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20385                        } else if ("c".equals(name) || "content".equals(name)) {
20386                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20387                        } else {
20388                            pw.println("Error: unknown resolver table type: " + name);
20389                            return;
20390                        }
20391                        opti++;
20392                    }
20393                }
20394            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20395                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20396            } else if ("permission".equals(cmd)) {
20397                if (opti >= args.length) {
20398                    pw.println("Error: permission requires permission name");
20399                    return;
20400                }
20401                permissionNames = new ArraySet<>();
20402                while (opti < args.length) {
20403                    permissionNames.add(args[opti]);
20404                    opti++;
20405                }
20406                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20407                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20408            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20409                dumpState.setDump(DumpState.DUMP_PREFERRED);
20410            } else if ("preferred-xml".equals(cmd)) {
20411                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20412                if (opti < args.length && "--full".equals(args[opti])) {
20413                    fullPreferred = true;
20414                    opti++;
20415                }
20416            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20417                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20418            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20419                dumpState.setDump(DumpState.DUMP_PACKAGES);
20420            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20421                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20422            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20423                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20424            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20425                dumpState.setDump(DumpState.DUMP_MESSAGES);
20426            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20427                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20428            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20429                    || "intent-filter-verifiers".equals(cmd)) {
20430                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20431            } else if ("version".equals(cmd)) {
20432                dumpState.setDump(DumpState.DUMP_VERSION);
20433            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20434                dumpState.setDump(DumpState.DUMP_KEYSETS);
20435            } else if ("installs".equals(cmd)) {
20436                dumpState.setDump(DumpState.DUMP_INSTALLS);
20437            } else if ("frozen".equals(cmd)) {
20438                dumpState.setDump(DumpState.DUMP_FROZEN);
20439            } else if ("volumes".equals(cmd)) {
20440                dumpState.setDump(DumpState.DUMP_VOLUMES);
20441            } else if ("dexopt".equals(cmd)) {
20442                dumpState.setDump(DumpState.DUMP_DEXOPT);
20443            } else if ("compiler-stats".equals(cmd)) {
20444                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20445            } else if ("changes".equals(cmd)) {
20446                dumpState.setDump(DumpState.DUMP_CHANGES);
20447            } else if ("write".equals(cmd)) {
20448                synchronized (mPackages) {
20449                    mSettings.writeLPr();
20450                    pw.println("Settings written.");
20451                    return;
20452                }
20453            }
20454        }
20455
20456        if (checkin) {
20457            pw.println("vers,1");
20458        }
20459
20460        // reader
20461        synchronized (mPackages) {
20462            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20463                if (!checkin) {
20464                    if (dumpState.onTitlePrinted())
20465                        pw.println();
20466                    pw.println("Database versions:");
20467                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20468                }
20469            }
20470
20471            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20472                if (!checkin) {
20473                    if (dumpState.onTitlePrinted())
20474                        pw.println();
20475                    pw.println("Verifiers:");
20476                    pw.print("  Required: ");
20477                    pw.print(mRequiredVerifierPackage);
20478                    pw.print(" (uid=");
20479                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20480                            UserHandle.USER_SYSTEM));
20481                    pw.println(")");
20482                } else if (mRequiredVerifierPackage != null) {
20483                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20484                    pw.print(",");
20485                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20486                            UserHandle.USER_SYSTEM));
20487                }
20488            }
20489
20490            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20491                    packageName == null) {
20492                if (mIntentFilterVerifierComponent != null) {
20493                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20494                    if (!checkin) {
20495                        if (dumpState.onTitlePrinted())
20496                            pw.println();
20497                        pw.println("Intent Filter Verifier:");
20498                        pw.print("  Using: ");
20499                        pw.print(verifierPackageName);
20500                        pw.print(" (uid=");
20501                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20502                                UserHandle.USER_SYSTEM));
20503                        pw.println(")");
20504                    } else if (verifierPackageName != null) {
20505                        pw.print("ifv,"); pw.print(verifierPackageName);
20506                        pw.print(",");
20507                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20508                                UserHandle.USER_SYSTEM));
20509                    }
20510                } else {
20511                    pw.println();
20512                    pw.println("No Intent Filter Verifier available!");
20513                }
20514            }
20515
20516            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20517                boolean printedHeader = false;
20518                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20519                while (it.hasNext()) {
20520                    String libName = it.next();
20521                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20522                    if (versionedLib == null) {
20523                        continue;
20524                    }
20525                    final int versionCount = versionedLib.size();
20526                    for (int i = 0; i < versionCount; i++) {
20527                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20528                        if (!checkin) {
20529                            if (!printedHeader) {
20530                                if (dumpState.onTitlePrinted())
20531                                    pw.println();
20532                                pw.println("Libraries:");
20533                                printedHeader = true;
20534                            }
20535                            pw.print("  ");
20536                        } else {
20537                            pw.print("lib,");
20538                        }
20539                        pw.print(libEntry.info.getName());
20540                        if (libEntry.info.isStatic()) {
20541                            pw.print(" version=" + libEntry.info.getVersion());
20542                        }
20543                        if (!checkin) {
20544                            pw.print(" -> ");
20545                        }
20546                        if (libEntry.path != null) {
20547                            pw.print(" (jar) ");
20548                            pw.print(libEntry.path);
20549                        } else {
20550                            pw.print(" (apk) ");
20551                            pw.print(libEntry.apk);
20552                        }
20553                        pw.println();
20554                    }
20555                }
20556            }
20557
20558            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20559                if (dumpState.onTitlePrinted())
20560                    pw.println();
20561                if (!checkin) {
20562                    pw.println("Features:");
20563                }
20564
20565                synchronized (mAvailableFeatures) {
20566                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20567                        if (checkin) {
20568                            pw.print("feat,");
20569                            pw.print(feat.name);
20570                            pw.print(",");
20571                            pw.println(feat.version);
20572                        } else {
20573                            pw.print("  ");
20574                            pw.print(feat.name);
20575                            if (feat.version > 0) {
20576                                pw.print(" version=");
20577                                pw.print(feat.version);
20578                            }
20579                            pw.println();
20580                        }
20581                    }
20582                }
20583            }
20584
20585            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20586                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20587                        : "Activity Resolver Table:", "  ", packageName,
20588                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20589                    dumpState.setTitlePrinted(true);
20590                }
20591            }
20592            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20593                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20594                        : "Receiver Resolver Table:", "  ", packageName,
20595                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20596                    dumpState.setTitlePrinted(true);
20597                }
20598            }
20599            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20600                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20601                        : "Service Resolver Table:", "  ", packageName,
20602                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20603                    dumpState.setTitlePrinted(true);
20604                }
20605            }
20606            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20607                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20608                        : "Provider Resolver Table:", "  ", packageName,
20609                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20610                    dumpState.setTitlePrinted(true);
20611                }
20612            }
20613
20614            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20615                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20616                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20617                    int user = mSettings.mPreferredActivities.keyAt(i);
20618                    if (pir.dump(pw,
20619                            dumpState.getTitlePrinted()
20620                                ? "\nPreferred Activities User " + user + ":"
20621                                : "Preferred Activities User " + user + ":", "  ",
20622                            packageName, true, false)) {
20623                        dumpState.setTitlePrinted(true);
20624                    }
20625                }
20626            }
20627
20628            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20629                pw.flush();
20630                FileOutputStream fout = new FileOutputStream(fd);
20631                BufferedOutputStream str = new BufferedOutputStream(fout);
20632                XmlSerializer serializer = new FastXmlSerializer();
20633                try {
20634                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20635                    serializer.startDocument(null, true);
20636                    serializer.setFeature(
20637                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20638                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20639                    serializer.endDocument();
20640                    serializer.flush();
20641                } catch (IllegalArgumentException e) {
20642                    pw.println("Failed writing: " + e);
20643                } catch (IllegalStateException e) {
20644                    pw.println("Failed writing: " + e);
20645                } catch (IOException e) {
20646                    pw.println("Failed writing: " + e);
20647                }
20648            }
20649
20650            if (!checkin
20651                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20652                    && packageName == null) {
20653                pw.println();
20654                int count = mSettings.mPackages.size();
20655                if (count == 0) {
20656                    pw.println("No applications!");
20657                    pw.println();
20658                } else {
20659                    final String prefix = "  ";
20660                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20661                    if (allPackageSettings.size() == 0) {
20662                        pw.println("No domain preferred apps!");
20663                        pw.println();
20664                    } else {
20665                        pw.println("App verification status:");
20666                        pw.println();
20667                        count = 0;
20668                        for (PackageSetting ps : allPackageSettings) {
20669                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20670                            if (ivi == null || ivi.getPackageName() == null) continue;
20671                            pw.println(prefix + "Package: " + ivi.getPackageName());
20672                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20673                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20674                            pw.println();
20675                            count++;
20676                        }
20677                        if (count == 0) {
20678                            pw.println(prefix + "No app verification established.");
20679                            pw.println();
20680                        }
20681                        for (int userId : sUserManager.getUserIds()) {
20682                            pw.println("App linkages for user " + userId + ":");
20683                            pw.println();
20684                            count = 0;
20685                            for (PackageSetting ps : allPackageSettings) {
20686                                final long status = ps.getDomainVerificationStatusForUser(userId);
20687                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20688                                        && !DEBUG_DOMAIN_VERIFICATION) {
20689                                    continue;
20690                                }
20691                                pw.println(prefix + "Package: " + ps.name);
20692                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20693                                String statusStr = IntentFilterVerificationInfo.
20694                                        getStatusStringFromValue(status);
20695                                pw.println(prefix + "Status:  " + statusStr);
20696                                pw.println();
20697                                count++;
20698                            }
20699                            if (count == 0) {
20700                                pw.println(prefix + "No configured app linkages.");
20701                                pw.println();
20702                            }
20703                        }
20704                    }
20705                }
20706            }
20707
20708            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20709                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20710            }
20711
20712            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20713                boolean printedSomething = false;
20714                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20715                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20716                        continue;
20717                    }
20718                    if (!printedSomething) {
20719                        if (dumpState.onTitlePrinted())
20720                            pw.println();
20721                        pw.println("Registered ContentProviders:");
20722                        printedSomething = true;
20723                    }
20724                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20725                    pw.print("    "); pw.println(p.toString());
20726                }
20727                printedSomething = false;
20728                for (Map.Entry<String, PackageParser.Provider> entry :
20729                        mProvidersByAuthority.entrySet()) {
20730                    PackageParser.Provider p = entry.getValue();
20731                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20732                        continue;
20733                    }
20734                    if (!printedSomething) {
20735                        if (dumpState.onTitlePrinted())
20736                            pw.println();
20737                        pw.println("ContentProvider Authorities:");
20738                        printedSomething = true;
20739                    }
20740                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20741                    pw.print("    "); pw.println(p.toString());
20742                    if (p.info != null && p.info.applicationInfo != null) {
20743                        final String appInfo = p.info.applicationInfo.toString();
20744                        pw.print("      applicationInfo="); pw.println(appInfo);
20745                    }
20746                }
20747            }
20748
20749            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20750                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20751            }
20752
20753            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20754                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20755            }
20756
20757            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20758                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20759            }
20760
20761            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
20762                if (dumpState.onTitlePrinted()) pw.println();
20763                pw.println("Package Changes:");
20764                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
20765                final int K = mChangedPackages.size();
20766                for (int i = 0; i < K; i++) {
20767                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
20768                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
20769                    final int N = changes.size();
20770                    if (N == 0) {
20771                        pw.print("    "); pw.println("No packages changed");
20772                    } else {
20773                        for (int j = 0; j < N; j++) {
20774                            final String pkgName = changes.valueAt(j);
20775                            final int sequenceNumber = changes.keyAt(j);
20776                            pw.print("    ");
20777                            pw.print("seq=");
20778                            pw.print(sequenceNumber);
20779                            pw.print(", package=");
20780                            pw.println(pkgName);
20781                        }
20782                    }
20783                }
20784            }
20785
20786            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20787                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20788            }
20789
20790            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20791                // XXX should handle packageName != null by dumping only install data that
20792                // the given package is involved with.
20793                if (dumpState.onTitlePrinted()) pw.println();
20794
20795                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20796                ipw.println();
20797                ipw.println("Frozen packages:");
20798                ipw.increaseIndent();
20799                if (mFrozenPackages.size() == 0) {
20800                    ipw.println("(none)");
20801                } else {
20802                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20803                        ipw.println(mFrozenPackages.valueAt(i));
20804                    }
20805                }
20806                ipw.decreaseIndent();
20807            }
20808
20809            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
20810                if (dumpState.onTitlePrinted()) pw.println();
20811
20812                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20813                ipw.println();
20814                ipw.println("Loaded volumes:");
20815                ipw.increaseIndent();
20816                if (mLoadedVolumes.size() == 0) {
20817                    ipw.println("(none)");
20818                } else {
20819                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
20820                        ipw.println(mLoadedVolumes.valueAt(i));
20821                    }
20822                }
20823                ipw.decreaseIndent();
20824            }
20825
20826            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20827                if (dumpState.onTitlePrinted()) pw.println();
20828                dumpDexoptStateLPr(pw, packageName);
20829            }
20830
20831            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20832                if (dumpState.onTitlePrinted()) pw.println();
20833                dumpCompilerStatsLPr(pw, packageName);
20834            }
20835
20836            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20837                if (dumpState.onTitlePrinted()) pw.println();
20838                mSettings.dumpReadMessagesLPr(pw, dumpState);
20839
20840                pw.println();
20841                pw.println("Package warning messages:");
20842                dumpCriticalInfo(pw, null);
20843            }
20844
20845            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20846                dumpCriticalInfo(pw, "msg,");
20847            }
20848        }
20849
20850        // PackageInstaller should be called outside of mPackages lock
20851        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20852            // XXX should handle packageName != null by dumping only install data that
20853            // the given package is involved with.
20854            if (dumpState.onTitlePrinted()) pw.println();
20855            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20856        }
20857    }
20858
20859    private void dumpProto(FileDescriptor fd) {
20860        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20861
20862        synchronized (mPackages) {
20863            final long requiredVerifierPackageToken =
20864                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20865            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20866            proto.write(
20867                    PackageServiceDumpProto.PackageShortProto.UID,
20868                    getPackageUid(
20869                            mRequiredVerifierPackage,
20870                            MATCH_DEBUG_TRIAGED_MISSING,
20871                            UserHandle.USER_SYSTEM));
20872            proto.end(requiredVerifierPackageToken);
20873
20874            if (mIntentFilterVerifierComponent != null) {
20875                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20876                final long verifierPackageToken =
20877                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20878                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20879                proto.write(
20880                        PackageServiceDumpProto.PackageShortProto.UID,
20881                        getPackageUid(
20882                                verifierPackageName,
20883                                MATCH_DEBUG_TRIAGED_MISSING,
20884                                UserHandle.USER_SYSTEM));
20885                proto.end(verifierPackageToken);
20886            }
20887
20888            dumpSharedLibrariesProto(proto);
20889            dumpFeaturesProto(proto);
20890            mSettings.dumpPackagesProto(proto);
20891            mSettings.dumpSharedUsersProto(proto);
20892            dumpCriticalInfo(proto);
20893        }
20894        proto.flush();
20895    }
20896
20897    private void dumpFeaturesProto(ProtoOutputStream proto) {
20898        synchronized (mAvailableFeatures) {
20899            final int count = mAvailableFeatures.size();
20900            for (int i = 0; i < count; i++) {
20901                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
20902            }
20903        }
20904    }
20905
20906    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20907        final int count = mSharedLibraries.size();
20908        for (int i = 0; i < count; i++) {
20909            final String libName = mSharedLibraries.keyAt(i);
20910            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20911            if (versionedLib == null) {
20912                continue;
20913            }
20914            final int versionCount = versionedLib.size();
20915            for (int j = 0; j < versionCount; j++) {
20916                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20917                final long sharedLibraryToken =
20918                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20919                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20920                final boolean isJar = (libEntry.path != null);
20921                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20922                if (isJar) {
20923                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20924                } else {
20925                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20926                }
20927                proto.end(sharedLibraryToken);
20928            }
20929        }
20930    }
20931
20932    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20933        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20934        ipw.println();
20935        ipw.println("Dexopt state:");
20936        ipw.increaseIndent();
20937        Collection<PackageParser.Package> packages = null;
20938        if (packageName != null) {
20939            PackageParser.Package targetPackage = mPackages.get(packageName);
20940            if (targetPackage != null) {
20941                packages = Collections.singletonList(targetPackage);
20942            } else {
20943                ipw.println("Unable to find package: " + packageName);
20944                return;
20945            }
20946        } else {
20947            packages = mPackages.values();
20948        }
20949
20950        for (PackageParser.Package pkg : packages) {
20951            ipw.println("[" + pkg.packageName + "]");
20952            ipw.increaseIndent();
20953            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
20954                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
20955            ipw.decreaseIndent();
20956        }
20957    }
20958
20959    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20960        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20961        ipw.println();
20962        ipw.println("Compiler stats:");
20963        ipw.increaseIndent();
20964        Collection<PackageParser.Package> packages = null;
20965        if (packageName != null) {
20966            PackageParser.Package targetPackage = mPackages.get(packageName);
20967            if (targetPackage != null) {
20968                packages = Collections.singletonList(targetPackage);
20969            } else {
20970                ipw.println("Unable to find package: " + packageName);
20971                return;
20972            }
20973        } else {
20974            packages = mPackages.values();
20975        }
20976
20977        for (PackageParser.Package pkg : packages) {
20978            ipw.println("[" + pkg.packageName + "]");
20979            ipw.increaseIndent();
20980
20981            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20982            if (stats == null) {
20983                ipw.println("(No recorded stats)");
20984            } else {
20985                stats.dump(ipw);
20986            }
20987            ipw.decreaseIndent();
20988        }
20989    }
20990
20991    private String dumpDomainString(String packageName) {
20992        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20993                .getList();
20994        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20995
20996        ArraySet<String> result = new ArraySet<>();
20997        if (iviList.size() > 0) {
20998            for (IntentFilterVerificationInfo ivi : iviList) {
20999                for (String host : ivi.getDomains()) {
21000                    result.add(host);
21001                }
21002            }
21003        }
21004        if (filters != null && filters.size() > 0) {
21005            for (IntentFilter filter : filters) {
21006                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21007                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21008                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21009                    result.addAll(filter.getHostsList());
21010                }
21011            }
21012        }
21013
21014        StringBuilder sb = new StringBuilder(result.size() * 16);
21015        for (String domain : result) {
21016            if (sb.length() > 0) sb.append(" ");
21017            sb.append(domain);
21018        }
21019        return sb.toString();
21020    }
21021
21022    // ------- apps on sdcard specific code -------
21023    static final boolean DEBUG_SD_INSTALL = false;
21024
21025    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21026
21027    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21028
21029    private boolean mMediaMounted = false;
21030
21031    static String getEncryptKey() {
21032        try {
21033            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21034                    SD_ENCRYPTION_KEYSTORE_NAME);
21035            if (sdEncKey == null) {
21036                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21037                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21038                if (sdEncKey == null) {
21039                    Slog.e(TAG, "Failed to create encryption keys");
21040                    return null;
21041                }
21042            }
21043            return sdEncKey;
21044        } catch (NoSuchAlgorithmException nsae) {
21045            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21046            return null;
21047        } catch (IOException ioe) {
21048            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21049            return null;
21050        }
21051    }
21052
21053    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21054            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21055        final int size = infos.size();
21056        final String[] packageNames = new String[size];
21057        final int[] packageUids = new int[size];
21058        for (int i = 0; i < size; i++) {
21059            final ApplicationInfo info = infos.get(i);
21060            packageNames[i] = info.packageName;
21061            packageUids[i] = info.uid;
21062        }
21063        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21064                finishedReceiver);
21065    }
21066
21067    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21068            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21069        sendResourcesChangedBroadcast(mediaStatus, replacing,
21070                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21071    }
21072
21073    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21074            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21075        int size = pkgList.length;
21076        if (size > 0) {
21077            // Send broadcasts here
21078            Bundle extras = new Bundle();
21079            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21080            if (uidArr != null) {
21081                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21082            }
21083            if (replacing) {
21084                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21085            }
21086            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21087                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21088            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21089        }
21090    }
21091
21092    private void loadPrivatePackages(final VolumeInfo vol) {
21093        mHandler.post(new Runnable() {
21094            @Override
21095            public void run() {
21096                loadPrivatePackagesInner(vol);
21097            }
21098        });
21099    }
21100
21101    private void loadPrivatePackagesInner(VolumeInfo vol) {
21102        final String volumeUuid = vol.fsUuid;
21103        if (TextUtils.isEmpty(volumeUuid)) {
21104            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21105            return;
21106        }
21107
21108        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21109        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21110        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21111
21112        final VersionInfo ver;
21113        final List<PackageSetting> packages;
21114        synchronized (mPackages) {
21115            ver = mSettings.findOrCreateVersion(volumeUuid);
21116            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21117        }
21118
21119        for (PackageSetting ps : packages) {
21120            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21121            synchronized (mInstallLock) {
21122                final PackageParser.Package pkg;
21123                try {
21124                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21125                    loaded.add(pkg.applicationInfo);
21126
21127                } catch (PackageManagerException e) {
21128                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21129                }
21130
21131                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21132                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21133                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21134                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21135                }
21136            }
21137        }
21138
21139        // Reconcile app data for all started/unlocked users
21140        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21141        final UserManager um = mContext.getSystemService(UserManager.class);
21142        UserManagerInternal umInternal = getUserManagerInternal();
21143        for (UserInfo user : um.getUsers()) {
21144            final int flags;
21145            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21146                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21147            } else if (umInternal.isUserRunning(user.id)) {
21148                flags = StorageManager.FLAG_STORAGE_DE;
21149            } else {
21150                continue;
21151            }
21152
21153            try {
21154                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21155                synchronized (mInstallLock) {
21156                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21157                }
21158            } catch (IllegalStateException e) {
21159                // Device was probably ejected, and we'll process that event momentarily
21160                Slog.w(TAG, "Failed to prepare storage: " + e);
21161            }
21162        }
21163
21164        synchronized (mPackages) {
21165            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21166            if (sdkUpdated) {
21167                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21168                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21169            }
21170            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21171                    mPermissionCallback);
21172
21173            // Yay, everything is now upgraded
21174            ver.forceCurrent();
21175
21176            mSettings.writeLPr();
21177        }
21178
21179        for (PackageFreezer freezer : freezers) {
21180            freezer.close();
21181        }
21182
21183        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21184        sendResourcesChangedBroadcast(true, false, loaded, null);
21185        mLoadedVolumes.add(vol.getId());
21186    }
21187
21188    private void unloadPrivatePackages(final VolumeInfo vol) {
21189        mHandler.post(new Runnable() {
21190            @Override
21191            public void run() {
21192                unloadPrivatePackagesInner(vol);
21193            }
21194        });
21195    }
21196
21197    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21198        final String volumeUuid = vol.fsUuid;
21199        if (TextUtils.isEmpty(volumeUuid)) {
21200            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21201            return;
21202        }
21203
21204        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21205        synchronized (mInstallLock) {
21206        synchronized (mPackages) {
21207            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21208            for (PackageSetting ps : packages) {
21209                if (ps.pkg == null) continue;
21210
21211                final ApplicationInfo info = ps.pkg.applicationInfo;
21212                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21213                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21214
21215                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21216                        "unloadPrivatePackagesInner")) {
21217                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21218                            false, null)) {
21219                        unloaded.add(info);
21220                    } else {
21221                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21222                    }
21223                }
21224
21225                // Try very hard to release any references to this package
21226                // so we don't risk the system server being killed due to
21227                // open FDs
21228                AttributeCache.instance().removePackage(ps.name);
21229            }
21230
21231            mSettings.writeLPr();
21232        }
21233        }
21234
21235        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21236        sendResourcesChangedBroadcast(false, false, unloaded, null);
21237        mLoadedVolumes.remove(vol.getId());
21238
21239        // Try very hard to release any references to this path so we don't risk
21240        // the system server being killed due to open FDs
21241        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21242
21243        for (int i = 0; i < 3; i++) {
21244            System.gc();
21245            System.runFinalization();
21246        }
21247    }
21248
21249    private void assertPackageKnown(String volumeUuid, String packageName)
21250            throws PackageManagerException {
21251        synchronized (mPackages) {
21252            // Normalize package name to handle renamed packages
21253            packageName = normalizePackageNameLPr(packageName);
21254
21255            final PackageSetting ps = mSettings.mPackages.get(packageName);
21256            if (ps == null) {
21257                throw new PackageManagerException("Package " + packageName + " is unknown");
21258            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21259                throw new PackageManagerException(
21260                        "Package " + packageName + " found on unknown volume " + volumeUuid
21261                                + "; expected volume " + ps.volumeUuid);
21262            }
21263        }
21264    }
21265
21266    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21267            throws PackageManagerException {
21268        synchronized (mPackages) {
21269            // Normalize package name to handle renamed packages
21270            packageName = normalizePackageNameLPr(packageName);
21271
21272            final PackageSetting ps = mSettings.mPackages.get(packageName);
21273            if (ps == null) {
21274                throw new PackageManagerException("Package " + packageName + " is unknown");
21275            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21276                throw new PackageManagerException(
21277                        "Package " + packageName + " found on unknown volume " + volumeUuid
21278                                + "; expected volume " + ps.volumeUuid);
21279            } else if (!ps.getInstalled(userId)) {
21280                throw new PackageManagerException(
21281                        "Package " + packageName + " not installed for user " + userId);
21282            }
21283        }
21284    }
21285
21286    private List<String> collectAbsoluteCodePaths() {
21287        synchronized (mPackages) {
21288            List<String> codePaths = new ArrayList<>();
21289            final int packageCount = mSettings.mPackages.size();
21290            for (int i = 0; i < packageCount; i++) {
21291                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21292                codePaths.add(ps.codePath.getAbsolutePath());
21293            }
21294            return codePaths;
21295        }
21296    }
21297
21298    /**
21299     * Examine all apps present on given mounted volume, and destroy apps that
21300     * aren't expected, either due to uninstallation or reinstallation on
21301     * another volume.
21302     */
21303    private void reconcileApps(String volumeUuid) {
21304        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21305        List<File> filesToDelete = null;
21306
21307        final File[] files = FileUtils.listFilesOrEmpty(
21308                Environment.getDataAppDirectory(volumeUuid));
21309        for (File file : files) {
21310            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21311                    && !PackageInstallerService.isStageName(file.getName());
21312            if (!isPackage) {
21313                // Ignore entries which are not packages
21314                continue;
21315            }
21316
21317            String absolutePath = file.getAbsolutePath();
21318
21319            boolean pathValid = false;
21320            final int absoluteCodePathCount = absoluteCodePaths.size();
21321            for (int i = 0; i < absoluteCodePathCount; i++) {
21322                String absoluteCodePath = absoluteCodePaths.get(i);
21323                if (absolutePath.startsWith(absoluteCodePath)) {
21324                    pathValid = true;
21325                    break;
21326                }
21327            }
21328
21329            if (!pathValid) {
21330                if (filesToDelete == null) {
21331                    filesToDelete = new ArrayList<>();
21332                }
21333                filesToDelete.add(file);
21334            }
21335        }
21336
21337        if (filesToDelete != null) {
21338            final int fileToDeleteCount = filesToDelete.size();
21339            for (int i = 0; i < fileToDeleteCount; i++) {
21340                File fileToDelete = filesToDelete.get(i);
21341                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21342                synchronized (mInstallLock) {
21343                    removeCodePathLI(fileToDelete);
21344                }
21345            }
21346        }
21347    }
21348
21349    /**
21350     * Reconcile all app data for the given user.
21351     * <p>
21352     * Verifies that directories exist and that ownership and labeling is
21353     * correct for all installed apps on all mounted volumes.
21354     */
21355    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21356        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21357        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21358            final String volumeUuid = vol.getFsUuid();
21359            synchronized (mInstallLock) {
21360                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21361            }
21362        }
21363    }
21364
21365    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21366            boolean migrateAppData) {
21367        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21368    }
21369
21370    /**
21371     * Reconcile all app data on given mounted volume.
21372     * <p>
21373     * Destroys app data that isn't expected, either due to uninstallation or
21374     * reinstallation on another volume.
21375     * <p>
21376     * Verifies that directories exist and that ownership and labeling is
21377     * correct for all installed apps.
21378     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21379     */
21380    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21381            boolean migrateAppData, boolean onlyCoreApps) {
21382        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21383                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21384        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21385
21386        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21387        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21388
21389        // First look for stale data that doesn't belong, and check if things
21390        // have changed since we did our last restorecon
21391        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21392            if (StorageManager.isFileEncryptedNativeOrEmulated()
21393                    && !StorageManager.isUserKeyUnlocked(userId)) {
21394                throw new RuntimeException(
21395                        "Yikes, someone asked us to reconcile CE storage while " + userId
21396                                + " was still locked; this would have caused massive data loss!");
21397            }
21398
21399            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21400            for (File file : files) {
21401                final String packageName = file.getName();
21402                try {
21403                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21404                } catch (PackageManagerException e) {
21405                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21406                    try {
21407                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21408                                StorageManager.FLAG_STORAGE_CE, 0);
21409                    } catch (InstallerException e2) {
21410                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21411                    }
21412                }
21413            }
21414        }
21415        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21416            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21417            for (File file : files) {
21418                final String packageName = file.getName();
21419                try {
21420                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21421                } catch (PackageManagerException e) {
21422                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21423                    try {
21424                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21425                                StorageManager.FLAG_STORAGE_DE, 0);
21426                    } catch (InstallerException e2) {
21427                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21428                    }
21429                }
21430            }
21431        }
21432
21433        // Ensure that data directories are ready to roll for all packages
21434        // installed for this volume and user
21435        final List<PackageSetting> packages;
21436        synchronized (mPackages) {
21437            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21438        }
21439        int preparedCount = 0;
21440        for (PackageSetting ps : packages) {
21441            final String packageName = ps.name;
21442            if (ps.pkg == null) {
21443                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21444                // TODO: might be due to legacy ASEC apps; we should circle back
21445                // and reconcile again once they're scanned
21446                continue;
21447            }
21448            // Skip non-core apps if requested
21449            if (onlyCoreApps && !ps.pkg.coreApp) {
21450                result.add(packageName);
21451                continue;
21452            }
21453
21454            if (ps.getInstalled(userId)) {
21455                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21456                preparedCount++;
21457            }
21458        }
21459
21460        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21461        return result;
21462    }
21463
21464    /**
21465     * Prepare app data for the given app just after it was installed or
21466     * upgraded. This method carefully only touches users that it's installed
21467     * for, and it forces a restorecon to handle any seinfo changes.
21468     * <p>
21469     * Verifies that directories exist and that ownership and labeling is
21470     * correct for all installed apps. If there is an ownership mismatch, it
21471     * will try recovering system apps by wiping data; third-party app data is
21472     * left intact.
21473     * <p>
21474     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21475     */
21476    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21477        final PackageSetting ps;
21478        synchronized (mPackages) {
21479            ps = mSettings.mPackages.get(pkg.packageName);
21480            mSettings.writeKernelMappingLPr(ps);
21481        }
21482
21483        final UserManager um = mContext.getSystemService(UserManager.class);
21484        UserManagerInternal umInternal = getUserManagerInternal();
21485        for (UserInfo user : um.getUsers()) {
21486            final int flags;
21487            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21488                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21489            } else if (umInternal.isUserRunning(user.id)) {
21490                flags = StorageManager.FLAG_STORAGE_DE;
21491            } else {
21492                continue;
21493            }
21494
21495            if (ps.getInstalled(user.id)) {
21496                // TODO: when user data is locked, mark that we're still dirty
21497                prepareAppDataLIF(pkg, user.id, flags);
21498            }
21499        }
21500    }
21501
21502    /**
21503     * Prepare app data for the given app.
21504     * <p>
21505     * Verifies that directories exist and that ownership and labeling is
21506     * correct for all installed apps. If there is an ownership mismatch, this
21507     * will try recovering system apps by wiping data; third-party app data is
21508     * left intact.
21509     */
21510    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21511        if (pkg == null) {
21512            Slog.wtf(TAG, "Package was null!", new Throwable());
21513            return;
21514        }
21515        prepareAppDataLeafLIF(pkg, userId, flags);
21516        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21517        for (int i = 0; i < childCount; i++) {
21518            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21519        }
21520    }
21521
21522    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21523            boolean maybeMigrateAppData) {
21524        prepareAppDataLIF(pkg, userId, flags);
21525
21526        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21527            // We may have just shuffled around app data directories, so
21528            // prepare them one more time
21529            prepareAppDataLIF(pkg, userId, flags);
21530        }
21531    }
21532
21533    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21534        if (DEBUG_APP_DATA) {
21535            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21536                    + Integer.toHexString(flags));
21537        }
21538
21539        final String volumeUuid = pkg.volumeUuid;
21540        final String packageName = pkg.packageName;
21541        final ApplicationInfo app = pkg.applicationInfo;
21542        final int appId = UserHandle.getAppId(app.uid);
21543
21544        Preconditions.checkNotNull(app.seInfo);
21545
21546        long ceDataInode = -1;
21547        try {
21548            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21549                    appId, app.seInfo, app.targetSdkVersion);
21550        } catch (InstallerException e) {
21551            if (app.isSystemApp()) {
21552                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21553                        + ", but trying to recover: " + e);
21554                destroyAppDataLeafLIF(pkg, userId, flags);
21555                try {
21556                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21557                            appId, app.seInfo, app.targetSdkVersion);
21558                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21559                } catch (InstallerException e2) {
21560                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21561                }
21562            } else {
21563                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21564            }
21565        }
21566
21567        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21568            // TODO: mark this structure as dirty so we persist it!
21569            synchronized (mPackages) {
21570                final PackageSetting ps = mSettings.mPackages.get(packageName);
21571                if (ps != null) {
21572                    ps.setCeDataInode(ceDataInode, userId);
21573                }
21574            }
21575        }
21576
21577        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21578    }
21579
21580    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21581        if (pkg == null) {
21582            Slog.wtf(TAG, "Package was null!", new Throwable());
21583            return;
21584        }
21585        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21586        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21587        for (int i = 0; i < childCount; i++) {
21588            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21589        }
21590    }
21591
21592    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21593        final String volumeUuid = pkg.volumeUuid;
21594        final String packageName = pkg.packageName;
21595        final ApplicationInfo app = pkg.applicationInfo;
21596
21597        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21598            // Create a native library symlink only if we have native libraries
21599            // and if the native libraries are 32 bit libraries. We do not provide
21600            // this symlink for 64 bit libraries.
21601            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21602                final String nativeLibPath = app.nativeLibraryDir;
21603                try {
21604                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21605                            nativeLibPath, userId);
21606                } catch (InstallerException e) {
21607                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21608                }
21609            }
21610        }
21611    }
21612
21613    /**
21614     * For system apps on non-FBE devices, this method migrates any existing
21615     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21616     * requested by the app.
21617     */
21618    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21619        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21620                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21621            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21622                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21623            try {
21624                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21625                        storageTarget);
21626            } catch (InstallerException e) {
21627                logCriticalInfo(Log.WARN,
21628                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21629            }
21630            return true;
21631        } else {
21632            return false;
21633        }
21634    }
21635
21636    public PackageFreezer freezePackage(String packageName, String killReason) {
21637        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21638    }
21639
21640    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21641        return new PackageFreezer(packageName, userId, killReason);
21642    }
21643
21644    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21645            String killReason) {
21646        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21647    }
21648
21649    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21650            String killReason) {
21651        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21652            return new PackageFreezer();
21653        } else {
21654            return freezePackage(packageName, userId, killReason);
21655        }
21656    }
21657
21658    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21659            String killReason) {
21660        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21661    }
21662
21663    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21664            String killReason) {
21665        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21666            return new PackageFreezer();
21667        } else {
21668            return freezePackage(packageName, userId, killReason);
21669        }
21670    }
21671
21672    /**
21673     * Class that freezes and kills the given package upon creation, and
21674     * unfreezes it upon closing. This is typically used when doing surgery on
21675     * app code/data to prevent the app from running while you're working.
21676     */
21677    private class PackageFreezer implements AutoCloseable {
21678        private final String mPackageName;
21679        private final PackageFreezer[] mChildren;
21680
21681        private final boolean mWeFroze;
21682
21683        private final AtomicBoolean mClosed = new AtomicBoolean();
21684        private final CloseGuard mCloseGuard = CloseGuard.get();
21685
21686        /**
21687         * Create and return a stub freezer that doesn't actually do anything,
21688         * typically used when someone requested
21689         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21690         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21691         */
21692        public PackageFreezer() {
21693            mPackageName = null;
21694            mChildren = null;
21695            mWeFroze = false;
21696            mCloseGuard.open("close");
21697        }
21698
21699        public PackageFreezer(String packageName, int userId, String killReason) {
21700            synchronized (mPackages) {
21701                mPackageName = packageName;
21702                mWeFroze = mFrozenPackages.add(mPackageName);
21703
21704                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21705                if (ps != null) {
21706                    killApplication(ps.name, ps.appId, userId, killReason);
21707                }
21708
21709                final PackageParser.Package p = mPackages.get(packageName);
21710                if (p != null && p.childPackages != null) {
21711                    final int N = p.childPackages.size();
21712                    mChildren = new PackageFreezer[N];
21713                    for (int i = 0; i < N; i++) {
21714                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21715                                userId, killReason);
21716                    }
21717                } else {
21718                    mChildren = null;
21719                }
21720            }
21721            mCloseGuard.open("close");
21722        }
21723
21724        @Override
21725        protected void finalize() throws Throwable {
21726            try {
21727                if (mCloseGuard != null) {
21728                    mCloseGuard.warnIfOpen();
21729                }
21730
21731                close();
21732            } finally {
21733                super.finalize();
21734            }
21735        }
21736
21737        @Override
21738        public void close() {
21739            mCloseGuard.close();
21740            if (mClosed.compareAndSet(false, true)) {
21741                synchronized (mPackages) {
21742                    if (mWeFroze) {
21743                        mFrozenPackages.remove(mPackageName);
21744                    }
21745
21746                    if (mChildren != null) {
21747                        for (PackageFreezer freezer : mChildren) {
21748                            freezer.close();
21749                        }
21750                    }
21751                }
21752            }
21753        }
21754    }
21755
21756    /**
21757     * Verify that given package is currently frozen.
21758     */
21759    private void checkPackageFrozen(String packageName) {
21760        synchronized (mPackages) {
21761            if (!mFrozenPackages.contains(packageName)) {
21762                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21763            }
21764        }
21765    }
21766
21767    @Override
21768    public int movePackage(final String packageName, final String volumeUuid) {
21769        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21770
21771        final int callingUid = Binder.getCallingUid();
21772        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
21773        final int moveId = mNextMoveId.getAndIncrement();
21774        mHandler.post(new Runnable() {
21775            @Override
21776            public void run() {
21777                try {
21778                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
21779                } catch (PackageManagerException e) {
21780                    Slog.w(TAG, "Failed to move " + packageName, e);
21781                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
21782                }
21783            }
21784        });
21785        return moveId;
21786    }
21787
21788    private void movePackageInternal(final String packageName, final String volumeUuid,
21789            final int moveId, final int callingUid, UserHandle user)
21790                    throws PackageManagerException {
21791        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21792        final PackageManager pm = mContext.getPackageManager();
21793
21794        final boolean currentAsec;
21795        final String currentVolumeUuid;
21796        final File codeFile;
21797        final String installerPackageName;
21798        final String packageAbiOverride;
21799        final int appId;
21800        final String seinfo;
21801        final String label;
21802        final int targetSdkVersion;
21803        final PackageFreezer freezer;
21804        final int[] installedUserIds;
21805
21806        // reader
21807        synchronized (mPackages) {
21808            final PackageParser.Package pkg = mPackages.get(packageName);
21809            final PackageSetting ps = mSettings.mPackages.get(packageName);
21810            if (pkg == null
21811                    || ps == null
21812                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
21813                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21814            }
21815            if (pkg.applicationInfo.isSystemApp()) {
21816                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21817                        "Cannot move system application");
21818            }
21819
21820            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21821            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21822                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21823            if (isInternalStorage && !allow3rdPartyOnInternal) {
21824                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21825                        "3rd party apps are not allowed on internal storage");
21826            }
21827
21828            if (pkg.applicationInfo.isExternalAsec()) {
21829                currentAsec = true;
21830                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21831            } else if (pkg.applicationInfo.isForwardLocked()) {
21832                currentAsec = true;
21833                currentVolumeUuid = "forward_locked";
21834            } else {
21835                currentAsec = false;
21836                currentVolumeUuid = ps.volumeUuid;
21837
21838                final File probe = new File(pkg.codePath);
21839                final File probeOat = new File(probe, "oat");
21840                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21841                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21842                            "Move only supported for modern cluster style installs");
21843                }
21844            }
21845
21846            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21847                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21848                        "Package already moved to " + volumeUuid);
21849            }
21850            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21851                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21852                        "Device admin cannot be moved");
21853            }
21854
21855            if (mFrozenPackages.contains(packageName)) {
21856                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21857                        "Failed to move already frozen package");
21858            }
21859
21860            codeFile = new File(pkg.codePath);
21861            installerPackageName = ps.installerPackageName;
21862            packageAbiOverride = ps.cpuAbiOverrideString;
21863            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21864            seinfo = pkg.applicationInfo.seInfo;
21865            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21866            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21867            freezer = freezePackage(packageName, "movePackageInternal");
21868            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21869        }
21870
21871        final Bundle extras = new Bundle();
21872        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21873        extras.putString(Intent.EXTRA_TITLE, label);
21874        mMoveCallbacks.notifyCreated(moveId, extras);
21875
21876        int installFlags;
21877        final boolean moveCompleteApp;
21878        final File measurePath;
21879
21880        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21881            installFlags = INSTALL_INTERNAL;
21882            moveCompleteApp = !currentAsec;
21883            measurePath = Environment.getDataAppDirectory(volumeUuid);
21884        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21885            installFlags = INSTALL_EXTERNAL;
21886            moveCompleteApp = false;
21887            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21888        } else {
21889            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21890            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21891                    || !volume.isMountedWritable()) {
21892                freezer.close();
21893                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21894                        "Move location not mounted private volume");
21895            }
21896
21897            Preconditions.checkState(!currentAsec);
21898
21899            installFlags = INSTALL_INTERNAL;
21900            moveCompleteApp = true;
21901            measurePath = Environment.getDataAppDirectory(volumeUuid);
21902        }
21903
21904        // If we're moving app data around, we need all the users unlocked
21905        if (moveCompleteApp) {
21906            for (int userId : installedUserIds) {
21907                if (StorageManager.isFileEncryptedNativeOrEmulated()
21908                        && !StorageManager.isUserKeyUnlocked(userId)) {
21909                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
21910                            "User " + userId + " must be unlocked");
21911                }
21912            }
21913        }
21914
21915        final PackageStats stats = new PackageStats(null, -1);
21916        synchronized (mInstaller) {
21917            for (int userId : installedUserIds) {
21918                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21919                    freezer.close();
21920                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21921                            "Failed to measure package size");
21922                }
21923            }
21924        }
21925
21926        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21927                + stats.dataSize);
21928
21929        final long startFreeBytes = measurePath.getUsableSpace();
21930        final long sizeBytes;
21931        if (moveCompleteApp) {
21932            sizeBytes = stats.codeSize + stats.dataSize;
21933        } else {
21934            sizeBytes = stats.codeSize;
21935        }
21936
21937        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21938            freezer.close();
21939            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21940                    "Not enough free space to move");
21941        }
21942
21943        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21944
21945        final CountDownLatch installedLatch = new CountDownLatch(1);
21946        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21947            @Override
21948            public void onUserActionRequired(Intent intent) throws RemoteException {
21949                throw new IllegalStateException();
21950            }
21951
21952            @Override
21953            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21954                    Bundle extras) throws RemoteException {
21955                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21956                        + PackageManager.installStatusToString(returnCode, msg));
21957
21958                installedLatch.countDown();
21959                freezer.close();
21960
21961                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21962                switch (status) {
21963                    case PackageInstaller.STATUS_SUCCESS:
21964                        mMoveCallbacks.notifyStatusChanged(moveId,
21965                                PackageManager.MOVE_SUCCEEDED);
21966                        break;
21967                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21968                        mMoveCallbacks.notifyStatusChanged(moveId,
21969                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21970                        break;
21971                    default:
21972                        mMoveCallbacks.notifyStatusChanged(moveId,
21973                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21974                        break;
21975                }
21976            }
21977        };
21978
21979        final MoveInfo move;
21980        if (moveCompleteApp) {
21981            // Kick off a thread to report progress estimates
21982            new Thread() {
21983                @Override
21984                public void run() {
21985                    while (true) {
21986                        try {
21987                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21988                                break;
21989                            }
21990                        } catch (InterruptedException ignored) {
21991                        }
21992
21993                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
21994                        final int progress = 10 + (int) MathUtils.constrain(
21995                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21996                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21997                    }
21998                }
21999            }.start();
22000
22001            final String dataAppName = codeFile.getName();
22002            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22003                    dataAppName, appId, seinfo, targetSdkVersion);
22004        } else {
22005            move = null;
22006        }
22007
22008        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22009
22010        final Message msg = mHandler.obtainMessage(INIT_COPY);
22011        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22012        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22013                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22014                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22015                PackageManager.INSTALL_REASON_UNKNOWN);
22016        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22017        msg.obj = params;
22018
22019        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22020                System.identityHashCode(msg.obj));
22021        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22022                System.identityHashCode(msg.obj));
22023
22024        mHandler.sendMessage(msg);
22025    }
22026
22027    @Override
22028    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22029        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22030
22031        final int realMoveId = mNextMoveId.getAndIncrement();
22032        final Bundle extras = new Bundle();
22033        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22034        mMoveCallbacks.notifyCreated(realMoveId, extras);
22035
22036        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22037            @Override
22038            public void onCreated(int moveId, Bundle extras) {
22039                // Ignored
22040            }
22041
22042            @Override
22043            public void onStatusChanged(int moveId, int status, long estMillis) {
22044                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22045            }
22046        };
22047
22048        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22049        storage.setPrimaryStorageUuid(volumeUuid, callback);
22050        return realMoveId;
22051    }
22052
22053    @Override
22054    public int getMoveStatus(int moveId) {
22055        mContext.enforceCallingOrSelfPermission(
22056                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22057        return mMoveCallbacks.mLastStatus.get(moveId);
22058    }
22059
22060    @Override
22061    public void registerMoveCallback(IPackageMoveObserver callback) {
22062        mContext.enforceCallingOrSelfPermission(
22063                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22064        mMoveCallbacks.register(callback);
22065    }
22066
22067    @Override
22068    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22069        mContext.enforceCallingOrSelfPermission(
22070                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22071        mMoveCallbacks.unregister(callback);
22072    }
22073
22074    @Override
22075    public boolean setInstallLocation(int loc) {
22076        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22077                null);
22078        if (getInstallLocation() == loc) {
22079            return true;
22080        }
22081        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22082                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22083            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22084                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22085            return true;
22086        }
22087        return false;
22088   }
22089
22090    @Override
22091    public int getInstallLocation() {
22092        // allow instant app access
22093        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22094                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22095                PackageHelper.APP_INSTALL_AUTO);
22096    }
22097
22098    /** Called by UserManagerService */
22099    void cleanUpUser(UserManagerService userManager, int userHandle) {
22100        synchronized (mPackages) {
22101            mDirtyUsers.remove(userHandle);
22102            mUserNeedsBadging.delete(userHandle);
22103            mSettings.removeUserLPw(userHandle);
22104            mPendingBroadcasts.remove(userHandle);
22105            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22106            removeUnusedPackagesLPw(userManager, userHandle);
22107        }
22108    }
22109
22110    /**
22111     * We're removing userHandle and would like to remove any downloaded packages
22112     * that are no longer in use by any other user.
22113     * @param userHandle the user being removed
22114     */
22115    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22116        final boolean DEBUG_CLEAN_APKS = false;
22117        int [] users = userManager.getUserIds();
22118        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22119        while (psit.hasNext()) {
22120            PackageSetting ps = psit.next();
22121            if (ps.pkg == null) {
22122                continue;
22123            }
22124            final String packageName = ps.pkg.packageName;
22125            // Skip over if system app
22126            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22127                continue;
22128            }
22129            if (DEBUG_CLEAN_APKS) {
22130                Slog.i(TAG, "Checking package " + packageName);
22131            }
22132            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22133            if (keep) {
22134                if (DEBUG_CLEAN_APKS) {
22135                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22136                }
22137            } else {
22138                for (int i = 0; i < users.length; i++) {
22139                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22140                        keep = true;
22141                        if (DEBUG_CLEAN_APKS) {
22142                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22143                                    + users[i]);
22144                        }
22145                        break;
22146                    }
22147                }
22148            }
22149            if (!keep) {
22150                if (DEBUG_CLEAN_APKS) {
22151                    Slog.i(TAG, "  Removing package " + packageName);
22152                }
22153                mHandler.post(new Runnable() {
22154                    public void run() {
22155                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22156                                userHandle, 0);
22157                    } //end run
22158                });
22159            }
22160        }
22161    }
22162
22163    /** Called by UserManagerService */
22164    void createNewUser(int userId, String[] disallowedPackages) {
22165        synchronized (mInstallLock) {
22166            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22167        }
22168        synchronized (mPackages) {
22169            scheduleWritePackageRestrictionsLocked(userId);
22170            scheduleWritePackageListLocked(userId);
22171            applyFactoryDefaultBrowserLPw(userId);
22172            primeDomainVerificationsLPw(userId);
22173        }
22174    }
22175
22176    void onNewUserCreated(final int userId) {
22177        synchronized(mPackages) {
22178            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
22179            // If permission review for legacy apps is required, we represent
22180            // dagerous permissions for such apps as always granted runtime
22181            // permissions to keep per user flag state whether review is needed.
22182            // Hence, if a new user is added we have to propagate dangerous
22183            // permission grants for these legacy apps.
22184            if (mSettings.mPermissions.mPermissionReviewRequired) {
22185// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22186                mPermissionManager.updateAllPermissions(
22187                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22188                        mPermissionCallback);
22189            }
22190        }
22191    }
22192
22193    @Override
22194    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22195        mContext.enforceCallingOrSelfPermission(
22196                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22197                "Only package verification agents can read the verifier device identity");
22198
22199        synchronized (mPackages) {
22200            return mSettings.getVerifierDeviceIdentityLPw();
22201        }
22202    }
22203
22204    @Override
22205    public void setPermissionEnforced(String permission, boolean enforced) {
22206        // TODO: Now that we no longer change GID for storage, this should to away.
22207        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22208                "setPermissionEnforced");
22209        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22210            synchronized (mPackages) {
22211                if (mSettings.mReadExternalStorageEnforced == null
22212                        || mSettings.mReadExternalStorageEnforced != enforced) {
22213                    mSettings.mReadExternalStorageEnforced =
22214                            enforced ? Boolean.TRUE : Boolean.FALSE;
22215                    mSettings.writeLPr();
22216                }
22217            }
22218            // kill any non-foreground processes so we restart them and
22219            // grant/revoke the GID.
22220            final IActivityManager am = ActivityManager.getService();
22221            if (am != null) {
22222                final long token = Binder.clearCallingIdentity();
22223                try {
22224                    am.killProcessesBelowForeground("setPermissionEnforcement");
22225                } catch (RemoteException e) {
22226                } finally {
22227                    Binder.restoreCallingIdentity(token);
22228                }
22229            }
22230        } else {
22231            throw new IllegalArgumentException("No selective enforcement for " + permission);
22232        }
22233    }
22234
22235    @Override
22236    @Deprecated
22237    public boolean isPermissionEnforced(String permission) {
22238        // allow instant applications
22239        return true;
22240    }
22241
22242    @Override
22243    public boolean isStorageLow() {
22244        // allow instant applications
22245        final long token = Binder.clearCallingIdentity();
22246        try {
22247            final DeviceStorageMonitorInternal
22248                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22249            if (dsm != null) {
22250                return dsm.isMemoryLow();
22251            } else {
22252                return false;
22253            }
22254        } finally {
22255            Binder.restoreCallingIdentity(token);
22256        }
22257    }
22258
22259    @Override
22260    public IPackageInstaller getPackageInstaller() {
22261        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22262            return null;
22263        }
22264        return mInstallerService;
22265    }
22266
22267    @Override
22268    public IArtManager getArtManager() {
22269        return mArtManagerService;
22270    }
22271
22272    private boolean userNeedsBadging(int userId) {
22273        int index = mUserNeedsBadging.indexOfKey(userId);
22274        if (index < 0) {
22275            final UserInfo userInfo;
22276            final long token = Binder.clearCallingIdentity();
22277            try {
22278                userInfo = sUserManager.getUserInfo(userId);
22279            } finally {
22280                Binder.restoreCallingIdentity(token);
22281            }
22282            final boolean b;
22283            if (userInfo != null && userInfo.isManagedProfile()) {
22284                b = true;
22285            } else {
22286                b = false;
22287            }
22288            mUserNeedsBadging.put(userId, b);
22289            return b;
22290        }
22291        return mUserNeedsBadging.valueAt(index);
22292    }
22293
22294    @Override
22295    public KeySet getKeySetByAlias(String packageName, String alias) {
22296        if (packageName == null || alias == null) {
22297            return null;
22298        }
22299        synchronized(mPackages) {
22300            final PackageParser.Package pkg = mPackages.get(packageName);
22301            if (pkg == null) {
22302                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22303                throw new IllegalArgumentException("Unknown package: " + packageName);
22304            }
22305            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22306            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22307                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22308                throw new IllegalArgumentException("Unknown package: " + packageName);
22309            }
22310            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22311            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22312        }
22313    }
22314
22315    @Override
22316    public KeySet getSigningKeySet(String packageName) {
22317        if (packageName == null) {
22318            return null;
22319        }
22320        synchronized(mPackages) {
22321            final int callingUid = Binder.getCallingUid();
22322            final int callingUserId = UserHandle.getUserId(callingUid);
22323            final PackageParser.Package pkg = mPackages.get(packageName);
22324            if (pkg == null) {
22325                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22326                throw new IllegalArgumentException("Unknown package: " + packageName);
22327            }
22328            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22329            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22330                // filter and pretend the package doesn't exist
22331                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22332                        + ", uid:" + callingUid);
22333                throw new IllegalArgumentException("Unknown package: " + packageName);
22334            }
22335            if (pkg.applicationInfo.uid != callingUid
22336                    && Process.SYSTEM_UID != callingUid) {
22337                throw new SecurityException("May not access signing KeySet of other apps.");
22338            }
22339            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22340            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22341        }
22342    }
22343
22344    @Override
22345    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22346        final int callingUid = Binder.getCallingUid();
22347        if (getInstantAppPackageName(callingUid) != null) {
22348            return false;
22349        }
22350        if (packageName == null || ks == null) {
22351            return false;
22352        }
22353        synchronized(mPackages) {
22354            final PackageParser.Package pkg = mPackages.get(packageName);
22355            if (pkg == null
22356                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22357                            UserHandle.getUserId(callingUid))) {
22358                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22359                throw new IllegalArgumentException("Unknown package: " + packageName);
22360            }
22361            IBinder ksh = ks.getToken();
22362            if (ksh instanceof KeySetHandle) {
22363                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22364                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22365            }
22366            return false;
22367        }
22368    }
22369
22370    @Override
22371    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22372        final int callingUid = Binder.getCallingUid();
22373        if (getInstantAppPackageName(callingUid) != null) {
22374            return false;
22375        }
22376        if (packageName == null || ks == null) {
22377            return false;
22378        }
22379        synchronized(mPackages) {
22380            final PackageParser.Package pkg = mPackages.get(packageName);
22381            if (pkg == null
22382                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22383                            UserHandle.getUserId(callingUid))) {
22384                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22385                throw new IllegalArgumentException("Unknown package: " + packageName);
22386            }
22387            IBinder ksh = ks.getToken();
22388            if (ksh instanceof KeySetHandle) {
22389                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22390                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22391            }
22392            return false;
22393        }
22394    }
22395
22396    private void deletePackageIfUnusedLPr(final String packageName) {
22397        PackageSetting ps = mSettings.mPackages.get(packageName);
22398        if (ps == null) {
22399            return;
22400        }
22401        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22402            // TODO Implement atomic delete if package is unused
22403            // It is currently possible that the package will be deleted even if it is installed
22404            // after this method returns.
22405            mHandler.post(new Runnable() {
22406                public void run() {
22407                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22408                            0, PackageManager.DELETE_ALL_USERS);
22409                }
22410            });
22411        }
22412    }
22413
22414    /**
22415     * Check and throw if the given before/after packages would be considered a
22416     * downgrade.
22417     */
22418    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22419            throws PackageManagerException {
22420        if (after.versionCode < before.mVersionCode) {
22421            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22422                    "Update version code " + after.versionCode + " is older than current "
22423                    + before.mVersionCode);
22424        } else if (after.versionCode == before.mVersionCode) {
22425            if (after.baseRevisionCode < before.baseRevisionCode) {
22426                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22427                        "Update base revision code " + after.baseRevisionCode
22428                        + " is older than current " + before.baseRevisionCode);
22429            }
22430
22431            if (!ArrayUtils.isEmpty(after.splitNames)) {
22432                for (int i = 0; i < after.splitNames.length; i++) {
22433                    final String splitName = after.splitNames[i];
22434                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22435                    if (j != -1) {
22436                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22437                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22438                                    "Update split " + splitName + " revision code "
22439                                    + after.splitRevisionCodes[i] + " is older than current "
22440                                    + before.splitRevisionCodes[j]);
22441                        }
22442                    }
22443                }
22444            }
22445        }
22446    }
22447
22448    private static class MoveCallbacks extends Handler {
22449        private static final int MSG_CREATED = 1;
22450        private static final int MSG_STATUS_CHANGED = 2;
22451
22452        private final RemoteCallbackList<IPackageMoveObserver>
22453                mCallbacks = new RemoteCallbackList<>();
22454
22455        private final SparseIntArray mLastStatus = new SparseIntArray();
22456
22457        public MoveCallbacks(Looper looper) {
22458            super(looper);
22459        }
22460
22461        public void register(IPackageMoveObserver callback) {
22462            mCallbacks.register(callback);
22463        }
22464
22465        public void unregister(IPackageMoveObserver callback) {
22466            mCallbacks.unregister(callback);
22467        }
22468
22469        @Override
22470        public void handleMessage(Message msg) {
22471            final SomeArgs args = (SomeArgs) msg.obj;
22472            final int n = mCallbacks.beginBroadcast();
22473            for (int i = 0; i < n; i++) {
22474                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22475                try {
22476                    invokeCallback(callback, msg.what, args);
22477                } catch (RemoteException ignored) {
22478                }
22479            }
22480            mCallbacks.finishBroadcast();
22481            args.recycle();
22482        }
22483
22484        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22485                throws RemoteException {
22486            switch (what) {
22487                case MSG_CREATED: {
22488                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22489                    break;
22490                }
22491                case MSG_STATUS_CHANGED: {
22492                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22493                    break;
22494                }
22495            }
22496        }
22497
22498        private void notifyCreated(int moveId, Bundle extras) {
22499            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22500
22501            final SomeArgs args = SomeArgs.obtain();
22502            args.argi1 = moveId;
22503            args.arg2 = extras;
22504            obtainMessage(MSG_CREATED, args).sendToTarget();
22505        }
22506
22507        private void notifyStatusChanged(int moveId, int status) {
22508            notifyStatusChanged(moveId, status, -1);
22509        }
22510
22511        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22512            Slog.v(TAG, "Move " + moveId + " status " + status);
22513
22514            final SomeArgs args = SomeArgs.obtain();
22515            args.argi1 = moveId;
22516            args.argi2 = status;
22517            args.arg3 = estMillis;
22518            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22519
22520            synchronized (mLastStatus) {
22521                mLastStatus.put(moveId, status);
22522            }
22523        }
22524    }
22525
22526    private final static class OnPermissionChangeListeners extends Handler {
22527        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22528
22529        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22530                new RemoteCallbackList<>();
22531
22532        public OnPermissionChangeListeners(Looper looper) {
22533            super(looper);
22534        }
22535
22536        @Override
22537        public void handleMessage(Message msg) {
22538            switch (msg.what) {
22539                case MSG_ON_PERMISSIONS_CHANGED: {
22540                    final int uid = msg.arg1;
22541                    handleOnPermissionsChanged(uid);
22542                } break;
22543            }
22544        }
22545
22546        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22547            mPermissionListeners.register(listener);
22548
22549        }
22550
22551        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22552            mPermissionListeners.unregister(listener);
22553        }
22554
22555        public void onPermissionsChanged(int uid) {
22556            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22557                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22558            }
22559        }
22560
22561        private void handleOnPermissionsChanged(int uid) {
22562            final int count = mPermissionListeners.beginBroadcast();
22563            try {
22564                for (int i = 0; i < count; i++) {
22565                    IOnPermissionsChangeListener callback = mPermissionListeners
22566                            .getBroadcastItem(i);
22567                    try {
22568                        callback.onPermissionsChanged(uid);
22569                    } catch (RemoteException e) {
22570                        Log.e(TAG, "Permission listener is dead", e);
22571                    }
22572                }
22573            } finally {
22574                mPermissionListeners.finishBroadcast();
22575            }
22576        }
22577    }
22578
22579    private class PackageManagerNative extends IPackageManagerNative.Stub {
22580        @Override
22581        public String[] getNamesForUids(int[] uids) throws RemoteException {
22582            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22583            // massage results so they can be parsed by the native binder
22584            for (int i = results.length - 1; i >= 0; --i) {
22585                if (results[i] == null) {
22586                    results[i] = "";
22587                }
22588            }
22589            return results;
22590        }
22591
22592        // NB: this differentiates between preloads and sideloads
22593        @Override
22594        public String getInstallerForPackage(String packageName) throws RemoteException {
22595            final String installerName = getInstallerPackageName(packageName);
22596            if (!TextUtils.isEmpty(installerName)) {
22597                return installerName;
22598            }
22599            // differentiate between preload and sideload
22600            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22601            ApplicationInfo appInfo = getApplicationInfo(packageName,
22602                                    /*flags*/ 0,
22603                                    /*userId*/ callingUser);
22604            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22605                return "preload";
22606            }
22607            return "";
22608        }
22609
22610        @Override
22611        public int getVersionCodeForPackage(String packageName) throws RemoteException {
22612            try {
22613                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22614                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22615                if (pInfo != null) {
22616                    return pInfo.versionCode;
22617                }
22618            } catch (Exception e) {
22619            }
22620            return 0;
22621        }
22622    }
22623
22624    private class PackageManagerInternalImpl extends PackageManagerInternal {
22625        @Override
22626        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22627                int flagValues, int userId) {
22628            PackageManagerService.this.updatePermissionFlags(
22629                    permName, packageName, flagMask, flagValues, userId);
22630        }
22631
22632        @Override
22633        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22634            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22635        }
22636
22637        @Override
22638        public boolean isInstantApp(String packageName, int userId) {
22639            return PackageManagerService.this.isInstantApp(packageName, userId);
22640        }
22641
22642        @Override
22643        public String getInstantAppPackageName(int uid) {
22644            return PackageManagerService.this.getInstantAppPackageName(uid);
22645        }
22646
22647        @Override
22648        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
22649            synchronized (mPackages) {
22650                return PackageManagerService.this.filterAppAccessLPr(
22651                        (PackageSetting) pkg.mExtras, callingUid, userId);
22652            }
22653        }
22654
22655        @Override
22656        public PackageParser.Package getPackage(String packageName) {
22657            synchronized (mPackages) {
22658                packageName = resolveInternalPackageNameLPr(
22659                        packageName, PackageManager.VERSION_CODE_HIGHEST);
22660                return mPackages.get(packageName);
22661            }
22662        }
22663
22664        @Override
22665        public PackageParser.Package getDisabledPackage(String packageName) {
22666            synchronized (mPackages) {
22667                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
22668                return (ps != null) ? ps.pkg : null;
22669            }
22670        }
22671
22672        @Override
22673        public String getKnownPackageName(int knownPackage, int userId) {
22674            switch(knownPackage) {
22675                case PackageManagerInternal.PACKAGE_BROWSER:
22676                    return getDefaultBrowserPackageName(userId);
22677                case PackageManagerInternal.PACKAGE_INSTALLER:
22678                    return mRequiredInstallerPackage;
22679                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
22680                    return mSetupWizardPackage;
22681                case PackageManagerInternal.PACKAGE_SYSTEM:
22682                    return "android";
22683                case PackageManagerInternal.PACKAGE_VERIFIER:
22684                    return mRequiredVerifierPackage;
22685            }
22686            return null;
22687        }
22688
22689        @Override
22690        public boolean isResolveActivityComponent(ComponentInfo component) {
22691            return mResolveActivity.packageName.equals(component.packageName)
22692                    && mResolveActivity.name.equals(component.name);
22693        }
22694
22695        @Override
22696        public void setLocationPackagesProvider(PackagesProvider provider) {
22697            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
22698        }
22699
22700        @Override
22701        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22702            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
22703        }
22704
22705        @Override
22706        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22707            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
22708        }
22709
22710        @Override
22711        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22712            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
22713        }
22714
22715        @Override
22716        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22717            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
22718        }
22719
22720        @Override
22721        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22722            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
22723        }
22724
22725        @Override
22726        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22727            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
22728        }
22729
22730        @Override
22731        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22732            synchronized (mPackages) {
22733                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22734            }
22735            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
22736        }
22737
22738        @Override
22739        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22740            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
22741                    packageName, userId);
22742        }
22743
22744        @Override
22745        public void setKeepUninstalledPackages(final List<String> packageList) {
22746            Preconditions.checkNotNull(packageList);
22747            List<String> removedFromList = null;
22748            synchronized (mPackages) {
22749                if (mKeepUninstalledPackages != null) {
22750                    final int packagesCount = mKeepUninstalledPackages.size();
22751                    for (int i = 0; i < packagesCount; i++) {
22752                        String oldPackage = mKeepUninstalledPackages.get(i);
22753                        if (packageList != null && packageList.contains(oldPackage)) {
22754                            continue;
22755                        }
22756                        if (removedFromList == null) {
22757                            removedFromList = new ArrayList<>();
22758                        }
22759                        removedFromList.add(oldPackage);
22760                    }
22761                }
22762                mKeepUninstalledPackages = new ArrayList<>(packageList);
22763                if (removedFromList != null) {
22764                    final int removedCount = removedFromList.size();
22765                    for (int i = 0; i < removedCount; i++) {
22766                        deletePackageIfUnusedLPr(removedFromList.get(i));
22767                    }
22768                }
22769            }
22770        }
22771
22772        @Override
22773        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22774            synchronized (mPackages) {
22775                return mPermissionManager.isPermissionsReviewRequired(
22776                        mPackages.get(packageName), userId);
22777            }
22778        }
22779
22780        @Override
22781        public PackageInfo getPackageInfo(
22782                String packageName, int flags, int filterCallingUid, int userId) {
22783            return PackageManagerService.this
22784                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
22785                            flags, filterCallingUid, userId);
22786        }
22787
22788        @Override
22789        public int getPackageUid(String packageName, int flags, int userId) {
22790            return PackageManagerService.this
22791                    .getPackageUid(packageName, flags, userId);
22792        }
22793
22794        @Override
22795        public ApplicationInfo getApplicationInfo(
22796                String packageName, int flags, int filterCallingUid, int userId) {
22797            return PackageManagerService.this
22798                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
22799        }
22800
22801        @Override
22802        public ActivityInfo getActivityInfo(
22803                ComponentName component, int flags, int filterCallingUid, int userId) {
22804            return PackageManagerService.this
22805                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
22806        }
22807
22808        @Override
22809        public List<ResolveInfo> queryIntentActivities(
22810                Intent intent, int flags, int filterCallingUid, int userId) {
22811            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22812            return PackageManagerService.this
22813                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
22814                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
22815        }
22816
22817        @Override
22818        public List<ResolveInfo> queryIntentServices(
22819                Intent intent, int flags, int callingUid, int userId) {
22820            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22821            return PackageManagerService.this
22822                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
22823                            false);
22824        }
22825
22826        @Override
22827        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22828                int userId) {
22829            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22830        }
22831
22832        @Override
22833        public void setDeviceAndProfileOwnerPackages(
22834                int deviceOwnerUserId, String deviceOwnerPackage,
22835                SparseArray<String> profileOwnerPackages) {
22836            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22837                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22838        }
22839
22840        @Override
22841        public boolean isPackageDataProtected(int userId, String packageName) {
22842            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22843        }
22844
22845        @Override
22846        public boolean isPackageEphemeral(int userId, String packageName) {
22847            synchronized (mPackages) {
22848                final PackageSetting ps = mSettings.mPackages.get(packageName);
22849                return ps != null ? ps.getInstantApp(userId) : false;
22850            }
22851        }
22852
22853        @Override
22854        public boolean wasPackageEverLaunched(String packageName, int userId) {
22855            synchronized (mPackages) {
22856                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22857            }
22858        }
22859
22860        @Override
22861        public void grantRuntimePermission(String packageName, String permName, int userId,
22862                boolean overridePolicy) {
22863            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
22864                    permName, packageName, overridePolicy, getCallingUid(), userId,
22865                    mPermissionCallback);
22866        }
22867
22868        @Override
22869        public void revokeRuntimePermission(String packageName, String permName, int userId,
22870                boolean overridePolicy) {
22871            mPermissionManager.revokeRuntimePermission(
22872                    permName, packageName, overridePolicy, getCallingUid(), userId,
22873                    mPermissionCallback);
22874        }
22875
22876        @Override
22877        public String getNameForUid(int uid) {
22878            return PackageManagerService.this.getNameForUid(uid);
22879        }
22880
22881        @Override
22882        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22883                Intent origIntent, String resolvedType, String callingPackage,
22884                Bundle verificationBundle, int userId) {
22885            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22886                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
22887                    userId);
22888        }
22889
22890        @Override
22891        public void grantEphemeralAccess(int userId, Intent intent,
22892                int targetAppId, int ephemeralAppId) {
22893            synchronized (mPackages) {
22894                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22895                        targetAppId, ephemeralAppId);
22896            }
22897        }
22898
22899        @Override
22900        public boolean isInstantAppInstallerComponent(ComponentName component) {
22901            synchronized (mPackages) {
22902                return mInstantAppInstallerActivity != null
22903                        && mInstantAppInstallerActivity.getComponentName().equals(component);
22904            }
22905        }
22906
22907        @Override
22908        public void pruneInstantApps() {
22909            mInstantAppRegistry.pruneInstantApps();
22910        }
22911
22912        @Override
22913        public String getSetupWizardPackageName() {
22914            return mSetupWizardPackage;
22915        }
22916
22917        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22918            if (policy != null) {
22919                mExternalSourcesPolicy = policy;
22920            }
22921        }
22922
22923        @Override
22924        public boolean isPackagePersistent(String packageName) {
22925            synchronized (mPackages) {
22926                PackageParser.Package pkg = mPackages.get(packageName);
22927                return pkg != null
22928                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22929                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22930                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22931                        : false;
22932            }
22933        }
22934
22935        @Override
22936        public boolean isLegacySystemApp(Package pkg) {
22937            synchronized (mPackages) {
22938                final PackageSetting ps = (PackageSetting) pkg.mExtras;
22939                return mPromoteSystemApps
22940                        && ps.isSystem()
22941                        && mExistingSystemPackages.contains(ps.name);
22942            }
22943        }
22944
22945        @Override
22946        public List<PackageInfo> getOverlayPackages(int userId) {
22947            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22948            synchronized (mPackages) {
22949                for (PackageParser.Package p : mPackages.values()) {
22950                    if (p.mOverlayTarget != null) {
22951                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22952                        if (pkg != null) {
22953                            overlayPackages.add(pkg);
22954                        }
22955                    }
22956                }
22957            }
22958            return overlayPackages;
22959        }
22960
22961        @Override
22962        public List<String> getTargetPackageNames(int userId) {
22963            List<String> targetPackages = new ArrayList<>();
22964            synchronized (mPackages) {
22965                for (PackageParser.Package p : mPackages.values()) {
22966                    if (p.mOverlayTarget == null) {
22967                        targetPackages.add(p.packageName);
22968                    }
22969                }
22970            }
22971            return targetPackages;
22972        }
22973
22974        @Override
22975        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
22976                @Nullable List<String> overlayPackageNames) {
22977            synchronized (mPackages) {
22978                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
22979                    Slog.e(TAG, "failed to find package " + targetPackageName);
22980                    return false;
22981                }
22982                ArrayList<String> overlayPaths = null;
22983                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
22984                    final int N = overlayPackageNames.size();
22985                    overlayPaths = new ArrayList<>(N);
22986                    for (int i = 0; i < N; i++) {
22987                        final String packageName = overlayPackageNames.get(i);
22988                        final PackageParser.Package pkg = mPackages.get(packageName);
22989                        if (pkg == null) {
22990                            Slog.e(TAG, "failed to find package " + packageName);
22991                            return false;
22992                        }
22993                        overlayPaths.add(pkg.baseCodePath);
22994                    }
22995                }
22996
22997                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
22998                ps.setOverlayPaths(overlayPaths, userId);
22999                return true;
23000            }
23001        }
23002
23003        @Override
23004        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23005                int flags, int userId, boolean resolveForStart) {
23006            return resolveIntentInternal(
23007                    intent, resolvedType, flags, userId, resolveForStart);
23008        }
23009
23010        @Override
23011        public ResolveInfo resolveService(Intent intent, String resolvedType,
23012                int flags, int userId, int callingUid) {
23013            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23014        }
23015
23016        @Override
23017        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23018            return PackageManagerService.this.resolveContentProviderInternal(
23019                    name, flags, userId);
23020        }
23021
23022        @Override
23023        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23024            synchronized (mPackages) {
23025                mIsolatedOwners.put(isolatedUid, ownerUid);
23026            }
23027        }
23028
23029        @Override
23030        public void removeIsolatedUid(int isolatedUid) {
23031            synchronized (mPackages) {
23032                mIsolatedOwners.delete(isolatedUid);
23033            }
23034        }
23035
23036        @Override
23037        public int getUidTargetSdkVersion(int uid) {
23038            synchronized (mPackages) {
23039                return getUidTargetSdkVersionLockedLPr(uid);
23040            }
23041        }
23042
23043        @Override
23044        public boolean canAccessInstantApps(int callingUid, int userId) {
23045            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23046        }
23047
23048        @Override
23049        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23050            synchronized (mPackages) {
23051                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23052            }
23053        }
23054
23055        @Override
23056        public void notifyPackageUse(String packageName, int reason) {
23057            synchronized (mPackages) {
23058                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23059            }
23060        }
23061    }
23062
23063    @Override
23064    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23065        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23066        synchronized (mPackages) {
23067            final long identity = Binder.clearCallingIdentity();
23068            try {
23069                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23070                        packageNames, userId);
23071            } finally {
23072                Binder.restoreCallingIdentity(identity);
23073            }
23074        }
23075    }
23076
23077    @Override
23078    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23079        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23080        synchronized (mPackages) {
23081            final long identity = Binder.clearCallingIdentity();
23082            try {
23083                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23084                        packageNames, userId);
23085            } finally {
23086                Binder.restoreCallingIdentity(identity);
23087            }
23088        }
23089    }
23090
23091    private static void enforceSystemOrPhoneCaller(String tag) {
23092        int callingUid = Binder.getCallingUid();
23093        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23094            throw new SecurityException(
23095                    "Cannot call " + tag + " from UID " + callingUid);
23096        }
23097    }
23098
23099    boolean isHistoricalPackageUsageAvailable() {
23100        return mPackageUsage.isHistoricalPackageUsageAvailable();
23101    }
23102
23103    /**
23104     * Return a <b>copy</b> of the collection of packages known to the package manager.
23105     * @return A copy of the values of mPackages.
23106     */
23107    Collection<PackageParser.Package> getPackages() {
23108        synchronized (mPackages) {
23109            return new ArrayList<>(mPackages.values());
23110        }
23111    }
23112
23113    /**
23114     * Logs process start information (including base APK hash) to the security log.
23115     * @hide
23116     */
23117    @Override
23118    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23119            String apkFile, int pid) {
23120        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23121            return;
23122        }
23123        if (!SecurityLog.isLoggingEnabled()) {
23124            return;
23125        }
23126        Bundle data = new Bundle();
23127        data.putLong("startTimestamp", System.currentTimeMillis());
23128        data.putString("processName", processName);
23129        data.putInt("uid", uid);
23130        data.putString("seinfo", seinfo);
23131        data.putString("apkFile", apkFile);
23132        data.putInt("pid", pid);
23133        Message msg = mProcessLoggingHandler.obtainMessage(
23134                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23135        msg.setData(data);
23136        mProcessLoggingHandler.sendMessage(msg);
23137    }
23138
23139    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23140        return mCompilerStats.getPackageStats(pkgName);
23141    }
23142
23143    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23144        return getOrCreateCompilerPackageStats(pkg.packageName);
23145    }
23146
23147    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23148        return mCompilerStats.getOrCreatePackageStats(pkgName);
23149    }
23150
23151    public void deleteCompilerPackageStats(String pkgName) {
23152        mCompilerStats.deletePackageStats(pkgName);
23153    }
23154
23155    @Override
23156    public int getInstallReason(String packageName, int userId) {
23157        final int callingUid = Binder.getCallingUid();
23158        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23159                true /* requireFullPermission */, false /* checkShell */,
23160                "get install reason");
23161        synchronized (mPackages) {
23162            final PackageSetting ps = mSettings.mPackages.get(packageName);
23163            if (filterAppAccessLPr(ps, callingUid, userId)) {
23164                return PackageManager.INSTALL_REASON_UNKNOWN;
23165            }
23166            if (ps != null) {
23167                return ps.getInstallReason(userId);
23168            }
23169        }
23170        return PackageManager.INSTALL_REASON_UNKNOWN;
23171    }
23172
23173    @Override
23174    public boolean canRequestPackageInstalls(String packageName, int userId) {
23175        return canRequestPackageInstallsInternal(packageName, 0, userId,
23176                true /* throwIfPermNotDeclared*/);
23177    }
23178
23179    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23180            boolean throwIfPermNotDeclared) {
23181        int callingUid = Binder.getCallingUid();
23182        int uid = getPackageUid(packageName, 0, userId);
23183        if (callingUid != uid && callingUid != Process.ROOT_UID
23184                && callingUid != Process.SYSTEM_UID) {
23185            throw new SecurityException(
23186                    "Caller uid " + callingUid + " does not own package " + packageName);
23187        }
23188        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23189        if (info == null) {
23190            return false;
23191        }
23192        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23193            return false;
23194        }
23195        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23196        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23197        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23198            if (throwIfPermNotDeclared) {
23199                throw new SecurityException("Need to declare " + appOpPermission
23200                        + " to call this api");
23201            } else {
23202                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23203                return false;
23204            }
23205        }
23206        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23207            return false;
23208        }
23209        if (mExternalSourcesPolicy != null) {
23210            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23211            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23212                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23213            }
23214        }
23215        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23216    }
23217
23218    @Override
23219    public ComponentName getInstantAppResolverSettingsComponent() {
23220        return mInstantAppResolverSettingsComponent;
23221    }
23222
23223    @Override
23224    public ComponentName getInstantAppInstallerComponent() {
23225        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23226            return null;
23227        }
23228        return mInstantAppInstallerActivity == null
23229                ? null : mInstantAppInstallerActivity.getComponentName();
23230    }
23231
23232    @Override
23233    public String getInstantAppAndroidId(String packageName, int userId) {
23234        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23235                "getInstantAppAndroidId");
23236        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23237                true /* requireFullPermission */, false /* checkShell */,
23238                "getInstantAppAndroidId");
23239        // Make sure the target is an Instant App.
23240        if (!isInstantApp(packageName, userId)) {
23241            return null;
23242        }
23243        synchronized (mPackages) {
23244            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23245        }
23246    }
23247
23248    boolean canHaveOatDir(String packageName) {
23249        synchronized (mPackages) {
23250            PackageParser.Package p = mPackages.get(packageName);
23251            if (p == null) {
23252                return false;
23253            }
23254            return p.canHaveOatDir();
23255        }
23256    }
23257
23258    private String getOatDir(PackageParser.Package pkg) {
23259        if (!pkg.canHaveOatDir()) {
23260            return null;
23261        }
23262        File codePath = new File(pkg.codePath);
23263        if (codePath.isDirectory()) {
23264            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23265        }
23266        return null;
23267    }
23268
23269    void deleteOatArtifactsOfPackage(String packageName) {
23270        final String[] instructionSets;
23271        final List<String> codePaths;
23272        final String oatDir;
23273        final PackageParser.Package pkg;
23274        synchronized (mPackages) {
23275            pkg = mPackages.get(packageName);
23276        }
23277        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23278        codePaths = pkg.getAllCodePaths();
23279        oatDir = getOatDir(pkg);
23280
23281        for (String codePath : codePaths) {
23282            for (String isa : instructionSets) {
23283                try {
23284                    mInstaller.deleteOdex(codePath, isa, oatDir);
23285                } catch (InstallerException e) {
23286                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23287                }
23288            }
23289        }
23290    }
23291
23292    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23293        Set<String> unusedPackages = new HashSet<>();
23294        long currentTimeInMillis = System.currentTimeMillis();
23295        synchronized (mPackages) {
23296            for (PackageParser.Package pkg : mPackages.values()) {
23297                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23298                if (ps == null) {
23299                    continue;
23300                }
23301                PackageDexUsage.PackageUseInfo packageUseInfo =
23302                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23303                if (PackageManagerServiceUtils
23304                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23305                                downgradeTimeThresholdMillis, packageUseInfo,
23306                                pkg.getLatestPackageUseTimeInMills(),
23307                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23308                    unusedPackages.add(pkg.packageName);
23309                }
23310            }
23311        }
23312        return unusedPackages;
23313    }
23314}
23315
23316interface PackageSender {
23317    void sendPackageBroadcast(final String action, final String pkg,
23318        final Bundle extras, final int flags, final String targetPkg,
23319        final IIntentReceiver finishedReceiver, final int[] userIds);
23320    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23321        boolean includeStopped, int appId, int... userIds);
23322}
23323