PackageManagerService.java revision 3accca05ddcad9d0b1b313eae49f273e39121d3c
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.res.Resources;
190import android.database.ContentObserver;
191import android.graphics.Bitmap;
192import android.hardware.display.DisplayManager;
193import android.net.Uri;
194import android.os.Binder;
195import android.os.Build;
196import android.os.Bundle;
197import android.os.Debug;
198import android.os.Environment;
199import android.os.Environment.UserEnvironment;
200import android.os.FileUtils;
201import android.os.Handler;
202import android.os.IBinder;
203import android.os.Looper;
204import android.os.Message;
205import android.os.Parcel;
206import android.os.ParcelFileDescriptor;
207import android.os.PatternMatcher;
208import android.os.Process;
209import android.os.RemoteCallbackList;
210import android.os.RemoteException;
211import android.os.ResultReceiver;
212import android.os.SELinux;
213import android.os.ServiceManager;
214import android.os.ShellCallback;
215import android.os.SystemClock;
216import android.os.SystemProperties;
217import android.os.Trace;
218import android.os.UserHandle;
219import android.os.UserManager;
220import android.os.UserManagerInternal;
221import android.os.storage.IStorageManager;
222import android.os.storage.StorageEventListener;
223import android.os.storage.StorageManager;
224import android.os.storage.StorageManagerInternal;
225import android.os.storage.VolumeInfo;
226import android.os.storage.VolumeRecord;
227import android.provider.Settings.Global;
228import android.provider.Settings.Secure;
229import android.security.KeyStore;
230import android.security.SystemKeyStore;
231import android.service.pm.PackageServiceDumpProto;
232import android.system.ErrnoException;
233import android.system.Os;
234import android.text.TextUtils;
235import android.text.format.DateUtils;
236import android.util.ArrayMap;
237import android.util.ArraySet;
238import android.util.Base64;
239import android.util.DisplayMetrics;
240import android.util.EventLog;
241import android.util.ExceptionUtils;
242import android.util.Log;
243import android.util.LogPrinter;
244import android.util.LongSparseArray;
245import android.util.LongSparseLongArray;
246import android.util.MathUtils;
247import android.util.PackageUtils;
248import android.util.Pair;
249import android.util.PrintStreamPrinter;
250import android.util.Slog;
251import android.util.SparseArray;
252import android.util.SparseBooleanArray;
253import android.util.SparseIntArray;
254import android.util.TimingsTraceLog;
255import android.util.Xml;
256import android.util.jar.StrictJarFile;
257import android.util.proto.ProtoOutputStream;
258import android.view.Display;
259
260import com.android.internal.R;
261import com.android.internal.annotations.GuardedBy;
262import com.android.internal.app.IMediaContainerService;
263import com.android.internal.app.ResolverActivity;
264import com.android.internal.content.NativeLibraryHelper;
265import com.android.internal.content.PackageHelper;
266import com.android.internal.logging.MetricsLogger;
267import com.android.internal.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.DexLogger;
294import com.android.server.pm.dex.DexManager;
295import com.android.server.pm.dex.DexoptOptions;
296import com.android.server.pm.dex.PackageDexUsage;
297import com.android.server.pm.permission.BasePermission;
298import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
299import com.android.server.pm.permission.PermissionManagerService;
300import com.android.server.pm.permission.PermissionManagerInternal;
301import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
302import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
303import com.android.server.pm.permission.PermissionsState;
304import com.android.server.pm.permission.PermissionsState.PermissionState;
305import com.android.server.storage.DeviceStorageMonitorInternal;
306
307import dalvik.system.CloseGuard;
308import dalvik.system.VMRuntime;
309
310import libcore.io.IoUtils;
311
312import org.xmlpull.v1.XmlPullParser;
313import org.xmlpull.v1.XmlPullParserException;
314import org.xmlpull.v1.XmlSerializer;
315
316import java.io.BufferedOutputStream;
317import java.io.ByteArrayInputStream;
318import java.io.ByteArrayOutputStream;
319import java.io.File;
320import java.io.FileDescriptor;
321import java.io.FileInputStream;
322import java.io.FileOutputStream;
323import java.io.FilenameFilter;
324import java.io.IOException;
325import java.io.PrintWriter;
326import java.lang.annotation.Retention;
327import java.lang.annotation.RetentionPolicy;
328import java.nio.charset.StandardCharsets;
329import java.security.DigestInputStream;
330import java.security.MessageDigest;
331import java.security.NoSuchAlgorithmException;
332import java.security.PublicKey;
333import java.security.SecureRandom;
334import java.security.cert.Certificate;
335import java.security.cert.CertificateException;
336import java.util.ArrayList;
337import java.util.Arrays;
338import java.util.Collection;
339import java.util.Collections;
340import java.util.Comparator;
341import java.util.HashMap;
342import java.util.HashSet;
343import java.util.Iterator;
344import java.util.LinkedHashSet;
345import java.util.List;
346import java.util.Map;
347import java.util.Objects;
348import java.util.Set;
349import java.util.concurrent.CountDownLatch;
350import java.util.concurrent.Future;
351import java.util.concurrent.TimeUnit;
352import java.util.concurrent.atomic.AtomicBoolean;
353import java.util.concurrent.atomic.AtomicInteger;
354
355/**
356 * Keep track of all those APKs everywhere.
357 * <p>
358 * Internally there are two important locks:
359 * <ul>
360 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
361 * and other related state. It is a fine-grained lock that should only be held
362 * momentarily, as it's one of the most contended locks in the system.
363 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
364 * operations typically involve heavy lifting of application data on disk. Since
365 * {@code installd} is single-threaded, and it's operations can often be slow,
366 * this lock should never be acquired while already holding {@link #mPackages}.
367 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
368 * holding {@link #mInstallLock}.
369 * </ul>
370 * Many internal methods rely on the caller to hold the appropriate locks, and
371 * this contract is expressed through method name suffixes:
372 * <ul>
373 * <li>fooLI(): the caller must hold {@link #mInstallLock}
374 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
375 * being modified must be frozen
376 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
377 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
378 * </ul>
379 * <p>
380 * Because this class is very central to the platform's security; please run all
381 * CTS and unit tests whenever making modifications:
382 *
383 * <pre>
384 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
385 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
386 * </pre>
387 */
388public class PackageManagerService extends IPackageManager.Stub
389        implements PackageSender {
390    static final String TAG = "PackageManager";
391    public static final boolean DEBUG_SETTINGS = false;
392    static final boolean DEBUG_PREFERRED = false;
393    static final boolean DEBUG_UPGRADE = false;
394    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
395    private static final boolean DEBUG_BACKUP = false;
396    public static final boolean DEBUG_INSTALL = false;
397    public static final boolean DEBUG_REMOVE = false;
398    private static final boolean DEBUG_BROADCASTS = false;
399    private static final boolean DEBUG_SHOW_INFO = false;
400    private static final boolean DEBUG_PACKAGE_INFO = false;
401    private static final boolean DEBUG_INTENT_MATCHING = false;
402    public static final boolean DEBUG_PACKAGE_SCANNING = false;
403    private static final boolean DEBUG_VERIFY = false;
404    private static final boolean DEBUG_FILTERS = false;
405    public static final boolean DEBUG_PERMISSIONS = false;
406    private static final boolean DEBUG_SHARED_LIBRARIES = false;
407    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
408
409    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
410    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
411    // user, but by default initialize to this.
412    public static final boolean DEBUG_DEXOPT = false;
413
414    private static final boolean DEBUG_ABI_SELECTION = false;
415    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
416    private static final boolean DEBUG_TRIAGED_MISSING = false;
417    private static final boolean DEBUG_APP_DATA = false;
418
419    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
420    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
421
422    private static final boolean HIDE_EPHEMERAL_APIS = false;
423
424    private static final boolean ENABLE_FREE_CACHE_V2 =
425            SystemProperties.getBoolean("fw.free_cache_v2", true);
426
427    private static final int RADIO_UID = Process.PHONE_UID;
428    private static final int LOG_UID = Process.LOG_UID;
429    private static final int NFC_UID = Process.NFC_UID;
430    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
431    private static final int SHELL_UID = Process.SHELL_UID;
432
433    // Suffix used during package installation when copying/moving
434    // package apks to install directory.
435    private static final String INSTALL_PACKAGE_SUFFIX = "-";
436
437    static final int SCAN_NO_DEX = 1<<0;
438    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
439    static final int SCAN_NEW_INSTALL = 1<<2;
440    static final int SCAN_UPDATE_TIME = 1<<3;
441    static final int SCAN_BOOTING = 1<<4;
442    static final int SCAN_TRUSTED_OVERLAY = 1<<5;
443    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
444    static final int SCAN_REQUIRE_KNOWN = 1<<7;
445    static final int SCAN_MOVE = 1<<8;
446    static final int SCAN_INITIAL = 1<<9;
447    static final int SCAN_CHECK_ONLY = 1<<10;
448    static final int SCAN_DONT_KILL_APP = 1<<11;
449    static final int SCAN_IGNORE_FROZEN = 1<<12;
450    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
451    static final int SCAN_AS_INSTANT_APP = 1<<14;
452    static final int SCAN_AS_FULL_APP = 1<<15;
453    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
454    static final int SCAN_AS_SYSTEM = 1<<17;
455    static final int SCAN_AS_PRIVILEGED = 1<<18;
456    static final int SCAN_AS_OEM = 1<<19;
457
458    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
459            SCAN_NO_DEX,
460            SCAN_UPDATE_SIGNATURE,
461            SCAN_NEW_INSTALL,
462            SCAN_UPDATE_TIME,
463            SCAN_BOOTING,
464            SCAN_TRUSTED_OVERLAY,
465            SCAN_DELETE_DATA_ON_FAILURES,
466            SCAN_REQUIRE_KNOWN,
467            SCAN_MOVE,
468            SCAN_INITIAL,
469            SCAN_CHECK_ONLY,
470            SCAN_DONT_KILL_APP,
471            SCAN_IGNORE_FROZEN,
472            SCAN_FIRST_BOOT_OR_UPGRADE,
473            SCAN_AS_INSTANT_APP,
474            SCAN_AS_FULL_APP,
475            SCAN_AS_VIRTUAL_PRELOAD,
476    })
477    @Retention(RetentionPolicy.SOURCE)
478    public @interface ScanFlags {}
479
480    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
481    /** Extension of the compressed packages */
482    public final static String COMPRESSED_EXTENSION = ".gz";
483    /** Suffix of stub packages on the system partition */
484    public final static String STUB_SUFFIX = "-Stub";
485
486    private static final int[] EMPTY_INT_ARRAY = new int[0];
487
488    private static final int TYPE_UNKNOWN = 0;
489    private static final int TYPE_ACTIVITY = 1;
490    private static final int TYPE_RECEIVER = 2;
491    private static final int TYPE_SERVICE = 3;
492    private static final int TYPE_PROVIDER = 4;
493    @IntDef(prefix = { "TYPE_" }, value = {
494            TYPE_UNKNOWN,
495            TYPE_ACTIVITY,
496            TYPE_RECEIVER,
497            TYPE_SERVICE,
498            TYPE_PROVIDER,
499    })
500    @Retention(RetentionPolicy.SOURCE)
501    public @interface ComponentType {}
502
503    /**
504     * Timeout (in milliseconds) after which the watchdog should declare that
505     * our handler thread is wedged.  The usual default for such things is one
506     * minute but we sometimes do very lengthy I/O operations on this thread,
507     * such as installing multi-gigabyte applications, so ours needs to be longer.
508     */
509    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
510
511    /**
512     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
513     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
514     * settings entry if available, otherwise we use the hardcoded default.  If it's been
515     * more than this long since the last fstrim, we force one during the boot sequence.
516     *
517     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
518     * one gets run at the next available charging+idle time.  This final mandatory
519     * no-fstrim check kicks in only of the other scheduling criteria is never met.
520     */
521    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
522
523    /**
524     * Whether verification is enabled by default.
525     */
526    private static final boolean DEFAULT_VERIFY_ENABLE = true;
527
528    /**
529     * The default maximum time to wait for the verification agent to return in
530     * milliseconds.
531     */
532    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
533
534    /**
535     * The default response for package verification timeout.
536     *
537     * This can be either PackageManager.VERIFICATION_ALLOW or
538     * PackageManager.VERIFICATION_REJECT.
539     */
540    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
541
542    public static final String PLATFORM_PACKAGE_NAME = "android";
543
544    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
545
546    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
547            DEFAULT_CONTAINER_PACKAGE,
548            "com.android.defcontainer.DefaultContainerService");
549
550    private static final String KILL_APP_REASON_GIDS_CHANGED =
551            "permission grant or revoke changed gids";
552
553    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
554            "permissions revoked";
555
556    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
557
558    private static final String PACKAGE_SCHEME = "package";
559
560    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
561
562    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
563
564    /** Canonical intent used to identify what counts as a "web browser" app */
565    private static final Intent sBrowserIntent;
566    static {
567        sBrowserIntent = new Intent();
568        sBrowserIntent.setAction(Intent.ACTION_VIEW);
569        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
570        sBrowserIntent.setData(Uri.parse("http:"));
571    }
572
573    /**
574     * The set of all protected actions [i.e. those actions for which a high priority
575     * intent filter is disallowed].
576     */
577    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
578    static {
579        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
580        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
581        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
582        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
583    }
584
585    // Compilation reasons.
586    public static final int REASON_FIRST_BOOT = 0;
587    public static final int REASON_BOOT = 1;
588    public static final int REASON_INSTALL = 2;
589    public static final int REASON_BACKGROUND_DEXOPT = 3;
590    public static final int REASON_AB_OTA = 4;
591    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
592    public static final int REASON_SHARED = 6;
593
594    public static final int REASON_LAST = REASON_SHARED;
595
596    /**
597     * Version number for the package parser cache. Increment this whenever the format or
598     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
599     */
600    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
601
602    /**
603     * Whether the package parser cache is enabled.
604     */
605    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
606
607    final ServiceThread mHandlerThread;
608
609    final PackageHandler mHandler;
610
611    private final ProcessLoggingHandler mProcessLoggingHandler;
612
613    /**
614     * Messages for {@link #mHandler} that need to wait for system ready before
615     * being dispatched.
616     */
617    private ArrayList<Message> mPostSystemReadyMessages;
618
619    final int mSdkVersion = Build.VERSION.SDK_INT;
620
621    final Context mContext;
622    final boolean mFactoryTest;
623    final boolean mOnlyCore;
624    final DisplayMetrics mMetrics;
625    final int mDefParseFlags;
626    final String[] mSeparateProcesses;
627    final boolean mIsUpgrade;
628    final boolean mIsPreNUpgrade;
629    final boolean mIsPreNMR1Upgrade;
630
631    // Have we told the Activity Manager to whitelist the default container service by uid yet?
632    @GuardedBy("mPackages")
633    boolean mDefaultContainerWhitelisted = false;
634
635    @GuardedBy("mPackages")
636    private boolean mDexOptDialogShown;
637
638    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
639    // LOCK HELD.  Can be called with mInstallLock held.
640    @GuardedBy("mInstallLock")
641    final Installer mInstaller;
642
643    /** Directory where installed third-party apps stored */
644    final File mAppInstallDir;
645
646    /**
647     * Directory to which applications installed internally have their
648     * 32 bit native libraries copied.
649     */
650    private File mAppLib32InstallDir;
651
652    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
653    // apps.
654    final File mDrmAppPrivateInstallDir;
655
656    // ----------------------------------------------------------------
657
658    // Lock for state used when installing and doing other long running
659    // operations.  Methods that must be called with this lock held have
660    // the suffix "LI".
661    final Object mInstallLock = new Object();
662
663    // ----------------------------------------------------------------
664
665    // Keys are String (package name), values are Package.  This also serves
666    // as the lock for the global state.  Methods that must be called with
667    // this lock held have the prefix "LP".
668    @GuardedBy("mPackages")
669    final ArrayMap<String, PackageParser.Package> mPackages =
670            new ArrayMap<String, PackageParser.Package>();
671
672    final ArrayMap<String, Set<String>> mKnownCodebase =
673            new ArrayMap<String, Set<String>>();
674
675    // Keys are isolated uids and values are the uid of the application
676    // that created the isolated proccess.
677    @GuardedBy("mPackages")
678    final SparseIntArray mIsolatedOwners = new SparseIntArray();
679
680    /**
681     * Tracks new system packages [received in an OTA] that we expect to
682     * find updated user-installed versions. Keys are package name, values
683     * are package location.
684     */
685    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
686    /**
687     * Tracks high priority intent filters for protected actions. During boot, certain
688     * filter actions are protected and should never be allowed to have a high priority
689     * intent filter for them. However, there is one, and only one exception -- the
690     * setup wizard. It must be able to define a high priority intent filter for these
691     * actions to ensure there are no escapes from the wizard. We need to delay processing
692     * of these during boot as we need to look at all of the system packages in order
693     * to know which component is the setup wizard.
694     */
695    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
696    /**
697     * Whether or not processing protected filters should be deferred.
698     */
699    private boolean mDeferProtectedFilters = true;
700
701    /**
702     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
703     */
704    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
705    /**
706     * Whether or not system app permissions should be promoted from install to runtime.
707     */
708    boolean mPromoteSystemApps;
709
710    @GuardedBy("mPackages")
711    final Settings mSettings;
712
713    /**
714     * Set of package names that are currently "frozen", which means active
715     * surgery is being done on the code/data for that package. The platform
716     * will refuse to launch frozen packages to avoid race conditions.
717     *
718     * @see PackageFreezer
719     */
720    @GuardedBy("mPackages")
721    final ArraySet<String> mFrozenPackages = new ArraySet<>();
722
723    final ProtectedPackages mProtectedPackages;
724
725    @GuardedBy("mLoadedVolumes")
726    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
727
728    boolean mFirstBoot;
729
730    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
731
732    @GuardedBy("mAvailableFeatures")
733    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
734
735    // If mac_permissions.xml was found for seinfo labeling.
736    boolean mFoundPolicyFile;
737
738    private final InstantAppRegistry mInstantAppRegistry;
739
740    @GuardedBy("mPackages")
741    int mChangedPackagesSequenceNumber;
742    /**
743     * List of changed [installed, removed or updated] packages.
744     * mapping from user id -> sequence number -> package name
745     */
746    @GuardedBy("mPackages")
747    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
748    /**
749     * The sequence number of the last change to a package.
750     * mapping from user id -> package name -> sequence number
751     */
752    @GuardedBy("mPackages")
753    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
754
755    class PackageParserCallback implements PackageParser.Callback {
756        @Override public final boolean hasFeature(String feature) {
757            return PackageManagerService.this.hasSystemFeature(feature, 0);
758        }
759
760        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
761                Collection<PackageParser.Package> allPackages, String targetPackageName) {
762            List<PackageParser.Package> overlayPackages = null;
763            for (PackageParser.Package p : allPackages) {
764                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
765                    if (overlayPackages == null) {
766                        overlayPackages = new ArrayList<PackageParser.Package>();
767                    }
768                    overlayPackages.add(p);
769                }
770            }
771            if (overlayPackages != null) {
772                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
773                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
774                        return p1.mOverlayPriority - p2.mOverlayPriority;
775                    }
776                };
777                Collections.sort(overlayPackages, cmp);
778            }
779            return overlayPackages;
780        }
781
782        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
783                String targetPackageName, String targetPath) {
784            if ("android".equals(targetPackageName)) {
785                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
786                // native AssetManager.
787                return null;
788            }
789            List<PackageParser.Package> overlayPackages =
790                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
791            if (overlayPackages == null || overlayPackages.isEmpty()) {
792                return null;
793            }
794            List<String> overlayPathList = null;
795            for (PackageParser.Package overlayPackage : overlayPackages) {
796                if (targetPath == null) {
797                    if (overlayPathList == null) {
798                        overlayPathList = new ArrayList<String>();
799                    }
800                    overlayPathList.add(overlayPackage.baseCodePath);
801                    continue;
802                }
803
804                try {
805                    // Creates idmaps for system to parse correctly the Android manifest of the
806                    // target package.
807                    //
808                    // OverlayManagerService will update each of them with a correct gid from its
809                    // target package app id.
810                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
811                            UserHandle.getSharedAppGid(
812                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
813                    if (overlayPathList == null) {
814                        overlayPathList = new ArrayList<String>();
815                    }
816                    overlayPathList.add(overlayPackage.baseCodePath);
817                } catch (InstallerException e) {
818                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
819                            overlayPackage.baseCodePath);
820                }
821            }
822            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
823        }
824
825        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
826            synchronized (mPackages) {
827                return getStaticOverlayPathsLocked(
828                        mPackages.values(), targetPackageName, targetPath);
829            }
830        }
831
832        @Override public final String[] getOverlayApks(String targetPackageName) {
833            return getStaticOverlayPaths(targetPackageName, null);
834        }
835
836        @Override public final String[] getOverlayPaths(String targetPackageName,
837                String targetPath) {
838            return getStaticOverlayPaths(targetPackageName, targetPath);
839        }
840    }
841
842    class ParallelPackageParserCallback extends PackageParserCallback {
843        List<PackageParser.Package> mOverlayPackages = null;
844
845        void findStaticOverlayPackages() {
846            synchronized (mPackages) {
847                for (PackageParser.Package p : mPackages.values()) {
848                    if (p.mIsStaticOverlay) {
849                        if (mOverlayPackages == null) {
850                            mOverlayPackages = new ArrayList<PackageParser.Package>();
851                        }
852                        mOverlayPackages.add(p);
853                    }
854                }
855            }
856        }
857
858        @Override
859        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
860            // We can trust mOverlayPackages without holding mPackages because package uninstall
861            // can't happen while running parallel parsing.
862            // Moreover holding mPackages on each parsing thread causes dead-lock.
863            return mOverlayPackages == null ? null :
864                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
865        }
866    }
867
868    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
869    final ParallelPackageParserCallback mParallelPackageParserCallback =
870            new ParallelPackageParserCallback();
871
872    public static final class SharedLibraryEntry {
873        public final @Nullable String path;
874        public final @Nullable String apk;
875        public final @NonNull SharedLibraryInfo info;
876
877        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
878                String declaringPackageName, long declaringPackageVersionCode) {
879            path = _path;
880            apk = _apk;
881            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
882                    declaringPackageName, declaringPackageVersionCode), null);
883        }
884    }
885
886    // Currently known shared libraries.
887    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
888    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
889            new ArrayMap<>();
890
891    // All available activities, for your resolving pleasure.
892    final ActivityIntentResolver mActivities =
893            new ActivityIntentResolver();
894
895    // All available receivers, for your resolving pleasure.
896    final ActivityIntentResolver mReceivers =
897            new ActivityIntentResolver();
898
899    // All available services, for your resolving pleasure.
900    final ServiceIntentResolver mServices = new ServiceIntentResolver();
901
902    // All available providers, for your resolving pleasure.
903    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
904
905    // Mapping from provider base names (first directory in content URI codePath)
906    // to the provider information.
907    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
908            new ArrayMap<String, PackageParser.Provider>();
909
910    // Mapping from instrumentation class names to info about them.
911    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
912            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
913
914    // Packages whose data we have transfered into another package, thus
915    // should no longer exist.
916    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
917
918    // Broadcast actions that are only available to the system.
919    @GuardedBy("mProtectedBroadcasts")
920    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
921
922    /** List of packages waiting for verification. */
923    final SparseArray<PackageVerificationState> mPendingVerification
924            = new SparseArray<PackageVerificationState>();
925
926    final PackageInstallerService mInstallerService;
927
928    private final PackageDexOptimizer mPackageDexOptimizer;
929    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
930    // is used by other apps).
931    private final DexManager mDexManager;
932
933    private AtomicInteger mNextMoveId = new AtomicInteger();
934    private final MoveCallbacks mMoveCallbacks;
935
936    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
937
938    // Cache of users who need badging.
939    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
940
941    /** Token for keys in mPendingVerification. */
942    private int mPendingVerificationToken = 0;
943
944    volatile boolean mSystemReady;
945    volatile boolean mSafeMode;
946    volatile boolean mHasSystemUidErrors;
947    private volatile boolean mEphemeralAppsDisabled;
948
949    ApplicationInfo mAndroidApplication;
950    final ActivityInfo mResolveActivity = new ActivityInfo();
951    final ResolveInfo mResolveInfo = new ResolveInfo();
952    ComponentName mResolveComponentName;
953    PackageParser.Package mPlatformPackage;
954    ComponentName mCustomResolverComponentName;
955
956    boolean mResolverReplaced = false;
957
958    private final @Nullable ComponentName mIntentFilterVerifierComponent;
959    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
960
961    private int mIntentFilterVerificationToken = 0;
962
963    /** The service connection to the ephemeral resolver */
964    final EphemeralResolverConnection mInstantAppResolverConnection;
965    /** Component used to show resolver settings for Instant Apps */
966    final ComponentName mInstantAppResolverSettingsComponent;
967
968    /** Activity used to install instant applications */
969    ActivityInfo mInstantAppInstallerActivity;
970    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
971
972    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
973            = new SparseArray<IntentFilterVerificationState>();
974
975    // TODO remove this and go through mPermissonManager directly
976    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
977    private final PermissionManagerInternal mPermissionManager;
978
979    // List of packages names to keep cached, even if they are uninstalled for all users
980    private List<String> mKeepUninstalledPackages;
981
982    private UserManagerInternal mUserManagerInternal;
983
984    private DeviceIdleController.LocalService mDeviceIdleController;
985
986    private File mCacheDir;
987
988    private Future<?> mPrepareAppDataFuture;
989
990    private static class IFVerificationParams {
991        PackageParser.Package pkg;
992        boolean replacing;
993        int userId;
994        int verifierUid;
995
996        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
997                int _userId, int _verifierUid) {
998            pkg = _pkg;
999            replacing = _replacing;
1000            userId = _userId;
1001            replacing = _replacing;
1002            verifierUid = _verifierUid;
1003        }
1004    }
1005
1006    private interface IntentFilterVerifier<T extends IntentFilter> {
1007        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1008                                               T filter, String packageName);
1009        void startVerifications(int userId);
1010        void receiveVerificationResponse(int verificationId);
1011    }
1012
1013    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1014        private Context mContext;
1015        private ComponentName mIntentFilterVerifierComponent;
1016        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1017
1018        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1019            mContext = context;
1020            mIntentFilterVerifierComponent = verifierComponent;
1021        }
1022
1023        private String getDefaultScheme() {
1024            return IntentFilter.SCHEME_HTTPS;
1025        }
1026
1027        @Override
1028        public void startVerifications(int userId) {
1029            // Launch verifications requests
1030            int count = mCurrentIntentFilterVerifications.size();
1031            for (int n=0; n<count; n++) {
1032                int verificationId = mCurrentIntentFilterVerifications.get(n);
1033                final IntentFilterVerificationState ivs =
1034                        mIntentFilterVerificationStates.get(verificationId);
1035
1036                String packageName = ivs.getPackageName();
1037
1038                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1039                final int filterCount = filters.size();
1040                ArraySet<String> domainsSet = new ArraySet<>();
1041                for (int m=0; m<filterCount; m++) {
1042                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1043                    domainsSet.addAll(filter.getHostsList());
1044                }
1045                synchronized (mPackages) {
1046                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1047                            packageName, domainsSet) != null) {
1048                        scheduleWriteSettingsLocked();
1049                    }
1050                }
1051                sendVerificationRequest(verificationId, ivs);
1052            }
1053            mCurrentIntentFilterVerifications.clear();
1054        }
1055
1056        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1057            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1058            verificationIntent.putExtra(
1059                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1060                    verificationId);
1061            verificationIntent.putExtra(
1062                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1063                    getDefaultScheme());
1064            verificationIntent.putExtra(
1065                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1066                    ivs.getHostsString());
1067            verificationIntent.putExtra(
1068                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1069                    ivs.getPackageName());
1070            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1071            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1072
1073            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1074            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1075                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1076                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1077
1078            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1079            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1080                    "Sending IntentFilter verification broadcast");
1081        }
1082
1083        public void receiveVerificationResponse(int verificationId) {
1084            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1085
1086            final boolean verified = ivs.isVerified();
1087
1088            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1089            final int count = filters.size();
1090            if (DEBUG_DOMAIN_VERIFICATION) {
1091                Slog.i(TAG, "Received verification response " + verificationId
1092                        + " for " + count + " filters, verified=" + verified);
1093            }
1094            for (int n=0; n<count; n++) {
1095                PackageParser.ActivityIntentInfo filter = filters.get(n);
1096                filter.setVerified(verified);
1097
1098                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1099                        + " verified with result:" + verified + " and hosts:"
1100                        + ivs.getHostsString());
1101            }
1102
1103            mIntentFilterVerificationStates.remove(verificationId);
1104
1105            final String packageName = ivs.getPackageName();
1106            IntentFilterVerificationInfo ivi = null;
1107
1108            synchronized (mPackages) {
1109                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1110            }
1111            if (ivi == null) {
1112                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1113                        + verificationId + " packageName:" + packageName);
1114                return;
1115            }
1116            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1117                    "Updating IntentFilterVerificationInfo for package " + packageName
1118                            +" verificationId:" + verificationId);
1119
1120            synchronized (mPackages) {
1121                if (verified) {
1122                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1123                } else {
1124                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1125                }
1126                scheduleWriteSettingsLocked();
1127
1128                final int userId = ivs.getUserId();
1129                if (userId != UserHandle.USER_ALL) {
1130                    final int userStatus =
1131                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1132
1133                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1134                    boolean needUpdate = false;
1135
1136                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1137                    // already been set by the User thru the Disambiguation dialog
1138                    switch (userStatus) {
1139                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1140                            if (verified) {
1141                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1142                            } else {
1143                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1144                            }
1145                            needUpdate = true;
1146                            break;
1147
1148                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1149                            if (verified) {
1150                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1151                                needUpdate = true;
1152                            }
1153                            break;
1154
1155                        default:
1156                            // Nothing to do
1157                    }
1158
1159                    if (needUpdate) {
1160                        mSettings.updateIntentFilterVerificationStatusLPw(
1161                                packageName, updatedStatus, userId);
1162                        scheduleWritePackageRestrictionsLocked(userId);
1163                    }
1164                }
1165            }
1166        }
1167
1168        @Override
1169        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1170                    ActivityIntentInfo filter, String packageName) {
1171            if (!hasValidDomains(filter)) {
1172                return false;
1173            }
1174            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1175            if (ivs == null) {
1176                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1177                        packageName);
1178            }
1179            if (DEBUG_DOMAIN_VERIFICATION) {
1180                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1181            }
1182            ivs.addFilter(filter);
1183            return true;
1184        }
1185
1186        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1187                int userId, int verificationId, String packageName) {
1188            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1189                    verifierUid, userId, packageName);
1190            ivs.setPendingState();
1191            synchronized (mPackages) {
1192                mIntentFilterVerificationStates.append(verificationId, ivs);
1193                mCurrentIntentFilterVerifications.add(verificationId);
1194            }
1195            return ivs;
1196        }
1197    }
1198
1199    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1200        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1201                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1202                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1203    }
1204
1205    // Set of pending broadcasts for aggregating enable/disable of components.
1206    static class PendingPackageBroadcasts {
1207        // for each user id, a map of <package name -> components within that package>
1208        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1209
1210        public PendingPackageBroadcasts() {
1211            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1212        }
1213
1214        public ArrayList<String> get(int userId, String packageName) {
1215            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1216            return packages.get(packageName);
1217        }
1218
1219        public void put(int userId, String packageName, ArrayList<String> components) {
1220            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1221            packages.put(packageName, components);
1222        }
1223
1224        public void remove(int userId, String packageName) {
1225            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1226            if (packages != null) {
1227                packages.remove(packageName);
1228            }
1229        }
1230
1231        public void remove(int userId) {
1232            mUidMap.remove(userId);
1233        }
1234
1235        public int userIdCount() {
1236            return mUidMap.size();
1237        }
1238
1239        public int userIdAt(int n) {
1240            return mUidMap.keyAt(n);
1241        }
1242
1243        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1244            return mUidMap.get(userId);
1245        }
1246
1247        public int size() {
1248            // total number of pending broadcast entries across all userIds
1249            int num = 0;
1250            for (int i = 0; i< mUidMap.size(); i++) {
1251                num += mUidMap.valueAt(i).size();
1252            }
1253            return num;
1254        }
1255
1256        public void clear() {
1257            mUidMap.clear();
1258        }
1259
1260        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1261            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1262            if (map == null) {
1263                map = new ArrayMap<String, ArrayList<String>>();
1264                mUidMap.put(userId, map);
1265            }
1266            return map;
1267        }
1268    }
1269    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1270
1271    // Service Connection to remote media container service to copy
1272    // package uri's from external media onto secure containers
1273    // or internal storage.
1274    private IMediaContainerService mContainerService = null;
1275
1276    static final int SEND_PENDING_BROADCAST = 1;
1277    static final int MCS_BOUND = 3;
1278    static final int END_COPY = 4;
1279    static final int INIT_COPY = 5;
1280    static final int MCS_UNBIND = 6;
1281    static final int START_CLEANING_PACKAGE = 7;
1282    static final int FIND_INSTALL_LOC = 8;
1283    static final int POST_INSTALL = 9;
1284    static final int MCS_RECONNECT = 10;
1285    static final int MCS_GIVE_UP = 11;
1286    static final int WRITE_SETTINGS = 13;
1287    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1288    static final int PACKAGE_VERIFIED = 15;
1289    static final int CHECK_PENDING_VERIFICATION = 16;
1290    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1291    static final int INTENT_FILTER_VERIFIED = 18;
1292    static final int WRITE_PACKAGE_LIST = 19;
1293    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1294
1295    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1296
1297    // Delay time in millisecs
1298    static final int BROADCAST_DELAY = 10 * 1000;
1299
1300    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1301            2 * 60 * 60 * 1000L; /* two hours */
1302
1303    static UserManagerService sUserManager;
1304
1305    // Stores a list of users whose package restrictions file needs to be updated
1306    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1307
1308    final private DefaultContainerConnection mDefContainerConn =
1309            new DefaultContainerConnection();
1310    class DefaultContainerConnection implements ServiceConnection {
1311        public void onServiceConnected(ComponentName name, IBinder service) {
1312            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1313            final IMediaContainerService imcs = IMediaContainerService.Stub
1314                    .asInterface(Binder.allowBlocking(service));
1315            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1316        }
1317
1318        public void onServiceDisconnected(ComponentName name) {
1319            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1320        }
1321    }
1322
1323    // Recordkeeping of restore-after-install operations that are currently in flight
1324    // between the Package Manager and the Backup Manager
1325    static class PostInstallData {
1326        public InstallArgs args;
1327        public PackageInstalledInfo res;
1328
1329        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1330            args = _a;
1331            res = _r;
1332        }
1333    }
1334
1335    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1336    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1337
1338    // XML tags for backup/restore of various bits of state
1339    private static final String TAG_PREFERRED_BACKUP = "pa";
1340    private static final String TAG_DEFAULT_APPS = "da";
1341    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1342
1343    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1344    private static final String TAG_ALL_GRANTS = "rt-grants";
1345    private static final String TAG_GRANT = "grant";
1346    private static final String ATTR_PACKAGE_NAME = "pkg";
1347
1348    private static final String TAG_PERMISSION = "perm";
1349    private static final String ATTR_PERMISSION_NAME = "name";
1350    private static final String ATTR_IS_GRANTED = "g";
1351    private static final String ATTR_USER_SET = "set";
1352    private static final String ATTR_USER_FIXED = "fixed";
1353    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1354
1355    // System/policy permission grants are not backed up
1356    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1357            FLAG_PERMISSION_POLICY_FIXED
1358            | FLAG_PERMISSION_SYSTEM_FIXED
1359            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1360
1361    // And we back up these user-adjusted states
1362    private static final int USER_RUNTIME_GRANT_MASK =
1363            FLAG_PERMISSION_USER_SET
1364            | FLAG_PERMISSION_USER_FIXED
1365            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1366
1367    final @Nullable String mRequiredVerifierPackage;
1368    final @NonNull String mRequiredInstallerPackage;
1369    final @NonNull String mRequiredUninstallerPackage;
1370    final @Nullable String mSetupWizardPackage;
1371    final @Nullable String mStorageManagerPackage;
1372    final @NonNull String mServicesSystemSharedLibraryPackageName;
1373    final @NonNull String mSharedSystemSharedLibraryPackageName;
1374
1375    private final PackageUsage mPackageUsage = new PackageUsage();
1376    private final CompilerStats mCompilerStats = new CompilerStats();
1377
1378    class PackageHandler extends Handler {
1379        private boolean mBound = false;
1380        final ArrayList<HandlerParams> mPendingInstalls =
1381            new ArrayList<HandlerParams>();
1382
1383        private boolean connectToService() {
1384            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1385                    " DefaultContainerService");
1386            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1387            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1388            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1389                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1390                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1391                mBound = true;
1392                return true;
1393            }
1394            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1395            return false;
1396        }
1397
1398        private void disconnectService() {
1399            mContainerService = null;
1400            mBound = false;
1401            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1402            mContext.unbindService(mDefContainerConn);
1403            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1404        }
1405
1406        PackageHandler(Looper looper) {
1407            super(looper);
1408        }
1409
1410        public void handleMessage(Message msg) {
1411            try {
1412                doHandleMessage(msg);
1413            } finally {
1414                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415            }
1416        }
1417
1418        void doHandleMessage(Message msg) {
1419            switch (msg.what) {
1420                case INIT_COPY: {
1421                    HandlerParams params = (HandlerParams) msg.obj;
1422                    int idx = mPendingInstalls.size();
1423                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1424                    // If a bind was already initiated we dont really
1425                    // need to do anything. The pending install
1426                    // will be processed later on.
1427                    if (!mBound) {
1428                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1429                                System.identityHashCode(mHandler));
1430                        // If this is the only one pending we might
1431                        // have to bind to the service again.
1432                        if (!connectToService()) {
1433                            Slog.e(TAG, "Failed to bind to media container service");
1434                            params.serviceError();
1435                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1436                                    System.identityHashCode(mHandler));
1437                            if (params.traceMethod != null) {
1438                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1439                                        params.traceCookie);
1440                            }
1441                            return;
1442                        } else {
1443                            // Once we bind to the service, the first
1444                            // pending request will be processed.
1445                            mPendingInstalls.add(idx, params);
1446                        }
1447                    } else {
1448                        mPendingInstalls.add(idx, params);
1449                        // Already bound to the service. Just make
1450                        // sure we trigger off processing the first request.
1451                        if (idx == 0) {
1452                            mHandler.sendEmptyMessage(MCS_BOUND);
1453                        }
1454                    }
1455                    break;
1456                }
1457                case MCS_BOUND: {
1458                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1459                    if (msg.obj != null) {
1460                        mContainerService = (IMediaContainerService) msg.obj;
1461                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1462                                System.identityHashCode(mHandler));
1463                    }
1464                    if (mContainerService == null) {
1465                        if (!mBound) {
1466                            // Something seriously wrong since we are not bound and we are not
1467                            // waiting for connection. Bail out.
1468                            Slog.e(TAG, "Cannot bind to media container service");
1469                            for (HandlerParams params : mPendingInstalls) {
1470                                // Indicate service bind error
1471                                params.serviceError();
1472                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1473                                        System.identityHashCode(params));
1474                                if (params.traceMethod != null) {
1475                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1476                                            params.traceMethod, params.traceCookie);
1477                                }
1478                                return;
1479                            }
1480                            mPendingInstalls.clear();
1481                        } else {
1482                            Slog.w(TAG, "Waiting to connect to media container service");
1483                        }
1484                    } else if (mPendingInstalls.size() > 0) {
1485                        HandlerParams params = mPendingInstalls.get(0);
1486                        if (params != null) {
1487                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1488                                    System.identityHashCode(params));
1489                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1490                            if (params.startCopy()) {
1491                                // We are done...  look for more work or to
1492                                // go idle.
1493                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1494                                        "Checking for more work or unbind...");
1495                                // Delete pending install
1496                                if (mPendingInstalls.size() > 0) {
1497                                    mPendingInstalls.remove(0);
1498                                }
1499                                if (mPendingInstalls.size() == 0) {
1500                                    if (mBound) {
1501                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1502                                                "Posting delayed MCS_UNBIND");
1503                                        removeMessages(MCS_UNBIND);
1504                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1505                                        // Unbind after a little delay, to avoid
1506                                        // continual thrashing.
1507                                        sendMessageDelayed(ubmsg, 10000);
1508                                    }
1509                                } else {
1510                                    // There are more pending requests in queue.
1511                                    // Just post MCS_BOUND message to trigger processing
1512                                    // of next pending install.
1513                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1514                                            "Posting MCS_BOUND for next work");
1515                                    mHandler.sendEmptyMessage(MCS_BOUND);
1516                                }
1517                            }
1518                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1519                        }
1520                    } else {
1521                        // Should never happen ideally.
1522                        Slog.w(TAG, "Empty queue");
1523                    }
1524                    break;
1525                }
1526                case MCS_RECONNECT: {
1527                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1528                    if (mPendingInstalls.size() > 0) {
1529                        if (mBound) {
1530                            disconnectService();
1531                        }
1532                        if (!connectToService()) {
1533                            Slog.e(TAG, "Failed to bind to media container service");
1534                            for (HandlerParams params : mPendingInstalls) {
1535                                // Indicate service bind error
1536                                params.serviceError();
1537                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1538                                        System.identityHashCode(params));
1539                            }
1540                            mPendingInstalls.clear();
1541                        }
1542                    }
1543                    break;
1544                }
1545                case MCS_UNBIND: {
1546                    // If there is no actual work left, then time to unbind.
1547                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1548
1549                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1550                        if (mBound) {
1551                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1552
1553                            disconnectService();
1554                        }
1555                    } else if (mPendingInstalls.size() > 0) {
1556                        // There are more pending requests in queue.
1557                        // Just post MCS_BOUND message to trigger processing
1558                        // of next pending install.
1559                        mHandler.sendEmptyMessage(MCS_BOUND);
1560                    }
1561
1562                    break;
1563                }
1564                case MCS_GIVE_UP: {
1565                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1566                    HandlerParams params = mPendingInstalls.remove(0);
1567                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1568                            System.identityHashCode(params));
1569                    break;
1570                }
1571                case SEND_PENDING_BROADCAST: {
1572                    String packages[];
1573                    ArrayList<String> components[];
1574                    int size = 0;
1575                    int uids[];
1576                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1577                    synchronized (mPackages) {
1578                        if (mPendingBroadcasts == null) {
1579                            return;
1580                        }
1581                        size = mPendingBroadcasts.size();
1582                        if (size <= 0) {
1583                            // Nothing to be done. Just return
1584                            return;
1585                        }
1586                        packages = new String[size];
1587                        components = new ArrayList[size];
1588                        uids = new int[size];
1589                        int i = 0;  // filling out the above arrays
1590
1591                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1592                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1593                            Iterator<Map.Entry<String, ArrayList<String>>> it
1594                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1595                                            .entrySet().iterator();
1596                            while (it.hasNext() && i < size) {
1597                                Map.Entry<String, ArrayList<String>> ent = it.next();
1598                                packages[i] = ent.getKey();
1599                                components[i] = ent.getValue();
1600                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1601                                uids[i] = (ps != null)
1602                                        ? UserHandle.getUid(packageUserId, ps.appId)
1603                                        : -1;
1604                                i++;
1605                            }
1606                        }
1607                        size = i;
1608                        mPendingBroadcasts.clear();
1609                    }
1610                    // Send broadcasts
1611                    for (int i = 0; i < size; i++) {
1612                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1613                    }
1614                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1615                    break;
1616                }
1617                case START_CLEANING_PACKAGE: {
1618                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1619                    final String packageName = (String)msg.obj;
1620                    final int userId = msg.arg1;
1621                    final boolean andCode = msg.arg2 != 0;
1622                    synchronized (mPackages) {
1623                        if (userId == UserHandle.USER_ALL) {
1624                            int[] users = sUserManager.getUserIds();
1625                            for (int user : users) {
1626                                mSettings.addPackageToCleanLPw(
1627                                        new PackageCleanItem(user, packageName, andCode));
1628                            }
1629                        } else {
1630                            mSettings.addPackageToCleanLPw(
1631                                    new PackageCleanItem(userId, packageName, andCode));
1632                        }
1633                    }
1634                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1635                    startCleaningPackages();
1636                } break;
1637                case POST_INSTALL: {
1638                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1639
1640                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1641                    final boolean didRestore = (msg.arg2 != 0);
1642                    mRunningInstalls.delete(msg.arg1);
1643
1644                    if (data != null) {
1645                        InstallArgs args = data.args;
1646                        PackageInstalledInfo parentRes = data.res;
1647
1648                        final boolean grantPermissions = (args.installFlags
1649                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1650                        final boolean killApp = (args.installFlags
1651                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1652                        final boolean virtualPreload = ((args.installFlags
1653                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1654                        final String[] grantedPermissions = args.installGrantPermissions;
1655
1656                        // Handle the parent package
1657                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1658                                virtualPreload, grantedPermissions, didRestore,
1659                                args.installerPackageName, args.observer);
1660
1661                        // Handle the child packages
1662                        final int childCount = (parentRes.addedChildPackages != null)
1663                                ? parentRes.addedChildPackages.size() : 0;
1664                        for (int i = 0; i < childCount; i++) {
1665                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1666                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1667                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1668                                    args.installerPackageName, args.observer);
1669                        }
1670
1671                        // Log tracing if needed
1672                        if (args.traceMethod != null) {
1673                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1674                                    args.traceCookie);
1675                        }
1676                    } else {
1677                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1678                    }
1679
1680                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1681                } break;
1682                case WRITE_SETTINGS: {
1683                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1684                    synchronized (mPackages) {
1685                        removeMessages(WRITE_SETTINGS);
1686                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1687                        mSettings.writeLPr();
1688                        mDirtyUsers.clear();
1689                    }
1690                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1691                } break;
1692                case WRITE_PACKAGE_RESTRICTIONS: {
1693                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1694                    synchronized (mPackages) {
1695                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1696                        for (int userId : mDirtyUsers) {
1697                            mSettings.writePackageRestrictionsLPr(userId);
1698                        }
1699                        mDirtyUsers.clear();
1700                    }
1701                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1702                } break;
1703                case WRITE_PACKAGE_LIST: {
1704                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1705                    synchronized (mPackages) {
1706                        removeMessages(WRITE_PACKAGE_LIST);
1707                        mSettings.writePackageListLPr(msg.arg1);
1708                    }
1709                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1710                } break;
1711                case CHECK_PENDING_VERIFICATION: {
1712                    final int verificationId = msg.arg1;
1713                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1714
1715                    if ((state != null) && !state.timeoutExtended()) {
1716                        final InstallArgs args = state.getInstallArgs();
1717                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1718
1719                        Slog.i(TAG, "Verification timed out for " + originUri);
1720                        mPendingVerification.remove(verificationId);
1721
1722                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1723
1724                        final UserHandle user = args.getUser();
1725                        if (getDefaultVerificationResponse(user)
1726                                == PackageManager.VERIFICATION_ALLOW) {
1727                            Slog.i(TAG, "Continuing with installation of " + originUri);
1728                            state.setVerifierResponse(Binder.getCallingUid(),
1729                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1730                            broadcastPackageVerified(verificationId, originUri,
1731                                    PackageManager.VERIFICATION_ALLOW, user);
1732                            try {
1733                                ret = args.copyApk(mContainerService, true);
1734                            } catch (RemoteException e) {
1735                                Slog.e(TAG, "Could not contact the ContainerService");
1736                            }
1737                        } else {
1738                            broadcastPackageVerified(verificationId, originUri,
1739                                    PackageManager.VERIFICATION_REJECT, user);
1740                        }
1741
1742                        Trace.asyncTraceEnd(
1743                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1744
1745                        processPendingInstall(args, ret);
1746                        mHandler.sendEmptyMessage(MCS_UNBIND);
1747                    }
1748                    break;
1749                }
1750                case PACKAGE_VERIFIED: {
1751                    final int verificationId = msg.arg1;
1752
1753                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1754                    if (state == null) {
1755                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1756                        break;
1757                    }
1758
1759                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1760
1761                    state.setVerifierResponse(response.callerUid, response.code);
1762
1763                    if (state.isVerificationComplete()) {
1764                        mPendingVerification.remove(verificationId);
1765
1766                        final InstallArgs args = state.getInstallArgs();
1767                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1768
1769                        int ret;
1770                        if (state.isInstallAllowed()) {
1771                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    response.code, state.getInstallArgs().getUser());
1774                            try {
1775                                ret = args.copyApk(mContainerService, true);
1776                            } catch (RemoteException e) {
1777                                Slog.e(TAG, "Could not contact the ContainerService");
1778                            }
1779                        } else {
1780                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1781                        }
1782
1783                        Trace.asyncTraceEnd(
1784                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1785
1786                        processPendingInstall(args, ret);
1787                        mHandler.sendEmptyMessage(MCS_UNBIND);
1788                    }
1789
1790                    break;
1791                }
1792                case START_INTENT_FILTER_VERIFICATIONS: {
1793                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1794                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1795                            params.replacing, params.pkg);
1796                    break;
1797                }
1798                case INTENT_FILTER_VERIFIED: {
1799                    final int verificationId = msg.arg1;
1800
1801                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1802                            verificationId);
1803                    if (state == null) {
1804                        Slog.w(TAG, "Invalid IntentFilter verification token "
1805                                + verificationId + " received");
1806                        break;
1807                    }
1808
1809                    final int userId = state.getUserId();
1810
1811                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1812                            "Processing IntentFilter verification with token:"
1813                            + verificationId + " and userId:" + userId);
1814
1815                    final IntentFilterVerificationResponse response =
1816                            (IntentFilterVerificationResponse) msg.obj;
1817
1818                    state.setVerifierResponse(response.callerUid, response.code);
1819
1820                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1821                            "IntentFilter verification with token:" + verificationId
1822                            + " and userId:" + userId
1823                            + " is settings verifier response with response code:"
1824                            + response.code);
1825
1826                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1827                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1828                                + response.getFailedDomainsString());
1829                    }
1830
1831                    if (state.isVerificationComplete()) {
1832                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1833                    } else {
1834                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1835                                "IntentFilter verification with token:" + verificationId
1836                                + " was not said to be complete");
1837                    }
1838
1839                    break;
1840                }
1841                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1842                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1843                            mInstantAppResolverConnection,
1844                            (InstantAppRequest) msg.obj,
1845                            mInstantAppInstallerActivity,
1846                            mHandler);
1847                }
1848            }
1849        }
1850    }
1851
1852    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1853        @Override
1854        public void onGidsChanged(int appId, int userId) {
1855            mHandler.post(new Runnable() {
1856                @Override
1857                public void run() {
1858                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1859                }
1860            });
1861        }
1862        @Override
1863        public void onPermissionGranted(int uid, int userId) {
1864            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1865
1866            // Not critical; if this is lost, the application has to request again.
1867            synchronized (mPackages) {
1868                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1869            }
1870        }
1871        @Override
1872        public void onInstallPermissionGranted() {
1873            synchronized (mPackages) {
1874                scheduleWriteSettingsLocked();
1875            }
1876        }
1877        @Override
1878        public void onPermissionRevoked(int uid, int userId) {
1879            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1880
1881            synchronized (mPackages) {
1882                // Critical; after this call the application should never have the permission
1883                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1884            }
1885
1886            final int appId = UserHandle.getAppId(uid);
1887            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1888        }
1889        @Override
1890        public void onInstallPermissionRevoked() {
1891            synchronized (mPackages) {
1892                scheduleWriteSettingsLocked();
1893            }
1894        }
1895        @Override
1896        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1897            synchronized (mPackages) {
1898                for (int userId : updatedUserIds) {
1899                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1900                }
1901            }
1902        }
1903        @Override
1904        public void onInstallPermissionUpdated() {
1905            synchronized (mPackages) {
1906                scheduleWriteSettingsLocked();
1907            }
1908        }
1909        @Override
1910        public void onPermissionRemoved() {
1911            synchronized (mPackages) {
1912                mSettings.writeLPr();
1913            }
1914        }
1915    };
1916
1917    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1918            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1919            boolean launchedForRestore, String installerPackage,
1920            IPackageInstallObserver2 installObserver) {
1921        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1922            // Send the removed broadcasts
1923            if (res.removedInfo != null) {
1924                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1925            }
1926
1927            // Now that we successfully installed the package, grant runtime
1928            // permissions if requested before broadcasting the install. Also
1929            // for legacy apps in permission review mode we clear the permission
1930            // review flag which is used to emulate runtime permissions for
1931            // legacy apps.
1932            if (grantPermissions) {
1933                final int callingUid = Binder.getCallingUid();
1934                mPermissionManager.grantRequestedRuntimePermissions(
1935                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1936                        mPermissionCallback);
1937            }
1938
1939            final boolean update = res.removedInfo != null
1940                    && res.removedInfo.removedPackage != null;
1941            final String installerPackageName =
1942                    res.installerPackageName != null
1943                            ? res.installerPackageName
1944                            : res.removedInfo != null
1945                                    ? res.removedInfo.installerPackageName
1946                                    : null;
1947
1948            // If this is the first time we have child packages for a disabled privileged
1949            // app that had no children, we grant requested runtime permissions to the new
1950            // children if the parent on the system image had them already granted.
1951            if (res.pkg.parentPackage != null) {
1952                final int callingUid = Binder.getCallingUid();
1953                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1954                        res.pkg, callingUid, mPermissionCallback);
1955            }
1956
1957            synchronized (mPackages) {
1958                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1959            }
1960
1961            final String packageName = res.pkg.applicationInfo.packageName;
1962
1963            // Determine the set of users who are adding this package for
1964            // the first time vs. those who are seeing an update.
1965            int[] firstUsers = EMPTY_INT_ARRAY;
1966            int[] updateUsers = EMPTY_INT_ARRAY;
1967            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1968            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1969            for (int newUser : res.newUsers) {
1970                if (ps.getInstantApp(newUser)) {
1971                    continue;
1972                }
1973                if (allNewUsers) {
1974                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1975                    continue;
1976                }
1977                boolean isNew = true;
1978                for (int origUser : res.origUsers) {
1979                    if (origUser == newUser) {
1980                        isNew = false;
1981                        break;
1982                    }
1983                }
1984                if (isNew) {
1985                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1986                } else {
1987                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1988                }
1989            }
1990
1991            // Send installed broadcasts if the package is not a static shared lib.
1992            if (res.pkg.staticSharedLibName == null) {
1993                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1994
1995                // Send added for users that see the package for the first time
1996                // sendPackageAddedForNewUsers also deals with system apps
1997                int appId = UserHandle.getAppId(res.uid);
1998                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1999                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2000                        virtualPreload /*startReceiver*/, appId, firstUsers);
2001
2002                // Send added for users that don't see the package for the first time
2003                Bundle extras = new Bundle(1);
2004                extras.putInt(Intent.EXTRA_UID, res.uid);
2005                if (update) {
2006                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2007                }
2008                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2009                        extras, 0 /*flags*/,
2010                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2011                if (installerPackageName != null) {
2012                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2013                            extras, 0 /*flags*/,
2014                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2015                }
2016
2017                // Send replaced for users that don't see the package for the first time
2018                if (update) {
2019                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2020                            packageName, extras, 0 /*flags*/,
2021                            null /*targetPackage*/, null /*finishedReceiver*/,
2022                            updateUsers);
2023                    if (installerPackageName != null) {
2024                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2025                                extras, 0 /*flags*/,
2026                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2027                    }
2028                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2029                            null /*package*/, null /*extras*/, 0 /*flags*/,
2030                            packageName /*targetPackage*/,
2031                            null /*finishedReceiver*/, updateUsers);
2032                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2033                    // First-install and we did a restore, so we're responsible for the
2034                    // first-launch broadcast.
2035                    if (DEBUG_BACKUP) {
2036                        Slog.i(TAG, "Post-restore of " + packageName
2037                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2038                    }
2039                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2040                }
2041
2042                // Send broadcast package appeared if forward locked/external for all users
2043                // treat asec-hosted packages like removable media on upgrade
2044                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2045                    if (DEBUG_INSTALL) {
2046                        Slog.i(TAG, "upgrading pkg " + res.pkg
2047                                + " is ASEC-hosted -> AVAILABLE");
2048                    }
2049                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2050                    ArrayList<String> pkgList = new ArrayList<>(1);
2051                    pkgList.add(packageName);
2052                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2053                }
2054            }
2055
2056            // Work that needs to happen on first install within each user
2057            if (firstUsers != null && firstUsers.length > 0) {
2058                synchronized (mPackages) {
2059                    for (int userId : firstUsers) {
2060                        // If this app is a browser and it's newly-installed for some
2061                        // users, clear any default-browser state in those users. The
2062                        // app's nature doesn't depend on the user, so we can just check
2063                        // its browser nature in any user and generalize.
2064                        if (packageIsBrowser(packageName, userId)) {
2065                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2066                        }
2067
2068                        // We may also need to apply pending (restored) runtime
2069                        // permission grants within these users.
2070                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2071                    }
2072                }
2073            }
2074
2075            // Log current value of "unknown sources" setting
2076            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2077                    getUnknownSourcesSettings());
2078
2079            // Remove the replaced package's older resources safely now
2080            // We delete after a gc for applications  on sdcard.
2081            if (res.removedInfo != null && res.removedInfo.args != null) {
2082                Runtime.getRuntime().gc();
2083                synchronized (mInstallLock) {
2084                    res.removedInfo.args.doPostDeleteLI(true);
2085                }
2086            } else {
2087                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2088                // and not block here.
2089                VMRuntime.getRuntime().requestConcurrentGC();
2090            }
2091
2092            // Notify DexManager that the package was installed for new users.
2093            // The updated users should already be indexed and the package code paths
2094            // should not change.
2095            // Don't notify the manager for ephemeral apps as they are not expected to
2096            // survive long enough to benefit of background optimizations.
2097            for (int userId : firstUsers) {
2098                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2099                // There's a race currently where some install events may interleave with an uninstall.
2100                // This can lead to package info being null (b/36642664).
2101                if (info != null) {
2102                    mDexManager.notifyPackageInstalled(info, userId);
2103                }
2104            }
2105        }
2106
2107        // If someone is watching installs - notify them
2108        if (installObserver != null) {
2109            try {
2110                Bundle extras = extrasForInstallResult(res);
2111                installObserver.onPackageInstalled(res.name, res.returnCode,
2112                        res.returnMsg, extras);
2113            } catch (RemoteException e) {
2114                Slog.i(TAG, "Observer no longer exists.");
2115            }
2116        }
2117    }
2118
2119    private StorageEventListener mStorageListener = new StorageEventListener() {
2120        @Override
2121        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2122            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2123                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2124                    final String volumeUuid = vol.getFsUuid();
2125
2126                    // Clean up any users or apps that were removed or recreated
2127                    // while this volume was missing
2128                    sUserManager.reconcileUsers(volumeUuid);
2129                    reconcileApps(volumeUuid);
2130
2131                    // Clean up any install sessions that expired or were
2132                    // cancelled while this volume was missing
2133                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2134
2135                    loadPrivatePackages(vol);
2136
2137                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2138                    unloadPrivatePackages(vol);
2139                }
2140            }
2141        }
2142
2143        @Override
2144        public void onVolumeForgotten(String fsUuid) {
2145            if (TextUtils.isEmpty(fsUuid)) {
2146                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2147                return;
2148            }
2149
2150            // Remove any apps installed on the forgotten volume
2151            synchronized (mPackages) {
2152                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2153                for (PackageSetting ps : packages) {
2154                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2155                    deletePackageVersioned(new VersionedPackage(ps.name,
2156                            PackageManager.VERSION_CODE_HIGHEST),
2157                            new LegacyPackageDeleteObserver(null).getBinder(),
2158                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2159                    // Try very hard to release any references to this package
2160                    // so we don't risk the system server being killed due to
2161                    // open FDs
2162                    AttributeCache.instance().removePackage(ps.name);
2163                }
2164
2165                mSettings.onVolumeForgotten(fsUuid);
2166                mSettings.writeLPr();
2167            }
2168        }
2169    };
2170
2171    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2172        Bundle extras = null;
2173        switch (res.returnCode) {
2174            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2175                extras = new Bundle();
2176                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2177                        res.origPermission);
2178                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2179                        res.origPackage);
2180                break;
2181            }
2182            case PackageManager.INSTALL_SUCCEEDED: {
2183                extras = new Bundle();
2184                extras.putBoolean(Intent.EXTRA_REPLACING,
2185                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2186                break;
2187            }
2188        }
2189        return extras;
2190    }
2191
2192    void scheduleWriteSettingsLocked() {
2193        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2194            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2195        }
2196    }
2197
2198    void scheduleWritePackageListLocked(int userId) {
2199        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2200            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2201            msg.arg1 = userId;
2202            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2203        }
2204    }
2205
2206    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2207        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2208        scheduleWritePackageRestrictionsLocked(userId);
2209    }
2210
2211    void scheduleWritePackageRestrictionsLocked(int userId) {
2212        final int[] userIds = (userId == UserHandle.USER_ALL)
2213                ? sUserManager.getUserIds() : new int[]{userId};
2214        for (int nextUserId : userIds) {
2215            if (!sUserManager.exists(nextUserId)) return;
2216            mDirtyUsers.add(nextUserId);
2217            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2218                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2219            }
2220        }
2221    }
2222
2223    public static PackageManagerService main(Context context, Installer installer,
2224            boolean factoryTest, boolean onlyCore) {
2225        // Self-check for initial settings.
2226        PackageManagerServiceCompilerMapping.checkProperties();
2227
2228        PackageManagerService m = new PackageManagerService(context, installer,
2229                factoryTest, onlyCore);
2230        m.enableSystemUserPackages();
2231        ServiceManager.addService("package", m);
2232        final PackageManagerNative pmn = m.new PackageManagerNative();
2233        ServiceManager.addService("package_native", pmn);
2234        return m;
2235    }
2236
2237    private void enableSystemUserPackages() {
2238        if (!UserManager.isSplitSystemUser()) {
2239            return;
2240        }
2241        // For system user, enable apps based on the following conditions:
2242        // - app is whitelisted or belong to one of these groups:
2243        //   -- system app which has no launcher icons
2244        //   -- system app which has INTERACT_ACROSS_USERS permission
2245        //   -- system IME app
2246        // - app is not in the blacklist
2247        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2248        Set<String> enableApps = new ArraySet<>();
2249        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2250                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2251                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2252        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2253        enableApps.addAll(wlApps);
2254        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2255                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2256        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2257        enableApps.removeAll(blApps);
2258        Log.i(TAG, "Applications installed for system user: " + enableApps);
2259        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2260                UserHandle.SYSTEM);
2261        final int allAppsSize = allAps.size();
2262        synchronized (mPackages) {
2263            for (int i = 0; i < allAppsSize; i++) {
2264                String pName = allAps.get(i);
2265                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2266                // Should not happen, but we shouldn't be failing if it does
2267                if (pkgSetting == null) {
2268                    continue;
2269                }
2270                boolean install = enableApps.contains(pName);
2271                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2272                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2273                            + " for system user");
2274                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2275                }
2276            }
2277            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2278        }
2279    }
2280
2281    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2282        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2283                Context.DISPLAY_SERVICE);
2284        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2285    }
2286
2287    /**
2288     * Requests that files preopted on a secondary system partition be copied to the data partition
2289     * if possible.  Note that the actual copying of the files is accomplished by init for security
2290     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2291     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2292     */
2293    private static void requestCopyPreoptedFiles() {
2294        final int WAIT_TIME_MS = 100;
2295        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2296        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2297            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2298            // We will wait for up to 100 seconds.
2299            final long timeStart = SystemClock.uptimeMillis();
2300            final long timeEnd = timeStart + 100 * 1000;
2301            long timeNow = timeStart;
2302            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2303                try {
2304                    Thread.sleep(WAIT_TIME_MS);
2305                } catch (InterruptedException e) {
2306                    // Do nothing
2307                }
2308                timeNow = SystemClock.uptimeMillis();
2309                if (timeNow > timeEnd) {
2310                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2311                    Slog.wtf(TAG, "cppreopt did not finish!");
2312                    break;
2313                }
2314            }
2315
2316            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2317        }
2318    }
2319
2320    public PackageManagerService(Context context, Installer installer,
2321            boolean factoryTest, boolean onlyCore) {
2322        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2323        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2324        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2325                SystemClock.uptimeMillis());
2326
2327        if (mSdkVersion <= 0) {
2328            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2329        }
2330
2331        mContext = context;
2332
2333        mFactoryTest = factoryTest;
2334        mOnlyCore = onlyCore;
2335        mMetrics = new DisplayMetrics();
2336        mInstaller = installer;
2337
2338        // Create sub-components that provide services / data. Order here is important.
2339        synchronized (mInstallLock) {
2340        synchronized (mPackages) {
2341            // Expose private service for system components to use.
2342            LocalServices.addService(
2343                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2344            sUserManager = new UserManagerService(context, this,
2345                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2346            mPermissionManager = PermissionManagerService.create(context,
2347                    new DefaultPermissionGrantedCallback() {
2348                        @Override
2349                        public void onDefaultRuntimePermissionsGranted(int userId) {
2350                            synchronized(mPackages) {
2351                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2352                            }
2353                        }
2354                    }, mPackages /*externalLock*/);
2355            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2356            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2357        }
2358        }
2359        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2360                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2361        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2362                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2363        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2364                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2365        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2366                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2367        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2368                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2369        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2370                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2371
2372        String separateProcesses = SystemProperties.get("debug.separate_processes");
2373        if (separateProcesses != null && separateProcesses.length() > 0) {
2374            if ("*".equals(separateProcesses)) {
2375                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2376                mSeparateProcesses = null;
2377                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2378            } else {
2379                mDefParseFlags = 0;
2380                mSeparateProcesses = separateProcesses.split(",");
2381                Slog.w(TAG, "Running with debug.separate_processes: "
2382                        + separateProcesses);
2383            }
2384        } else {
2385            mDefParseFlags = 0;
2386            mSeparateProcesses = null;
2387        }
2388
2389        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2390                "*dexopt*");
2391        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2392                installer, mInstallLock);
2393        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2394                dexManagerListener);
2395        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2396
2397        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2398                FgThread.get().getLooper());
2399
2400        getDefaultDisplayMetrics(context, mMetrics);
2401
2402        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2403        SystemConfig systemConfig = SystemConfig.getInstance();
2404        mAvailableFeatures = systemConfig.getAvailableFeatures();
2405        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2406
2407        mProtectedPackages = new ProtectedPackages(mContext);
2408
2409        synchronized (mInstallLock) {
2410        // writer
2411        synchronized (mPackages) {
2412            mHandlerThread = new ServiceThread(TAG,
2413                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2414            mHandlerThread.start();
2415            mHandler = new PackageHandler(mHandlerThread.getLooper());
2416            mProcessLoggingHandler = new ProcessLoggingHandler();
2417            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2418            mInstantAppRegistry = new InstantAppRegistry(this);
2419
2420            File dataDir = Environment.getDataDirectory();
2421            mAppInstallDir = new File(dataDir, "app");
2422            mAppLib32InstallDir = new File(dataDir, "app-lib");
2423            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2424
2425            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2426            final int builtInLibCount = libConfig.size();
2427            for (int i = 0; i < builtInLibCount; i++) {
2428                String name = libConfig.keyAt(i);
2429                String path = libConfig.valueAt(i);
2430                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2431                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2432            }
2433
2434            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2435
2436            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2437            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2438            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2439
2440            // Clean up orphaned packages for which the code path doesn't exist
2441            // and they are an update to a system app - caused by bug/32321269
2442            final int packageSettingCount = mSettings.mPackages.size();
2443            for (int i = packageSettingCount - 1; i >= 0; i--) {
2444                PackageSetting ps = mSettings.mPackages.valueAt(i);
2445                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2446                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2447                    mSettings.mPackages.removeAt(i);
2448                    mSettings.enableSystemPackageLPw(ps.name);
2449                }
2450            }
2451
2452            if (mFirstBoot) {
2453                requestCopyPreoptedFiles();
2454            }
2455
2456            String customResolverActivity = Resources.getSystem().getString(
2457                    R.string.config_customResolverActivity);
2458            if (TextUtils.isEmpty(customResolverActivity)) {
2459                customResolverActivity = null;
2460            } else {
2461                mCustomResolverComponentName = ComponentName.unflattenFromString(
2462                        customResolverActivity);
2463            }
2464
2465            long startTime = SystemClock.uptimeMillis();
2466
2467            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2468                    startTime);
2469
2470            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2471            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2472
2473            if (bootClassPath == null) {
2474                Slog.w(TAG, "No BOOTCLASSPATH found!");
2475            }
2476
2477            if (systemServerClassPath == null) {
2478                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2479            }
2480
2481            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2482
2483            final VersionInfo ver = mSettings.getInternalVersion();
2484            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2485            if (mIsUpgrade) {
2486                logCriticalInfo(Log.INFO,
2487                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2488            }
2489
2490            // when upgrading from pre-M, promote system app permissions from install to runtime
2491            mPromoteSystemApps =
2492                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2493
2494            // When upgrading from pre-N, we need to handle package extraction like first boot,
2495            // as there is no profiling data available.
2496            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2497
2498            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2499
2500            // save off the names of pre-existing system packages prior to scanning; we don't
2501            // want to automatically grant runtime permissions for new system apps
2502            if (mPromoteSystemApps) {
2503                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2504                while (pkgSettingIter.hasNext()) {
2505                    PackageSetting ps = pkgSettingIter.next();
2506                    if (isSystemApp(ps)) {
2507                        mExistingSystemPackages.add(ps.name);
2508                    }
2509                }
2510            }
2511
2512            mCacheDir = preparePackageParserCache(mIsUpgrade);
2513
2514            // Set flag to monitor and not change apk file paths when
2515            // scanning install directories.
2516            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2517
2518            if (mIsUpgrade || mFirstBoot) {
2519                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2520            }
2521
2522            // Collect vendor overlay packages. (Do this before scanning any apps.)
2523            // For security and version matching reason, only consider
2524            // overlay packages if they reside in the right directory.
2525            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2526                    mDefParseFlags
2527                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2528                    scanFlags
2529                    | SCAN_AS_SYSTEM
2530                    | SCAN_TRUSTED_OVERLAY,
2531                    0);
2532
2533            mParallelPackageParserCallback.findStaticOverlayPackages();
2534
2535            // Find base frameworks (resource packages without code).
2536            scanDirTracedLI(frameworkDir,
2537                    mDefParseFlags
2538                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2539                    scanFlags
2540                    | SCAN_NO_DEX
2541                    | SCAN_AS_SYSTEM
2542                    | SCAN_AS_PRIVILEGED,
2543                    0);
2544
2545            // Collected privileged system packages.
2546            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2547            scanDirTracedLI(privilegedAppDir,
2548                    mDefParseFlags
2549                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2550                    scanFlags
2551                    | SCAN_AS_SYSTEM
2552                    | SCAN_AS_PRIVILEGED,
2553                    0);
2554
2555            // Collect ordinary system packages.
2556            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2557            scanDirTracedLI(systemAppDir,
2558                    mDefParseFlags
2559                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2560                    scanFlags
2561                    | SCAN_AS_SYSTEM,
2562                    0);
2563
2564            // Collect all vendor packages.
2565            File vendorAppDir = new File("/vendor/app");
2566            try {
2567                vendorAppDir = vendorAppDir.getCanonicalFile();
2568            } catch (IOException e) {
2569                // failed to look up canonical path, continue with original one
2570            }
2571            scanDirTracedLI(vendorAppDir,
2572                    mDefParseFlags
2573                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2574                    scanFlags
2575                    | SCAN_AS_SYSTEM,
2576                    0);
2577
2578            // Collect all OEM packages.
2579            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2580            scanDirTracedLI(oemAppDir,
2581                    mDefParseFlags
2582                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2583                    scanFlags
2584                    | SCAN_AS_SYSTEM
2585                    | SCAN_AS_OEM,
2586                    0);
2587
2588            // Prune any system packages that no longer exist.
2589            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2590            // Stub packages must either be replaced with full versions in the /data
2591            // partition or be disabled.
2592            final List<String> stubSystemApps = new ArrayList<>();
2593            if (!mOnlyCore) {
2594                // do this first before mucking with mPackages for the "expecting better" case
2595                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2596                while (pkgIterator.hasNext()) {
2597                    final PackageParser.Package pkg = pkgIterator.next();
2598                    if (pkg.isStub) {
2599                        stubSystemApps.add(pkg.packageName);
2600                    }
2601                }
2602
2603                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2604                while (psit.hasNext()) {
2605                    PackageSetting ps = psit.next();
2606
2607                    /*
2608                     * If this is not a system app, it can't be a
2609                     * disable system app.
2610                     */
2611                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2612                        continue;
2613                    }
2614
2615                    /*
2616                     * If the package is scanned, it's not erased.
2617                     */
2618                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2619                    if (scannedPkg != null) {
2620                        /*
2621                         * If the system app is both scanned and in the
2622                         * disabled packages list, then it must have been
2623                         * added via OTA. Remove it from the currently
2624                         * scanned package so the previously user-installed
2625                         * application can be scanned.
2626                         */
2627                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2628                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2629                                    + ps.name + "; removing system app.  Last known codePath="
2630                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2631                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2632                                    + scannedPkg.getLongVersionCode());
2633                            removePackageLI(scannedPkg, true);
2634                            mExpectingBetter.put(ps.name, ps.codePath);
2635                        }
2636
2637                        continue;
2638                    }
2639
2640                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2641                        psit.remove();
2642                        logCriticalInfo(Log.WARN, "System package " + ps.name
2643                                + " no longer exists; it's data will be wiped");
2644                        // Actual deletion of code and data will be handled by later
2645                        // reconciliation step
2646                    } else {
2647                        // we still have a disabled system package, but, it still might have
2648                        // been removed. check the code path still exists and check there's
2649                        // still a package. the latter can happen if an OTA keeps the same
2650                        // code path, but, changes the package name.
2651                        final PackageSetting disabledPs =
2652                                mSettings.getDisabledSystemPkgLPr(ps.name);
2653                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2654                                || disabledPs.pkg == null) {
2655                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2656                        }
2657                    }
2658                }
2659            }
2660
2661            //look for any incomplete package installations
2662            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2663            for (int i = 0; i < deletePkgsList.size(); i++) {
2664                // Actual deletion of code and data will be handled by later
2665                // reconciliation step
2666                final String packageName = deletePkgsList.get(i).name;
2667                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2668                synchronized (mPackages) {
2669                    mSettings.removePackageLPw(packageName);
2670                }
2671            }
2672
2673            //delete tmp files
2674            deleteTempPackageFiles();
2675
2676            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2677
2678            // Remove any shared userIDs that have no associated packages
2679            mSettings.pruneSharedUsersLPw();
2680            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2681            final int systemPackagesCount = mPackages.size();
2682            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2683                    + " ms, packageCount: " + systemPackagesCount
2684                    + " , timePerPackage: "
2685                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2686                    + " , cached: " + cachedSystemApps);
2687            if (mIsUpgrade && systemPackagesCount > 0) {
2688                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2689                        ((int) systemScanTime) / systemPackagesCount);
2690            }
2691            if (!mOnlyCore) {
2692                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2693                        SystemClock.uptimeMillis());
2694                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2695
2696                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2697                        | PackageParser.PARSE_FORWARD_LOCK,
2698                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2699
2700                // Remove disable package settings for updated system apps that were
2701                // removed via an OTA. If the update is no longer present, remove the
2702                // app completely. Otherwise, revoke their system privileges.
2703                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2704                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2705                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2706
2707                    final String msg;
2708                    if (deletedPkg == null) {
2709                        // should have found an update, but, we didn't; remove everything
2710                        msg = "Updated system package " + deletedAppName
2711                                + " no longer exists; removing its data";
2712                        // Actual deletion of code and data will be handled by later
2713                        // reconciliation step
2714                    } else {
2715                        // found an update; revoke system privileges
2716                        msg = "Updated system package + " + deletedAppName
2717                                + " no longer exists; revoking system privileges";
2718
2719                        // Don't do anything if a stub is removed from the system image. If
2720                        // we were to remove the uncompressed version from the /data partition,
2721                        // this is where it'd be done.
2722
2723                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2724                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2725                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2726                    }
2727                    logCriticalInfo(Log.WARN, msg);
2728                }
2729
2730                /*
2731                 * Make sure all system apps that we expected to appear on
2732                 * the userdata partition actually showed up. If they never
2733                 * appeared, crawl back and revive the system version.
2734                 */
2735                for (int i = 0; i < mExpectingBetter.size(); i++) {
2736                    final String packageName = mExpectingBetter.keyAt(i);
2737                    if (!mPackages.containsKey(packageName)) {
2738                        final File scanFile = mExpectingBetter.valueAt(i);
2739
2740                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2741                                + " but never showed up; reverting to system");
2742
2743                        final @ParseFlags int reparseFlags;
2744                        final @ScanFlags int rescanFlags;
2745                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2746                            reparseFlags =
2747                                    mDefParseFlags |
2748                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2749                            rescanFlags =
2750                                    scanFlags
2751                                    | SCAN_AS_SYSTEM
2752                                    | SCAN_AS_PRIVILEGED;
2753                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2754                            reparseFlags =
2755                                    mDefParseFlags |
2756                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2757                            rescanFlags =
2758                                    scanFlags
2759                                    | SCAN_AS_SYSTEM;
2760                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2761                            reparseFlags =
2762                                    mDefParseFlags |
2763                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2764                            rescanFlags =
2765                                    scanFlags
2766                                    | SCAN_AS_SYSTEM;
2767                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2768                            reparseFlags =
2769                                    mDefParseFlags |
2770                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2771                            rescanFlags =
2772                                    scanFlags
2773                                    | SCAN_AS_SYSTEM
2774                                    | SCAN_AS_OEM;
2775                        } else {
2776                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2777                            continue;
2778                        }
2779
2780                        mSettings.enableSystemPackageLPw(packageName);
2781
2782                        try {
2783                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2784                        } catch (PackageManagerException e) {
2785                            Slog.e(TAG, "Failed to parse original system package: "
2786                                    + e.getMessage());
2787                        }
2788                    }
2789                }
2790
2791                // Uncompress and install any stubbed system applications.
2792                // This must be done last to ensure all stubs are replaced or disabled.
2793                decompressSystemApplications(stubSystemApps, scanFlags);
2794
2795                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2796                                - cachedSystemApps;
2797
2798                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2799                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2800                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2801                        + " ms, packageCount: " + dataPackagesCount
2802                        + " , timePerPackage: "
2803                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2804                        + " , cached: " + cachedNonSystemApps);
2805                if (mIsUpgrade && dataPackagesCount > 0) {
2806                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2807                            ((int) dataScanTime) / dataPackagesCount);
2808                }
2809            }
2810            mExpectingBetter.clear();
2811
2812            // Resolve the storage manager.
2813            mStorageManagerPackage = getStorageManagerPackageName();
2814
2815            // Resolve protected action filters. Only the setup wizard is allowed to
2816            // have a high priority filter for these actions.
2817            mSetupWizardPackage = getSetupWizardPackageName();
2818            if (mProtectedFilters.size() > 0) {
2819                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2820                    Slog.i(TAG, "No setup wizard;"
2821                        + " All protected intents capped to priority 0");
2822                }
2823                for (ActivityIntentInfo filter : mProtectedFilters) {
2824                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2825                        if (DEBUG_FILTERS) {
2826                            Slog.i(TAG, "Found setup wizard;"
2827                                + " allow priority " + filter.getPriority() + ";"
2828                                + " package: " + filter.activity.info.packageName
2829                                + " activity: " + filter.activity.className
2830                                + " priority: " + filter.getPriority());
2831                        }
2832                        // skip setup wizard; allow it to keep the high priority filter
2833                        continue;
2834                    }
2835                    if (DEBUG_FILTERS) {
2836                        Slog.i(TAG, "Protected action; cap priority to 0;"
2837                                + " package: " + filter.activity.info.packageName
2838                                + " activity: " + filter.activity.className
2839                                + " origPrio: " + filter.getPriority());
2840                    }
2841                    filter.setPriority(0);
2842                }
2843            }
2844            mDeferProtectedFilters = false;
2845            mProtectedFilters.clear();
2846
2847            // Now that we know all of the shared libraries, update all clients to have
2848            // the correct library paths.
2849            updateAllSharedLibrariesLPw(null);
2850
2851            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2852                // NOTE: We ignore potential failures here during a system scan (like
2853                // the rest of the commands above) because there's precious little we
2854                // can do about it. A settings error is reported, though.
2855                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2856            }
2857
2858            // Now that we know all the packages we are keeping,
2859            // read and update their last usage times.
2860            mPackageUsage.read(mPackages);
2861            mCompilerStats.read();
2862
2863            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2864                    SystemClock.uptimeMillis());
2865            Slog.i(TAG, "Time to scan packages: "
2866                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2867                    + " seconds");
2868
2869            // If the platform SDK has changed since the last time we booted,
2870            // we need to re-grant app permission to catch any new ones that
2871            // appear.  This is really a hack, and means that apps can in some
2872            // cases get permissions that the user didn't initially explicitly
2873            // allow...  it would be nice to have some better way to handle
2874            // this situation.
2875            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2876            if (sdkUpdated) {
2877                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2878                        + mSdkVersion + "; regranting permissions for internal storage");
2879            }
2880            mPermissionManager.updateAllPermissions(
2881                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2882                    mPermissionCallback);
2883            ver.sdkVersion = mSdkVersion;
2884
2885            // If this is the first boot or an update from pre-M, and it is a normal
2886            // boot, then we need to initialize the default preferred apps across
2887            // all defined users.
2888            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2889                for (UserInfo user : sUserManager.getUsers(true)) {
2890                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2891                    applyFactoryDefaultBrowserLPw(user.id);
2892                    primeDomainVerificationsLPw(user.id);
2893                }
2894            }
2895
2896            // Prepare storage for system user really early during boot,
2897            // since core system apps like SettingsProvider and SystemUI
2898            // can't wait for user to start
2899            final int storageFlags;
2900            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2901                storageFlags = StorageManager.FLAG_STORAGE_DE;
2902            } else {
2903                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2904            }
2905            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2906                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2907                    true /* onlyCoreApps */);
2908            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2909                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2910                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2911                traceLog.traceBegin("AppDataFixup");
2912                try {
2913                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2914                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2915                } catch (InstallerException e) {
2916                    Slog.w(TAG, "Trouble fixing GIDs", e);
2917                }
2918                traceLog.traceEnd();
2919
2920                traceLog.traceBegin("AppDataPrepare");
2921                if (deferPackages == null || deferPackages.isEmpty()) {
2922                    return;
2923                }
2924                int count = 0;
2925                for (String pkgName : deferPackages) {
2926                    PackageParser.Package pkg = null;
2927                    synchronized (mPackages) {
2928                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2929                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2930                            pkg = ps.pkg;
2931                        }
2932                    }
2933                    if (pkg != null) {
2934                        synchronized (mInstallLock) {
2935                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2936                                    true /* maybeMigrateAppData */);
2937                        }
2938                        count++;
2939                    }
2940                }
2941                traceLog.traceEnd();
2942                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2943            }, "prepareAppData");
2944
2945            // If this is first boot after an OTA, and a normal boot, then
2946            // we need to clear code cache directories.
2947            // Note that we do *not* clear the application profiles. These remain valid
2948            // across OTAs and are used to drive profile verification (post OTA) and
2949            // profile compilation (without waiting to collect a fresh set of profiles).
2950            if (mIsUpgrade && !onlyCore) {
2951                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2952                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2953                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2954                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2955                        // No apps are running this early, so no need to freeze
2956                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2957                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2958                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2959                    }
2960                }
2961                ver.fingerprint = Build.FINGERPRINT;
2962            }
2963
2964            checkDefaultBrowser();
2965
2966            // clear only after permissions and other defaults have been updated
2967            mExistingSystemPackages.clear();
2968            mPromoteSystemApps = false;
2969
2970            // All the changes are done during package scanning.
2971            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2972
2973            // can downgrade to reader
2974            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2975            mSettings.writeLPr();
2976            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2977            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2978                    SystemClock.uptimeMillis());
2979
2980            if (!mOnlyCore) {
2981                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2982                mRequiredInstallerPackage = getRequiredInstallerLPr();
2983                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2984                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2985                if (mIntentFilterVerifierComponent != null) {
2986                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2987                            mIntentFilterVerifierComponent);
2988                } else {
2989                    mIntentFilterVerifier = null;
2990                }
2991                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2992                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2993                        SharedLibraryInfo.VERSION_UNDEFINED);
2994                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2995                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2996                        SharedLibraryInfo.VERSION_UNDEFINED);
2997            } else {
2998                mRequiredVerifierPackage = null;
2999                mRequiredInstallerPackage = null;
3000                mRequiredUninstallerPackage = null;
3001                mIntentFilterVerifierComponent = null;
3002                mIntentFilterVerifier = null;
3003                mServicesSystemSharedLibraryPackageName = null;
3004                mSharedSystemSharedLibraryPackageName = null;
3005            }
3006
3007            mInstallerService = new PackageInstallerService(context, this);
3008            final Pair<ComponentName, String> instantAppResolverComponent =
3009                    getInstantAppResolverLPr();
3010            if (instantAppResolverComponent != null) {
3011                if (DEBUG_EPHEMERAL) {
3012                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3013                }
3014                mInstantAppResolverConnection = new EphemeralResolverConnection(
3015                        mContext, instantAppResolverComponent.first,
3016                        instantAppResolverComponent.second);
3017                mInstantAppResolverSettingsComponent =
3018                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3019            } else {
3020                mInstantAppResolverConnection = null;
3021                mInstantAppResolverSettingsComponent = null;
3022            }
3023            updateInstantAppInstallerLocked(null);
3024
3025            // Read and update the usage of dex files.
3026            // Do this at the end of PM init so that all the packages have their
3027            // data directory reconciled.
3028            // At this point we know the code paths of the packages, so we can validate
3029            // the disk file and build the internal cache.
3030            // The usage file is expected to be small so loading and verifying it
3031            // should take a fairly small time compare to the other activities (e.g. package
3032            // scanning).
3033            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3034            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3035            for (int userId : currentUserIds) {
3036                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3037            }
3038            mDexManager.load(userPackages);
3039            if (mIsUpgrade) {
3040                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3041                        (int) (SystemClock.uptimeMillis() - startTime));
3042            }
3043        } // synchronized (mPackages)
3044        } // synchronized (mInstallLock)
3045
3046        // Now after opening every single application zip, make sure they
3047        // are all flushed.  Not really needed, but keeps things nice and
3048        // tidy.
3049        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3050        Runtime.getRuntime().gc();
3051        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3052
3053        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3054        FallbackCategoryProvider.loadFallbacks();
3055        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3056
3057        // The initial scanning above does many calls into installd while
3058        // holding the mPackages lock, but we're mostly interested in yelling
3059        // once we have a booted system.
3060        mInstaller.setWarnIfHeld(mPackages);
3061
3062        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3063    }
3064
3065    /**
3066     * Uncompress and install stub applications.
3067     * <p>In order to save space on the system partition, some applications are shipped in a
3068     * compressed form. In addition the compressed bits for the full application, the
3069     * system image contains a tiny stub comprised of only the Android manifest.
3070     * <p>During the first boot, attempt to uncompress and install the full application. If
3071     * the application can't be installed for any reason, disable the stub and prevent
3072     * uncompressing the full application during future boots.
3073     * <p>In order to forcefully attempt an installation of a full application, go to app
3074     * settings and enable the application.
3075     */
3076    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3077        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3078            final String pkgName = stubSystemApps.get(i);
3079            // skip if the system package is already disabled
3080            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3081                stubSystemApps.remove(i);
3082                continue;
3083            }
3084            // skip if the package isn't installed (?!); this should never happen
3085            final PackageParser.Package pkg = mPackages.get(pkgName);
3086            if (pkg == null) {
3087                stubSystemApps.remove(i);
3088                continue;
3089            }
3090            // skip if the package has been disabled by the user
3091            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3092            if (ps != null) {
3093                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3094                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3095                    stubSystemApps.remove(i);
3096                    continue;
3097                }
3098            }
3099
3100            if (DEBUG_COMPRESSION) {
3101                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3102            }
3103
3104            // uncompress the binary to its eventual destination on /data
3105            final File scanFile = decompressPackage(pkg);
3106            if (scanFile == null) {
3107                continue;
3108            }
3109
3110            // install the package to replace the stub on /system
3111            try {
3112                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3113                removePackageLI(pkg, true /*chatty*/);
3114                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3115                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3116                        UserHandle.USER_SYSTEM, "android");
3117                stubSystemApps.remove(i);
3118                continue;
3119            } catch (PackageManagerException e) {
3120                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3121            }
3122
3123            // any failed attempt to install the package will be cleaned up later
3124        }
3125
3126        // disable any stub still left; these failed to install the full application
3127        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3128            final String pkgName = stubSystemApps.get(i);
3129            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3130            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3131                    UserHandle.USER_SYSTEM, "android");
3132            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3133        }
3134    }
3135
3136    /**
3137     * Decompresses the given package on the system image onto
3138     * the /data partition.
3139     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3140     */
3141    private File decompressPackage(PackageParser.Package pkg) {
3142        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3143        if (compressedFiles == null || compressedFiles.length == 0) {
3144            if (DEBUG_COMPRESSION) {
3145                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3146            }
3147            return null;
3148        }
3149        final File dstCodePath =
3150                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3151        int ret = PackageManager.INSTALL_SUCCEEDED;
3152        try {
3153            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3154            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3155            for (File srcFile : compressedFiles) {
3156                final String srcFileName = srcFile.getName();
3157                final String dstFileName = srcFileName.substring(
3158                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3159                final File dstFile = new File(dstCodePath, dstFileName);
3160                ret = decompressFile(srcFile, dstFile);
3161                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3162                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3163                            + "; pkg: " + pkg.packageName
3164                            + ", file: " + dstFileName);
3165                    break;
3166                }
3167            }
3168        } catch (ErrnoException e) {
3169            logCriticalInfo(Log.ERROR, "Failed to decompress"
3170                    + "; pkg: " + pkg.packageName
3171                    + ", err: " + e.errno);
3172        }
3173        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3174            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3175            NativeLibraryHelper.Handle handle = null;
3176            try {
3177                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3178                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3179                        null /*abiOverride*/);
3180            } catch (IOException e) {
3181                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3182                        + "; pkg: " + pkg.packageName);
3183                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3184            } finally {
3185                IoUtils.closeQuietly(handle);
3186            }
3187        }
3188        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3189            if (dstCodePath == null || !dstCodePath.exists()) {
3190                return null;
3191            }
3192            removeCodePathLI(dstCodePath);
3193            return null;
3194        }
3195
3196        return dstCodePath;
3197    }
3198
3199    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3200        // we're only interested in updating the installer appliction when 1) it's not
3201        // already set or 2) the modified package is the installer
3202        if (mInstantAppInstallerActivity != null
3203                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3204                        .equals(modifiedPackage)) {
3205            return;
3206        }
3207        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3208    }
3209
3210    private static File preparePackageParserCache(boolean isUpgrade) {
3211        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3212            return null;
3213        }
3214
3215        // Disable package parsing on eng builds to allow for faster incremental development.
3216        if (Build.IS_ENG) {
3217            return null;
3218        }
3219
3220        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3221            Slog.i(TAG, "Disabling package parser cache due to system property.");
3222            return null;
3223        }
3224
3225        // The base directory for the package parser cache lives under /data/system/.
3226        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3227                "package_cache");
3228        if (cacheBaseDir == null) {
3229            return null;
3230        }
3231
3232        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3233        // This also serves to "GC" unused entries when the package cache version changes (which
3234        // can only happen during upgrades).
3235        if (isUpgrade) {
3236            FileUtils.deleteContents(cacheBaseDir);
3237        }
3238
3239
3240        // Return the versioned package cache directory. This is something like
3241        // "/data/system/package_cache/1"
3242        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3243
3244        // The following is a workaround to aid development on non-numbered userdebug
3245        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3246        // the system partition is newer.
3247        //
3248        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3249        // that starts with "eng." to signify that this is an engineering build and not
3250        // destined for release.
3251        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3252            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3253
3254            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3255            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3256            // in general and should not be used for production changes. In this specific case,
3257            // we know that they will work.
3258            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3259            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3260                FileUtils.deleteContents(cacheBaseDir);
3261                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3262            }
3263        }
3264
3265        return cacheDir;
3266    }
3267
3268    @Override
3269    public boolean isFirstBoot() {
3270        // allow instant applications
3271        return mFirstBoot;
3272    }
3273
3274    @Override
3275    public boolean isOnlyCoreApps() {
3276        // allow instant applications
3277        return mOnlyCore;
3278    }
3279
3280    @Override
3281    public boolean isUpgrade() {
3282        // allow instant applications
3283        // The system property allows testing ota flow when upgraded to the same image.
3284        return mIsUpgrade || SystemProperties.getBoolean(
3285                "persist.pm.mock-upgrade", false /* default */);
3286    }
3287
3288    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3289        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3290
3291        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3292                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3293                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3294        if (matches.size() == 1) {
3295            return matches.get(0).getComponentInfo().packageName;
3296        } else if (matches.size() == 0) {
3297            Log.e(TAG, "There should probably be a verifier, but, none were found");
3298            return null;
3299        }
3300        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3301    }
3302
3303    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3304        synchronized (mPackages) {
3305            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3306            if (libraryEntry == null) {
3307                throw new IllegalStateException("Missing required shared library:" + name);
3308            }
3309            return libraryEntry.apk;
3310        }
3311    }
3312
3313    private @NonNull String getRequiredInstallerLPr() {
3314        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3315        intent.addCategory(Intent.CATEGORY_DEFAULT);
3316        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3317
3318        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3319                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3320                UserHandle.USER_SYSTEM);
3321        if (matches.size() == 1) {
3322            ResolveInfo resolveInfo = matches.get(0);
3323            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3324                throw new RuntimeException("The installer must be a privileged app");
3325            }
3326            return matches.get(0).getComponentInfo().packageName;
3327        } else {
3328            throw new RuntimeException("There must be exactly one installer; found " + matches);
3329        }
3330    }
3331
3332    private @NonNull String getRequiredUninstallerLPr() {
3333        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3334        intent.addCategory(Intent.CATEGORY_DEFAULT);
3335        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3336
3337        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3338                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3339                UserHandle.USER_SYSTEM);
3340        if (resolveInfo == null ||
3341                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3342            throw new RuntimeException("There must be exactly one uninstaller; found "
3343                    + resolveInfo);
3344        }
3345        return resolveInfo.getComponentInfo().packageName;
3346    }
3347
3348    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3349        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3350
3351        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3352                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3353                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3354        ResolveInfo best = null;
3355        final int N = matches.size();
3356        for (int i = 0; i < N; i++) {
3357            final ResolveInfo cur = matches.get(i);
3358            final String packageName = cur.getComponentInfo().packageName;
3359            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3360                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3361                continue;
3362            }
3363
3364            if (best == null || cur.priority > best.priority) {
3365                best = cur;
3366            }
3367        }
3368
3369        if (best != null) {
3370            return best.getComponentInfo().getComponentName();
3371        }
3372        Slog.w(TAG, "Intent filter verifier not found");
3373        return null;
3374    }
3375
3376    @Override
3377    public @Nullable ComponentName getInstantAppResolverComponent() {
3378        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3379            return null;
3380        }
3381        synchronized (mPackages) {
3382            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3383            if (instantAppResolver == null) {
3384                return null;
3385            }
3386            return instantAppResolver.first;
3387        }
3388    }
3389
3390    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3391        final String[] packageArray =
3392                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3393        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3394            if (DEBUG_EPHEMERAL) {
3395                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3396            }
3397            return null;
3398        }
3399
3400        final int callingUid = Binder.getCallingUid();
3401        final int resolveFlags =
3402                MATCH_DIRECT_BOOT_AWARE
3403                | MATCH_DIRECT_BOOT_UNAWARE
3404                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3405        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3406        final Intent resolverIntent = new Intent(actionName);
3407        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3408                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3409        // temporarily look for the old action
3410        if (resolvers.size() == 0) {
3411            if (DEBUG_EPHEMERAL) {
3412                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3413            }
3414            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3415            resolverIntent.setAction(actionName);
3416            resolvers = queryIntentServicesInternal(resolverIntent, null,
3417                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3418        }
3419        final int N = resolvers.size();
3420        if (N == 0) {
3421            if (DEBUG_EPHEMERAL) {
3422                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3423            }
3424            return null;
3425        }
3426
3427        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3428        for (int i = 0; i < N; i++) {
3429            final ResolveInfo info = resolvers.get(i);
3430
3431            if (info.serviceInfo == null) {
3432                continue;
3433            }
3434
3435            final String packageName = info.serviceInfo.packageName;
3436            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3437                if (DEBUG_EPHEMERAL) {
3438                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3439                            + " pkg: " + packageName + ", info:" + info);
3440                }
3441                continue;
3442            }
3443
3444            if (DEBUG_EPHEMERAL) {
3445                Slog.v(TAG, "Ephemeral resolver found;"
3446                        + " pkg: " + packageName + ", info:" + info);
3447            }
3448            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3449        }
3450        if (DEBUG_EPHEMERAL) {
3451            Slog.v(TAG, "Ephemeral resolver NOT found");
3452        }
3453        return null;
3454    }
3455
3456    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3457        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3458        intent.addCategory(Intent.CATEGORY_DEFAULT);
3459        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3460
3461        final int resolveFlags =
3462                MATCH_DIRECT_BOOT_AWARE
3463                | MATCH_DIRECT_BOOT_UNAWARE
3464                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3465        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3466                resolveFlags, UserHandle.USER_SYSTEM);
3467        // temporarily look for the old action
3468        if (matches.isEmpty()) {
3469            if (DEBUG_EPHEMERAL) {
3470                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3471            }
3472            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3473            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3474                    resolveFlags, UserHandle.USER_SYSTEM);
3475        }
3476        Iterator<ResolveInfo> iter = matches.iterator();
3477        while (iter.hasNext()) {
3478            final ResolveInfo rInfo = iter.next();
3479            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3480            if (ps != null) {
3481                final PermissionsState permissionsState = ps.getPermissionsState();
3482                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3483                    continue;
3484                }
3485            }
3486            iter.remove();
3487        }
3488        if (matches.size() == 0) {
3489            return null;
3490        } else if (matches.size() == 1) {
3491            return (ActivityInfo) matches.get(0).getComponentInfo();
3492        } else {
3493            throw new RuntimeException(
3494                    "There must be at most one ephemeral installer; found " + matches);
3495        }
3496    }
3497
3498    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3499            @NonNull ComponentName resolver) {
3500        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3501                .addCategory(Intent.CATEGORY_DEFAULT)
3502                .setPackage(resolver.getPackageName());
3503        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3504        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3505                UserHandle.USER_SYSTEM);
3506        // temporarily look for the old action
3507        if (matches.isEmpty()) {
3508            if (DEBUG_EPHEMERAL) {
3509                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3510            }
3511            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3512            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3513                    UserHandle.USER_SYSTEM);
3514        }
3515        if (matches.isEmpty()) {
3516            return null;
3517        }
3518        return matches.get(0).getComponentInfo().getComponentName();
3519    }
3520
3521    private void primeDomainVerificationsLPw(int userId) {
3522        if (DEBUG_DOMAIN_VERIFICATION) {
3523            Slog.d(TAG, "Priming domain verifications in user " + userId);
3524        }
3525
3526        SystemConfig systemConfig = SystemConfig.getInstance();
3527        ArraySet<String> packages = systemConfig.getLinkedApps();
3528
3529        for (String packageName : packages) {
3530            PackageParser.Package pkg = mPackages.get(packageName);
3531            if (pkg != null) {
3532                if (!pkg.isSystem()) {
3533                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3534                    continue;
3535                }
3536
3537                ArraySet<String> domains = null;
3538                for (PackageParser.Activity a : pkg.activities) {
3539                    for (ActivityIntentInfo filter : a.intents) {
3540                        if (hasValidDomains(filter)) {
3541                            if (domains == null) {
3542                                domains = new ArraySet<String>();
3543                            }
3544                            domains.addAll(filter.getHostsList());
3545                        }
3546                    }
3547                }
3548
3549                if (domains != null && domains.size() > 0) {
3550                    if (DEBUG_DOMAIN_VERIFICATION) {
3551                        Slog.v(TAG, "      + " + packageName);
3552                    }
3553                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3554                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3555                    // and then 'always' in the per-user state actually used for intent resolution.
3556                    final IntentFilterVerificationInfo ivi;
3557                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3558                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3559                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3560                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3561                } else {
3562                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3563                            + "' does not handle web links");
3564                }
3565            } else {
3566                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3567            }
3568        }
3569
3570        scheduleWritePackageRestrictionsLocked(userId);
3571        scheduleWriteSettingsLocked();
3572    }
3573
3574    private void applyFactoryDefaultBrowserLPw(int userId) {
3575        // The default browser app's package name is stored in a string resource,
3576        // with a product-specific overlay used for vendor customization.
3577        String browserPkg = mContext.getResources().getString(
3578                com.android.internal.R.string.default_browser);
3579        if (!TextUtils.isEmpty(browserPkg)) {
3580            // non-empty string => required to be a known package
3581            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3582            if (ps == null) {
3583                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3584                browserPkg = null;
3585            } else {
3586                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3587            }
3588        }
3589
3590        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3591        // default.  If there's more than one, just leave everything alone.
3592        if (browserPkg == null) {
3593            calculateDefaultBrowserLPw(userId);
3594        }
3595    }
3596
3597    private void calculateDefaultBrowserLPw(int userId) {
3598        List<String> allBrowsers = resolveAllBrowserApps(userId);
3599        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3600        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3601    }
3602
3603    private List<String> resolveAllBrowserApps(int userId) {
3604        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3605        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3606                PackageManager.MATCH_ALL, userId);
3607
3608        final int count = list.size();
3609        List<String> result = new ArrayList<String>(count);
3610        for (int i=0; i<count; i++) {
3611            ResolveInfo info = list.get(i);
3612            if (info.activityInfo == null
3613                    || !info.handleAllWebDataURI
3614                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3615                    || result.contains(info.activityInfo.packageName)) {
3616                continue;
3617            }
3618            result.add(info.activityInfo.packageName);
3619        }
3620
3621        return result;
3622    }
3623
3624    private boolean packageIsBrowser(String packageName, int userId) {
3625        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3626                PackageManager.MATCH_ALL, userId);
3627        final int N = list.size();
3628        for (int i = 0; i < N; i++) {
3629            ResolveInfo info = list.get(i);
3630            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3631                return true;
3632            }
3633        }
3634        return false;
3635    }
3636
3637    private void checkDefaultBrowser() {
3638        final int myUserId = UserHandle.myUserId();
3639        final String packageName = getDefaultBrowserPackageName(myUserId);
3640        if (packageName != null) {
3641            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3642            if (info == null) {
3643                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3644                synchronized (mPackages) {
3645                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3646                }
3647            }
3648        }
3649    }
3650
3651    @Override
3652    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3653            throws RemoteException {
3654        try {
3655            return super.onTransact(code, data, reply, flags);
3656        } catch (RuntimeException e) {
3657            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3658                Slog.wtf(TAG, "Package Manager Crash", e);
3659            }
3660            throw e;
3661        }
3662    }
3663
3664    static int[] appendInts(int[] cur, int[] add) {
3665        if (add == null) return cur;
3666        if (cur == null) return add;
3667        final int N = add.length;
3668        for (int i=0; i<N; i++) {
3669            cur = appendInt(cur, add[i]);
3670        }
3671        return cur;
3672    }
3673
3674    /**
3675     * Returns whether or not a full application can see an instant application.
3676     * <p>
3677     * Currently, there are three cases in which this can occur:
3678     * <ol>
3679     * <li>The calling application is a "special" process. Special processes
3680     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3681     * <li>The calling application has the permission
3682     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3683     * <li>The calling application is the default launcher on the
3684     *     system partition.</li>
3685     * </ol>
3686     */
3687    private boolean canViewInstantApps(int callingUid, int userId) {
3688        if (callingUid < Process.FIRST_APPLICATION_UID) {
3689            return true;
3690        }
3691        if (mContext.checkCallingOrSelfPermission(
3692                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3693            return true;
3694        }
3695        if (mContext.checkCallingOrSelfPermission(
3696                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3697            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3698            if (homeComponent != null
3699                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3700                return true;
3701            }
3702        }
3703        return false;
3704    }
3705
3706    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3707        if (!sUserManager.exists(userId)) return null;
3708        if (ps == null) {
3709            return null;
3710        }
3711        PackageParser.Package p = ps.pkg;
3712        if (p == null) {
3713            return null;
3714        }
3715        final int callingUid = Binder.getCallingUid();
3716        // Filter out ephemeral app metadata:
3717        //   * The system/shell/root can see metadata for any app
3718        //   * An installed app can see metadata for 1) other installed apps
3719        //     and 2) ephemeral apps that have explicitly interacted with it
3720        //   * Ephemeral apps can only see their own data and exposed installed apps
3721        //   * Holding a signature permission allows seeing instant apps
3722        if (filterAppAccessLPr(ps, callingUid, userId)) {
3723            return null;
3724        }
3725
3726        final PermissionsState permissionsState = ps.getPermissionsState();
3727
3728        // Compute GIDs only if requested
3729        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3730                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3731        // Compute granted permissions only if package has requested permissions
3732        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3733                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3734        final PackageUserState state = ps.readUserState(userId);
3735
3736        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3737                && ps.isSystem()) {
3738            flags |= MATCH_ANY_USER;
3739        }
3740
3741        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3742                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3743
3744        if (packageInfo == null) {
3745            return null;
3746        }
3747
3748        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3749                resolveExternalPackageNameLPr(p);
3750
3751        return packageInfo;
3752    }
3753
3754    @Override
3755    public void checkPackageStartable(String packageName, int userId) {
3756        final int callingUid = Binder.getCallingUid();
3757        if (getInstantAppPackageName(callingUid) != null) {
3758            throw new SecurityException("Instant applications don't have access to this method");
3759        }
3760        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3761        synchronized (mPackages) {
3762            final PackageSetting ps = mSettings.mPackages.get(packageName);
3763            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3764                throw new SecurityException("Package " + packageName + " was not found!");
3765            }
3766
3767            if (!ps.getInstalled(userId)) {
3768                throw new SecurityException(
3769                        "Package " + packageName + " was not installed for user " + userId + "!");
3770            }
3771
3772            if (mSafeMode && !ps.isSystem()) {
3773                throw new SecurityException("Package " + packageName + " not a system app!");
3774            }
3775
3776            if (mFrozenPackages.contains(packageName)) {
3777                throw new SecurityException("Package " + packageName + " is currently frozen!");
3778            }
3779
3780            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3781                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3782            }
3783        }
3784    }
3785
3786    @Override
3787    public boolean isPackageAvailable(String packageName, int userId) {
3788        if (!sUserManager.exists(userId)) return false;
3789        final int callingUid = Binder.getCallingUid();
3790        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3791                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3792        synchronized (mPackages) {
3793            PackageParser.Package p = mPackages.get(packageName);
3794            if (p != null) {
3795                final PackageSetting ps = (PackageSetting) p.mExtras;
3796                if (filterAppAccessLPr(ps, callingUid, userId)) {
3797                    return false;
3798                }
3799                if (ps != null) {
3800                    final PackageUserState state = ps.readUserState(userId);
3801                    if (state != null) {
3802                        return PackageParser.isAvailable(state);
3803                    }
3804                }
3805            }
3806        }
3807        return false;
3808    }
3809
3810    @Override
3811    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3812        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3813                flags, Binder.getCallingUid(), userId);
3814    }
3815
3816    @Override
3817    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3818            int flags, int userId) {
3819        return getPackageInfoInternal(versionedPackage.getPackageName(),
3820                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
3821    }
3822
3823    /**
3824     * Important: The provided filterCallingUid is used exclusively to filter out packages
3825     * that can be seen based on user state. It's typically the original caller uid prior
3826     * to clearing. Because it can only be provided by trusted code, it's value can be
3827     * trusted and will be used as-is; unlike userId which will be validated by this method.
3828     */
3829    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
3830            int flags, int filterCallingUid, int userId) {
3831        if (!sUserManager.exists(userId)) return null;
3832        flags = updateFlagsForPackage(flags, userId, packageName);
3833        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3834                false /* requireFullPermission */, false /* checkShell */, "get package info");
3835
3836        // reader
3837        synchronized (mPackages) {
3838            // Normalize package name to handle renamed packages and static libs
3839            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3840
3841            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3842            if (matchFactoryOnly) {
3843                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3844                if (ps != null) {
3845                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3846                        return null;
3847                    }
3848                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3849                        return null;
3850                    }
3851                    return generatePackageInfo(ps, flags, userId);
3852                }
3853            }
3854
3855            PackageParser.Package p = mPackages.get(packageName);
3856            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3857                return null;
3858            }
3859            if (DEBUG_PACKAGE_INFO)
3860                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3861            if (p != null) {
3862                final PackageSetting ps = (PackageSetting) p.mExtras;
3863                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3864                    return null;
3865                }
3866                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3867                    return null;
3868                }
3869                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3870            }
3871            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3872                final PackageSetting ps = mSettings.mPackages.get(packageName);
3873                if (ps == null) return null;
3874                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3875                    return null;
3876                }
3877                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3878                    return null;
3879                }
3880                return generatePackageInfo(ps, flags, userId);
3881            }
3882        }
3883        return null;
3884    }
3885
3886    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3887        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3888            return true;
3889        }
3890        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3891            return true;
3892        }
3893        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3894            return true;
3895        }
3896        return false;
3897    }
3898
3899    private boolean isComponentVisibleToInstantApp(
3900            @Nullable ComponentName component, @ComponentType int type) {
3901        if (type == TYPE_ACTIVITY) {
3902            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3903            return activity != null
3904                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3905                    : false;
3906        } else if (type == TYPE_RECEIVER) {
3907            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3908            return activity != null
3909                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3910                    : false;
3911        } else if (type == TYPE_SERVICE) {
3912            final PackageParser.Service service = mServices.mServices.get(component);
3913            return service != null
3914                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3915                    : false;
3916        } else if (type == TYPE_PROVIDER) {
3917            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3918            return provider != null
3919                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3920                    : false;
3921        } else if (type == TYPE_UNKNOWN) {
3922            return isComponentVisibleToInstantApp(component);
3923        }
3924        return false;
3925    }
3926
3927    /**
3928     * Returns whether or not access to the application should be filtered.
3929     * <p>
3930     * Access may be limited based upon whether the calling or target applications
3931     * are instant applications.
3932     *
3933     * @see #canAccessInstantApps(int)
3934     */
3935    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3936            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3937        // if we're in an isolated process, get the real calling UID
3938        if (Process.isIsolated(callingUid)) {
3939            callingUid = mIsolatedOwners.get(callingUid);
3940        }
3941        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3942        final boolean callerIsInstantApp = instantAppPkgName != null;
3943        if (ps == null) {
3944            if (callerIsInstantApp) {
3945                // pretend the application exists, but, needs to be filtered
3946                return true;
3947            }
3948            return false;
3949        }
3950        // if the target and caller are the same application, don't filter
3951        if (isCallerSameApp(ps.name, callingUid)) {
3952            return false;
3953        }
3954        if (callerIsInstantApp) {
3955            // request for a specific component; if it hasn't been explicitly exposed, filter
3956            if (component != null) {
3957                return !isComponentVisibleToInstantApp(component, componentType);
3958            }
3959            // request for application; if no components have been explicitly exposed, filter
3960            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3961        }
3962        if (ps.getInstantApp(userId)) {
3963            // caller can see all components of all instant applications, don't filter
3964            if (canViewInstantApps(callingUid, userId)) {
3965                return false;
3966            }
3967            // request for a specific instant application component, filter
3968            if (component != null) {
3969                return true;
3970            }
3971            // request for an instant application; if the caller hasn't been granted access, filter
3972            return !mInstantAppRegistry.isInstantAccessGranted(
3973                    userId, UserHandle.getAppId(callingUid), ps.appId);
3974        }
3975        return false;
3976    }
3977
3978    /**
3979     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3980     */
3981    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3982        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3983    }
3984
3985    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3986            int flags) {
3987        // Callers can access only the libs they depend on, otherwise they need to explicitly
3988        // ask for the shared libraries given the caller is allowed to access all static libs.
3989        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3990            // System/shell/root get to see all static libs
3991            final int appId = UserHandle.getAppId(uid);
3992            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3993                    || appId == Process.ROOT_UID) {
3994                return false;
3995            }
3996        }
3997
3998        // No package means no static lib as it is always on internal storage
3999        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4000            return false;
4001        }
4002
4003        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4004                ps.pkg.staticSharedLibVersion);
4005        if (libEntry == null) {
4006            return false;
4007        }
4008
4009        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4010        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4011        if (uidPackageNames == null) {
4012            return true;
4013        }
4014
4015        for (String uidPackageName : uidPackageNames) {
4016            if (ps.name.equals(uidPackageName)) {
4017                return false;
4018            }
4019            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4020            if (uidPs != null) {
4021                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4022                        libEntry.info.getName());
4023                if (index < 0) {
4024                    continue;
4025                }
4026                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4027                    return false;
4028                }
4029            }
4030        }
4031        return true;
4032    }
4033
4034    @Override
4035    public String[] currentToCanonicalPackageNames(String[] names) {
4036        final int callingUid = Binder.getCallingUid();
4037        if (getInstantAppPackageName(callingUid) != null) {
4038            return names;
4039        }
4040        final String[] out = new String[names.length];
4041        // reader
4042        synchronized (mPackages) {
4043            final int callingUserId = UserHandle.getUserId(callingUid);
4044            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4045            for (int i=names.length-1; i>=0; i--) {
4046                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4047                boolean translateName = false;
4048                if (ps != null && ps.realName != null) {
4049                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4050                    translateName = !targetIsInstantApp
4051                            || canViewInstantApps
4052                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4053                                    UserHandle.getAppId(callingUid), ps.appId);
4054                }
4055                out[i] = translateName ? ps.realName : names[i];
4056            }
4057        }
4058        return out;
4059    }
4060
4061    @Override
4062    public String[] canonicalToCurrentPackageNames(String[] names) {
4063        final int callingUid = Binder.getCallingUid();
4064        if (getInstantAppPackageName(callingUid) != null) {
4065            return names;
4066        }
4067        final String[] out = new String[names.length];
4068        // reader
4069        synchronized (mPackages) {
4070            final int callingUserId = UserHandle.getUserId(callingUid);
4071            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4072            for (int i=names.length-1; i>=0; i--) {
4073                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4074                boolean translateName = false;
4075                if (cur != null) {
4076                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4077                    final boolean targetIsInstantApp =
4078                            ps != null && ps.getInstantApp(callingUserId);
4079                    translateName = !targetIsInstantApp
4080                            || canViewInstantApps
4081                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4082                                    UserHandle.getAppId(callingUid), ps.appId);
4083                }
4084                out[i] = translateName ? cur : names[i];
4085            }
4086        }
4087        return out;
4088    }
4089
4090    @Override
4091    public int getPackageUid(String packageName, int flags, int userId) {
4092        if (!sUserManager.exists(userId)) return -1;
4093        final int callingUid = Binder.getCallingUid();
4094        flags = updateFlagsForPackage(flags, userId, packageName);
4095        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4096                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4097
4098        // reader
4099        synchronized (mPackages) {
4100            final PackageParser.Package p = mPackages.get(packageName);
4101            if (p != null && p.isMatch(flags)) {
4102                PackageSetting ps = (PackageSetting) p.mExtras;
4103                if (filterAppAccessLPr(ps, callingUid, userId)) {
4104                    return -1;
4105                }
4106                return UserHandle.getUid(userId, p.applicationInfo.uid);
4107            }
4108            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4109                final PackageSetting ps = mSettings.mPackages.get(packageName);
4110                if (ps != null && ps.isMatch(flags)
4111                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4112                    return UserHandle.getUid(userId, ps.appId);
4113                }
4114            }
4115        }
4116
4117        return -1;
4118    }
4119
4120    @Override
4121    public int[] getPackageGids(String packageName, int flags, int userId) {
4122        if (!sUserManager.exists(userId)) return null;
4123        final int callingUid = Binder.getCallingUid();
4124        flags = updateFlagsForPackage(flags, userId, packageName);
4125        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4126                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4127
4128        // reader
4129        synchronized (mPackages) {
4130            final PackageParser.Package p = mPackages.get(packageName);
4131            if (p != null && p.isMatch(flags)) {
4132                PackageSetting ps = (PackageSetting) p.mExtras;
4133                if (filterAppAccessLPr(ps, callingUid, userId)) {
4134                    return null;
4135                }
4136                // TODO: Shouldn't this be checking for package installed state for userId and
4137                // return null?
4138                return ps.getPermissionsState().computeGids(userId);
4139            }
4140            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4141                final PackageSetting ps = mSettings.mPackages.get(packageName);
4142                if (ps != null && ps.isMatch(flags)
4143                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4144                    return ps.getPermissionsState().computeGids(userId);
4145                }
4146            }
4147        }
4148
4149        return null;
4150    }
4151
4152    @Override
4153    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4154        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4155    }
4156
4157    @Override
4158    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4159            int flags) {
4160        final List<PermissionInfo> permissionList =
4161                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4162        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4163    }
4164
4165    @Override
4166    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4167        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4168    }
4169
4170    @Override
4171    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4172        final List<PermissionGroupInfo> permissionList =
4173                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4174        return (permissionList == null)
4175                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4176    }
4177
4178    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4179            int filterCallingUid, int userId) {
4180        if (!sUserManager.exists(userId)) return null;
4181        PackageSetting ps = mSettings.mPackages.get(packageName);
4182        if (ps != null) {
4183            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4184                return null;
4185            }
4186            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4187                return null;
4188            }
4189            if (ps.pkg == null) {
4190                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4191                if (pInfo != null) {
4192                    return pInfo.applicationInfo;
4193                }
4194                return null;
4195            }
4196            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4197                    ps.readUserState(userId), userId);
4198            if (ai != null) {
4199                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4200            }
4201            return ai;
4202        }
4203        return null;
4204    }
4205
4206    @Override
4207    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4208        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4209    }
4210
4211    /**
4212     * Important: The provided filterCallingUid is used exclusively to filter out applications
4213     * that can be seen based on user state. It's typically the original caller uid prior
4214     * to clearing. Because it can only be provided by trusted code, it's value can be
4215     * trusted and will be used as-is; unlike userId which will be validated by this method.
4216     */
4217    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4218            int filterCallingUid, int userId) {
4219        if (!sUserManager.exists(userId)) return null;
4220        flags = updateFlagsForApplication(flags, userId, packageName);
4221        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4222                false /* requireFullPermission */, false /* checkShell */, "get application info");
4223
4224        // writer
4225        synchronized (mPackages) {
4226            // Normalize package name to handle renamed packages and static libs
4227            packageName = resolveInternalPackageNameLPr(packageName,
4228                    PackageManager.VERSION_CODE_HIGHEST);
4229
4230            PackageParser.Package p = mPackages.get(packageName);
4231            if (DEBUG_PACKAGE_INFO) Log.v(
4232                    TAG, "getApplicationInfo " + packageName
4233                    + ": " + p);
4234            if (p != null) {
4235                PackageSetting ps = mSettings.mPackages.get(packageName);
4236                if (ps == null) return null;
4237                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4238                    return null;
4239                }
4240                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4241                    return null;
4242                }
4243                // Note: isEnabledLP() does not apply here - always return info
4244                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4245                        p, flags, ps.readUserState(userId), userId);
4246                if (ai != null) {
4247                    ai.packageName = resolveExternalPackageNameLPr(p);
4248                }
4249                return ai;
4250            }
4251            if ("android".equals(packageName)||"system".equals(packageName)) {
4252                return mAndroidApplication;
4253            }
4254            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4255                // Already generates the external package name
4256                return generateApplicationInfoFromSettingsLPw(packageName,
4257                        flags, filterCallingUid, userId);
4258            }
4259        }
4260        return null;
4261    }
4262
4263    private String normalizePackageNameLPr(String packageName) {
4264        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4265        return normalizedPackageName != null ? normalizedPackageName : packageName;
4266    }
4267
4268    @Override
4269    public void deletePreloadsFileCache() {
4270        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4271            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4272        }
4273        File dir = Environment.getDataPreloadsFileCacheDirectory();
4274        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4275        FileUtils.deleteContents(dir);
4276    }
4277
4278    @Override
4279    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4280            final int storageFlags, final IPackageDataObserver observer) {
4281        mContext.enforceCallingOrSelfPermission(
4282                android.Manifest.permission.CLEAR_APP_CACHE, null);
4283        mHandler.post(() -> {
4284            boolean success = false;
4285            try {
4286                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4287                success = true;
4288            } catch (IOException e) {
4289                Slog.w(TAG, e);
4290            }
4291            if (observer != null) {
4292                try {
4293                    observer.onRemoveCompleted(null, success);
4294                } catch (RemoteException e) {
4295                    Slog.w(TAG, e);
4296                }
4297            }
4298        });
4299    }
4300
4301    @Override
4302    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4303            final int storageFlags, final IntentSender pi) {
4304        mContext.enforceCallingOrSelfPermission(
4305                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4306        mHandler.post(() -> {
4307            boolean success = false;
4308            try {
4309                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4310                success = true;
4311            } catch (IOException e) {
4312                Slog.w(TAG, e);
4313            }
4314            if (pi != null) {
4315                try {
4316                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4317                } catch (SendIntentException e) {
4318                    Slog.w(TAG, e);
4319                }
4320            }
4321        });
4322    }
4323
4324    /**
4325     * Blocking call to clear various types of cached data across the system
4326     * until the requested bytes are available.
4327     */
4328    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4329        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4330        final File file = storage.findPathForUuid(volumeUuid);
4331        if (file.getUsableSpace() >= bytes) return;
4332
4333        if (ENABLE_FREE_CACHE_V2) {
4334            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4335                    volumeUuid);
4336            final boolean aggressive = (storageFlags
4337                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4338            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4339
4340            // 1. Pre-flight to determine if we have any chance to succeed
4341            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4342            if (internalVolume && (aggressive || SystemProperties
4343                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4344                deletePreloadsFileCache();
4345                if (file.getUsableSpace() >= bytes) return;
4346            }
4347
4348            // 3. Consider parsed APK data (aggressive only)
4349            if (internalVolume && aggressive) {
4350                FileUtils.deleteContents(mCacheDir);
4351                if (file.getUsableSpace() >= bytes) return;
4352            }
4353
4354            // 4. Consider cached app data (above quotas)
4355            try {
4356                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4357                        Installer.FLAG_FREE_CACHE_V2);
4358            } catch (InstallerException ignored) {
4359            }
4360            if (file.getUsableSpace() >= bytes) return;
4361
4362            // 5. Consider shared libraries with refcount=0 and age>min cache period
4363            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4364                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4365                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4366                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4367                return;
4368            }
4369
4370            // 6. Consider dexopt output (aggressive only)
4371            // TODO: Implement
4372
4373            // 7. Consider installed instant apps unused longer than min cache period
4374            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4375                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4376                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4377                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4378                return;
4379            }
4380
4381            // 8. Consider cached app data (below quotas)
4382            try {
4383                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4384                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4385            } catch (InstallerException ignored) {
4386            }
4387            if (file.getUsableSpace() >= bytes) return;
4388
4389            // 9. Consider DropBox entries
4390            // TODO: Implement
4391
4392            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4393            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4394                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4395                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4396                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4397                return;
4398            }
4399        } else {
4400            try {
4401                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4402            } catch (InstallerException ignored) {
4403            }
4404            if (file.getUsableSpace() >= bytes) return;
4405        }
4406
4407        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4408    }
4409
4410    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4411            throws IOException {
4412        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4413        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4414
4415        List<VersionedPackage> packagesToDelete = null;
4416        final long now = System.currentTimeMillis();
4417
4418        synchronized (mPackages) {
4419            final int[] allUsers = sUserManager.getUserIds();
4420            final int libCount = mSharedLibraries.size();
4421            for (int i = 0; i < libCount; i++) {
4422                final LongSparseArray<SharedLibraryEntry> versionedLib
4423                        = mSharedLibraries.valueAt(i);
4424                if (versionedLib == null) {
4425                    continue;
4426                }
4427                final int versionCount = versionedLib.size();
4428                for (int j = 0; j < versionCount; j++) {
4429                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4430                    // Skip packages that are not static shared libs.
4431                    if (!libInfo.isStatic()) {
4432                        break;
4433                    }
4434                    // Important: We skip static shared libs used for some user since
4435                    // in such a case we need to keep the APK on the device. The check for
4436                    // a lib being used for any user is performed by the uninstall call.
4437                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4438                    // Resolve the package name - we use synthetic package names internally
4439                    final String internalPackageName = resolveInternalPackageNameLPr(
4440                            declaringPackage.getPackageName(),
4441                            declaringPackage.getLongVersionCode());
4442                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4443                    // Skip unused static shared libs cached less than the min period
4444                    // to prevent pruning a lib needed by a subsequently installed package.
4445                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4446                        continue;
4447                    }
4448                    if (packagesToDelete == null) {
4449                        packagesToDelete = new ArrayList<>();
4450                    }
4451                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4452                            declaringPackage.getLongVersionCode()));
4453                }
4454            }
4455        }
4456
4457        if (packagesToDelete != null) {
4458            final int packageCount = packagesToDelete.size();
4459            for (int i = 0; i < packageCount; i++) {
4460                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4461                // Delete the package synchronously (will fail of the lib used for any user).
4462                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4463                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4464                                == PackageManager.DELETE_SUCCEEDED) {
4465                    if (volume.getUsableSpace() >= neededSpace) {
4466                        return true;
4467                    }
4468                }
4469            }
4470        }
4471
4472        return false;
4473    }
4474
4475    /**
4476     * Update given flags based on encryption status of current user.
4477     */
4478    private int updateFlags(int flags, int userId) {
4479        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4480                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4481            // Caller expressed an explicit opinion about what encryption
4482            // aware/unaware components they want to see, so fall through and
4483            // give them what they want
4484        } else {
4485            // Caller expressed no opinion, so match based on user state
4486            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4487                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4488            } else {
4489                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4490            }
4491        }
4492        return flags;
4493    }
4494
4495    private UserManagerInternal getUserManagerInternal() {
4496        if (mUserManagerInternal == null) {
4497            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4498        }
4499        return mUserManagerInternal;
4500    }
4501
4502    private DeviceIdleController.LocalService getDeviceIdleController() {
4503        if (mDeviceIdleController == null) {
4504            mDeviceIdleController =
4505                    LocalServices.getService(DeviceIdleController.LocalService.class);
4506        }
4507        return mDeviceIdleController;
4508    }
4509
4510    /**
4511     * Update given flags when being used to request {@link PackageInfo}.
4512     */
4513    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4514        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4515        boolean triaged = true;
4516        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4517                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4518            // Caller is asking for component details, so they'd better be
4519            // asking for specific encryption matching behavior, or be triaged
4520            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4521                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4522                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4523                triaged = false;
4524            }
4525        }
4526        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4527                | PackageManager.MATCH_SYSTEM_ONLY
4528                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4529            triaged = false;
4530        }
4531        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4532            mPermissionManager.enforceCrossUserPermission(
4533                    Binder.getCallingUid(), userId, false, false,
4534                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4535                    + Debug.getCallers(5));
4536        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4537                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4538            // If the caller wants all packages and has a restricted profile associated with it,
4539            // then match all users. This is to make sure that launchers that need to access work
4540            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4541            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4542            flags |= PackageManager.MATCH_ANY_USER;
4543        }
4544        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4545            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4546                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4547        }
4548        return updateFlags(flags, userId);
4549    }
4550
4551    /**
4552     * Update given flags when being used to request {@link ApplicationInfo}.
4553     */
4554    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4555        return updateFlagsForPackage(flags, userId, cookie);
4556    }
4557
4558    /**
4559     * Update given flags when being used to request {@link ComponentInfo}.
4560     */
4561    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4562        if (cookie instanceof Intent) {
4563            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4564                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4565            }
4566        }
4567
4568        boolean triaged = true;
4569        // Caller is asking for component details, so they'd better be
4570        // asking for specific encryption matching behavior, or be triaged
4571        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4572                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4573                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4574            triaged = false;
4575        }
4576        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4577            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4578                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4579        }
4580
4581        return updateFlags(flags, userId);
4582    }
4583
4584    /**
4585     * Update given intent when being used to request {@link ResolveInfo}.
4586     */
4587    private Intent updateIntentForResolve(Intent intent) {
4588        if (intent.getSelector() != null) {
4589            intent = intent.getSelector();
4590        }
4591        if (DEBUG_PREFERRED) {
4592            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4593        }
4594        return intent;
4595    }
4596
4597    /**
4598     * Update given flags when being used to request {@link ResolveInfo}.
4599     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4600     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4601     * flag set. However, this flag is only honoured in three circumstances:
4602     * <ul>
4603     * <li>when called from a system process</li>
4604     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4605     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4606     * action and a {@code android.intent.category.BROWSABLE} category</li>
4607     * </ul>
4608     */
4609    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4610        return updateFlagsForResolve(flags, userId, intent, callingUid,
4611                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4612    }
4613    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4614            boolean wantInstantApps) {
4615        return updateFlagsForResolve(flags, userId, intent, callingUid,
4616                wantInstantApps, false /*onlyExposedExplicitly*/);
4617    }
4618    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4619            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4620        // Safe mode means we shouldn't match any third-party components
4621        if (mSafeMode) {
4622            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4623        }
4624        if (getInstantAppPackageName(callingUid) != null) {
4625            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4626            if (onlyExposedExplicitly) {
4627                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4628            }
4629            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4630            flags |= PackageManager.MATCH_INSTANT;
4631        } else {
4632            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4633            final boolean allowMatchInstant =
4634                    (wantInstantApps
4635                            && Intent.ACTION_VIEW.equals(intent.getAction())
4636                            && hasWebURI(intent))
4637                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4638            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4639                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4640            if (!allowMatchInstant) {
4641                flags &= ~PackageManager.MATCH_INSTANT;
4642            }
4643        }
4644        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4645    }
4646
4647    @Override
4648    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4649        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4650    }
4651
4652    /**
4653     * Important: The provided filterCallingUid is used exclusively to filter out activities
4654     * that can be seen based on user state. It's typically the original caller uid prior
4655     * to clearing. Because it can only be provided by trusted code, it's value can be
4656     * trusted and will be used as-is; unlike userId which will be validated by this method.
4657     */
4658    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4659            int filterCallingUid, int userId) {
4660        if (!sUserManager.exists(userId)) return null;
4661        flags = updateFlagsForComponent(flags, userId, component);
4662        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4663                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4664        synchronized (mPackages) {
4665            PackageParser.Activity a = mActivities.mActivities.get(component);
4666
4667            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4668            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4669                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4670                if (ps == null) return null;
4671                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4672                    return null;
4673                }
4674                return PackageParser.generateActivityInfo(
4675                        a, flags, ps.readUserState(userId), userId);
4676            }
4677            if (mResolveComponentName.equals(component)) {
4678                return PackageParser.generateActivityInfo(
4679                        mResolveActivity, flags, new PackageUserState(), userId);
4680            }
4681        }
4682        return null;
4683    }
4684
4685    @Override
4686    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4687            String resolvedType) {
4688        synchronized (mPackages) {
4689            if (component.equals(mResolveComponentName)) {
4690                // The resolver supports EVERYTHING!
4691                return true;
4692            }
4693            final int callingUid = Binder.getCallingUid();
4694            final int callingUserId = UserHandle.getUserId(callingUid);
4695            PackageParser.Activity a = mActivities.mActivities.get(component);
4696            if (a == null) {
4697                return false;
4698            }
4699            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4700            if (ps == null) {
4701                return false;
4702            }
4703            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4704                return false;
4705            }
4706            for (int i=0; i<a.intents.size(); i++) {
4707                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4708                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4709                    return true;
4710                }
4711            }
4712            return false;
4713        }
4714    }
4715
4716    @Override
4717    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4718        if (!sUserManager.exists(userId)) return null;
4719        final int callingUid = Binder.getCallingUid();
4720        flags = updateFlagsForComponent(flags, userId, component);
4721        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4722                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4723        synchronized (mPackages) {
4724            PackageParser.Activity a = mReceivers.mActivities.get(component);
4725            if (DEBUG_PACKAGE_INFO) Log.v(
4726                TAG, "getReceiverInfo " + component + ": " + a);
4727            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4728                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4729                if (ps == null) return null;
4730                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4731                    return null;
4732                }
4733                return PackageParser.generateActivityInfo(
4734                        a, flags, ps.readUserState(userId), userId);
4735            }
4736        }
4737        return null;
4738    }
4739
4740    @Override
4741    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4742            int flags, int userId) {
4743        if (!sUserManager.exists(userId)) return null;
4744        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4745        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4746            return null;
4747        }
4748
4749        flags = updateFlagsForPackage(flags, userId, null);
4750
4751        final boolean canSeeStaticLibraries =
4752                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4753                        == PERMISSION_GRANTED
4754                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4755                        == PERMISSION_GRANTED
4756                || canRequestPackageInstallsInternal(packageName,
4757                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4758                        false  /* throwIfPermNotDeclared*/)
4759                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4760                        == PERMISSION_GRANTED;
4761
4762        synchronized (mPackages) {
4763            List<SharedLibraryInfo> result = null;
4764
4765            final int libCount = mSharedLibraries.size();
4766            for (int i = 0; i < libCount; i++) {
4767                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4768                if (versionedLib == null) {
4769                    continue;
4770                }
4771
4772                final int versionCount = versionedLib.size();
4773                for (int j = 0; j < versionCount; j++) {
4774                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4775                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4776                        break;
4777                    }
4778                    final long identity = Binder.clearCallingIdentity();
4779                    try {
4780                        PackageInfo packageInfo = getPackageInfoVersioned(
4781                                libInfo.getDeclaringPackage(), flags
4782                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4783                        if (packageInfo == null) {
4784                            continue;
4785                        }
4786                    } finally {
4787                        Binder.restoreCallingIdentity(identity);
4788                    }
4789
4790                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4791                            libInfo.getLongVersion(), libInfo.getType(),
4792                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4793                            flags, userId));
4794
4795                    if (result == null) {
4796                        result = new ArrayList<>();
4797                    }
4798                    result.add(resLibInfo);
4799                }
4800            }
4801
4802            return result != null ? new ParceledListSlice<>(result) : null;
4803        }
4804    }
4805
4806    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4807            SharedLibraryInfo libInfo, int flags, int userId) {
4808        List<VersionedPackage> versionedPackages = null;
4809        final int packageCount = mSettings.mPackages.size();
4810        for (int i = 0; i < packageCount; i++) {
4811            PackageSetting ps = mSettings.mPackages.valueAt(i);
4812
4813            if (ps == null) {
4814                continue;
4815            }
4816
4817            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4818                continue;
4819            }
4820
4821            final String libName = libInfo.getName();
4822            if (libInfo.isStatic()) {
4823                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4824                if (libIdx < 0) {
4825                    continue;
4826                }
4827                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
4828                    continue;
4829                }
4830                if (versionedPackages == null) {
4831                    versionedPackages = new ArrayList<>();
4832                }
4833                // If the dependent is a static shared lib, use the public package name
4834                String dependentPackageName = ps.name;
4835                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4836                    dependentPackageName = ps.pkg.manifestPackageName;
4837                }
4838                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4839            } else if (ps.pkg != null) {
4840                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4841                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4842                    if (versionedPackages == null) {
4843                        versionedPackages = new ArrayList<>();
4844                    }
4845                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4846                }
4847            }
4848        }
4849
4850        return versionedPackages;
4851    }
4852
4853    @Override
4854    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4855        if (!sUserManager.exists(userId)) return null;
4856        final int callingUid = Binder.getCallingUid();
4857        flags = updateFlagsForComponent(flags, userId, component);
4858        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4859                false /* requireFullPermission */, false /* checkShell */, "get service info");
4860        synchronized (mPackages) {
4861            PackageParser.Service s = mServices.mServices.get(component);
4862            if (DEBUG_PACKAGE_INFO) Log.v(
4863                TAG, "getServiceInfo " + component + ": " + s);
4864            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4865                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4866                if (ps == null) return null;
4867                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4868                    return null;
4869                }
4870                return PackageParser.generateServiceInfo(
4871                        s, flags, ps.readUserState(userId), userId);
4872            }
4873        }
4874        return null;
4875    }
4876
4877    @Override
4878    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4879        if (!sUserManager.exists(userId)) return null;
4880        final int callingUid = Binder.getCallingUid();
4881        flags = updateFlagsForComponent(flags, userId, component);
4882        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4883                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4884        synchronized (mPackages) {
4885            PackageParser.Provider p = mProviders.mProviders.get(component);
4886            if (DEBUG_PACKAGE_INFO) Log.v(
4887                TAG, "getProviderInfo " + component + ": " + p);
4888            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4889                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4890                if (ps == null) return null;
4891                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4892                    return null;
4893                }
4894                return PackageParser.generateProviderInfo(
4895                        p, flags, ps.readUserState(userId), userId);
4896            }
4897        }
4898        return null;
4899    }
4900
4901    @Override
4902    public String[] getSystemSharedLibraryNames() {
4903        // allow instant applications
4904        synchronized (mPackages) {
4905            Set<String> libs = null;
4906            final int libCount = mSharedLibraries.size();
4907            for (int i = 0; i < libCount; i++) {
4908                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4909                if (versionedLib == null) {
4910                    continue;
4911                }
4912                final int versionCount = versionedLib.size();
4913                for (int j = 0; j < versionCount; j++) {
4914                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4915                    if (!libEntry.info.isStatic()) {
4916                        if (libs == null) {
4917                            libs = new ArraySet<>();
4918                        }
4919                        libs.add(libEntry.info.getName());
4920                        break;
4921                    }
4922                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4923                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4924                            UserHandle.getUserId(Binder.getCallingUid()),
4925                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4926                        if (libs == null) {
4927                            libs = new ArraySet<>();
4928                        }
4929                        libs.add(libEntry.info.getName());
4930                        break;
4931                    }
4932                }
4933            }
4934
4935            if (libs != null) {
4936                String[] libsArray = new String[libs.size()];
4937                libs.toArray(libsArray);
4938                return libsArray;
4939            }
4940
4941            return null;
4942        }
4943    }
4944
4945    @Override
4946    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4947        // allow instant applications
4948        synchronized (mPackages) {
4949            return mServicesSystemSharedLibraryPackageName;
4950        }
4951    }
4952
4953    @Override
4954    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4955        // allow instant applications
4956        synchronized (mPackages) {
4957            return mSharedSystemSharedLibraryPackageName;
4958        }
4959    }
4960
4961    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4962        for (int i = userList.length - 1; i >= 0; --i) {
4963            final int userId = userList[i];
4964            // don't add instant app to the list of updates
4965            if (pkgSetting.getInstantApp(userId)) {
4966                continue;
4967            }
4968            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4969            if (changedPackages == null) {
4970                changedPackages = new SparseArray<>();
4971                mChangedPackages.put(userId, changedPackages);
4972            }
4973            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4974            if (sequenceNumbers == null) {
4975                sequenceNumbers = new HashMap<>();
4976                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4977            }
4978            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4979            if (sequenceNumber != null) {
4980                changedPackages.remove(sequenceNumber);
4981            }
4982            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4983            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4984        }
4985        mChangedPackagesSequenceNumber++;
4986    }
4987
4988    @Override
4989    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4990        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4991            return null;
4992        }
4993        synchronized (mPackages) {
4994            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4995                return null;
4996            }
4997            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4998            if (changedPackages == null) {
4999                return null;
5000            }
5001            final List<String> packageNames =
5002                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5003            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5004                final String packageName = changedPackages.get(i);
5005                if (packageName != null) {
5006                    packageNames.add(packageName);
5007                }
5008            }
5009            return packageNames.isEmpty()
5010                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5011        }
5012    }
5013
5014    @Override
5015    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5016        // allow instant applications
5017        ArrayList<FeatureInfo> res;
5018        synchronized (mAvailableFeatures) {
5019            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5020            res.addAll(mAvailableFeatures.values());
5021        }
5022        final FeatureInfo fi = new FeatureInfo();
5023        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5024                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5025        res.add(fi);
5026
5027        return new ParceledListSlice<>(res);
5028    }
5029
5030    @Override
5031    public boolean hasSystemFeature(String name, int version) {
5032        // allow instant applications
5033        synchronized (mAvailableFeatures) {
5034            final FeatureInfo feat = mAvailableFeatures.get(name);
5035            if (feat == null) {
5036                return false;
5037            } else {
5038                return feat.version >= version;
5039            }
5040        }
5041    }
5042
5043    @Override
5044    public int checkPermission(String permName, String pkgName, int userId) {
5045        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5046    }
5047
5048    @Override
5049    public int checkUidPermission(String permName, int uid) {
5050        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5051    }
5052
5053    @Override
5054    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5055        if (UserHandle.getCallingUserId() != userId) {
5056            mContext.enforceCallingPermission(
5057                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5058                    "isPermissionRevokedByPolicy for user " + userId);
5059        }
5060
5061        if (checkPermission(permission, packageName, userId)
5062                == PackageManager.PERMISSION_GRANTED) {
5063            return false;
5064        }
5065
5066        final int callingUid = Binder.getCallingUid();
5067        if (getInstantAppPackageName(callingUid) != null) {
5068            if (!isCallerSameApp(packageName, callingUid)) {
5069                return false;
5070            }
5071        } else {
5072            if (isInstantApp(packageName, userId)) {
5073                return false;
5074            }
5075        }
5076
5077        final long identity = Binder.clearCallingIdentity();
5078        try {
5079            final int flags = getPermissionFlags(permission, packageName, userId);
5080            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5081        } finally {
5082            Binder.restoreCallingIdentity(identity);
5083        }
5084    }
5085
5086    @Override
5087    public String getPermissionControllerPackageName() {
5088        synchronized (mPackages) {
5089            return mRequiredInstallerPackage;
5090        }
5091    }
5092
5093    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5094        return mPermissionManager.addDynamicPermission(
5095                info, async, getCallingUid(), new PermissionCallback() {
5096                    @Override
5097                    public void onPermissionChanged() {
5098                        if (!async) {
5099                            mSettings.writeLPr();
5100                        } else {
5101                            scheduleWriteSettingsLocked();
5102                        }
5103                    }
5104                });
5105    }
5106
5107    @Override
5108    public boolean addPermission(PermissionInfo info) {
5109        synchronized (mPackages) {
5110            return addDynamicPermission(info, false);
5111        }
5112    }
5113
5114    @Override
5115    public boolean addPermissionAsync(PermissionInfo info) {
5116        synchronized (mPackages) {
5117            return addDynamicPermission(info, true);
5118        }
5119    }
5120
5121    @Override
5122    public void removePermission(String permName) {
5123        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5124    }
5125
5126    @Override
5127    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5128        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5129                getCallingUid(), userId, mPermissionCallback);
5130    }
5131
5132    @Override
5133    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5134        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5135                getCallingUid(), userId, mPermissionCallback);
5136    }
5137
5138    @Override
5139    public void resetRuntimePermissions() {
5140        mContext.enforceCallingOrSelfPermission(
5141                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5142                "revokeRuntimePermission");
5143
5144        int callingUid = Binder.getCallingUid();
5145        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5146            mContext.enforceCallingOrSelfPermission(
5147                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5148                    "resetRuntimePermissions");
5149        }
5150
5151        synchronized (mPackages) {
5152            mPermissionManager.updateAllPermissions(
5153                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5154                    mPermissionCallback);
5155            for (int userId : UserManagerService.getInstance().getUserIds()) {
5156                final int packageCount = mPackages.size();
5157                for (int i = 0; i < packageCount; i++) {
5158                    PackageParser.Package pkg = mPackages.valueAt(i);
5159                    if (!(pkg.mExtras instanceof PackageSetting)) {
5160                        continue;
5161                    }
5162                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5163                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5164                }
5165            }
5166        }
5167    }
5168
5169    @Override
5170    public int getPermissionFlags(String permName, String packageName, int userId) {
5171        return mPermissionManager.getPermissionFlags(
5172                permName, packageName, getCallingUid(), userId);
5173    }
5174
5175    @Override
5176    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5177            int flagValues, int userId) {
5178        mPermissionManager.updatePermissionFlags(
5179                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5180                mPermissionCallback);
5181    }
5182
5183    /**
5184     * Update the permission flags for all packages and runtime permissions of a user in order
5185     * to allow device or profile owner to remove POLICY_FIXED.
5186     */
5187    @Override
5188    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5189        synchronized (mPackages) {
5190            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5191                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5192                    mPermissionCallback);
5193            if (changed) {
5194                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5195            }
5196        }
5197    }
5198
5199    @Override
5200    public boolean shouldShowRequestPermissionRationale(String permissionName,
5201            String packageName, int userId) {
5202        if (UserHandle.getCallingUserId() != userId) {
5203            mContext.enforceCallingPermission(
5204                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5205                    "canShowRequestPermissionRationale for user " + userId);
5206        }
5207
5208        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5209        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5210            return false;
5211        }
5212
5213        if (checkPermission(permissionName, packageName, userId)
5214                == PackageManager.PERMISSION_GRANTED) {
5215            return false;
5216        }
5217
5218        final int flags;
5219
5220        final long identity = Binder.clearCallingIdentity();
5221        try {
5222            flags = getPermissionFlags(permissionName,
5223                    packageName, userId);
5224        } finally {
5225            Binder.restoreCallingIdentity(identity);
5226        }
5227
5228        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5229                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5230                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5231
5232        if ((flags & fixedFlags) != 0) {
5233            return false;
5234        }
5235
5236        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5237    }
5238
5239    @Override
5240    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5241        mContext.enforceCallingOrSelfPermission(
5242                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5243                "addOnPermissionsChangeListener");
5244
5245        synchronized (mPackages) {
5246            mOnPermissionChangeListeners.addListenerLocked(listener);
5247        }
5248    }
5249
5250    @Override
5251    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5252        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5253            throw new SecurityException("Instant applications don't have access to this method");
5254        }
5255        synchronized (mPackages) {
5256            mOnPermissionChangeListeners.removeListenerLocked(listener);
5257        }
5258    }
5259
5260    @Override
5261    public boolean isProtectedBroadcast(String actionName) {
5262        // allow instant applications
5263        synchronized (mProtectedBroadcasts) {
5264            if (mProtectedBroadcasts.contains(actionName)) {
5265                return true;
5266            } else if (actionName != null) {
5267                // TODO: remove these terrible hacks
5268                if (actionName.startsWith("android.net.netmon.lingerExpired")
5269                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5270                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5271                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5272                    return true;
5273                }
5274            }
5275        }
5276        return false;
5277    }
5278
5279    @Override
5280    public int checkSignatures(String pkg1, String pkg2) {
5281        synchronized (mPackages) {
5282            final PackageParser.Package p1 = mPackages.get(pkg1);
5283            final PackageParser.Package p2 = mPackages.get(pkg2);
5284            if (p1 == null || p1.mExtras == null
5285                    || p2 == null || p2.mExtras == null) {
5286                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5287            }
5288            final int callingUid = Binder.getCallingUid();
5289            final int callingUserId = UserHandle.getUserId(callingUid);
5290            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5291            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5292            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5293                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5294                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5295            }
5296            return compareSignatures(p1.mSignatures, p2.mSignatures);
5297        }
5298    }
5299
5300    @Override
5301    public int checkUidSignatures(int uid1, int uid2) {
5302        final int callingUid = Binder.getCallingUid();
5303        final int callingUserId = UserHandle.getUserId(callingUid);
5304        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5305        // Map to base uids.
5306        uid1 = UserHandle.getAppId(uid1);
5307        uid2 = UserHandle.getAppId(uid2);
5308        // reader
5309        synchronized (mPackages) {
5310            Signature[] s1;
5311            Signature[] s2;
5312            Object obj = mSettings.getUserIdLPr(uid1);
5313            if (obj != null) {
5314                if (obj instanceof SharedUserSetting) {
5315                    if (isCallerInstantApp) {
5316                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5317                    }
5318                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5319                } else if (obj instanceof PackageSetting) {
5320                    final PackageSetting ps = (PackageSetting) obj;
5321                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5322                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5323                    }
5324                    s1 = ps.signatures.mSignatures;
5325                } else {
5326                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5327                }
5328            } else {
5329                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5330            }
5331            obj = mSettings.getUserIdLPr(uid2);
5332            if (obj != null) {
5333                if (obj instanceof SharedUserSetting) {
5334                    if (isCallerInstantApp) {
5335                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5336                    }
5337                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5338                } else if (obj instanceof PackageSetting) {
5339                    final PackageSetting ps = (PackageSetting) obj;
5340                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5341                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5342                    }
5343                    s2 = ps.signatures.mSignatures;
5344                } else {
5345                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5346                }
5347            } else {
5348                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5349            }
5350            return compareSignatures(s1, s2);
5351        }
5352    }
5353
5354    /**
5355     * This method should typically only be used when granting or revoking
5356     * permissions, since the app may immediately restart after this call.
5357     * <p>
5358     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5359     * guard your work against the app being relaunched.
5360     */
5361    private void killUid(int appId, int userId, String reason) {
5362        final long identity = Binder.clearCallingIdentity();
5363        try {
5364            IActivityManager am = ActivityManager.getService();
5365            if (am != null) {
5366                try {
5367                    am.killUid(appId, userId, reason);
5368                } catch (RemoteException e) {
5369                    /* ignore - same process */
5370                }
5371            }
5372        } finally {
5373            Binder.restoreCallingIdentity(identity);
5374        }
5375    }
5376
5377    /**
5378     * If the database version for this type of package (internal storage or
5379     * external storage) is less than the version where package signatures
5380     * were updated, return true.
5381     */
5382    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5383        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5384        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5385    }
5386
5387    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5388        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5389        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5390    }
5391
5392    @Override
5393    public List<String> getAllPackages() {
5394        final int callingUid = Binder.getCallingUid();
5395        final int callingUserId = UserHandle.getUserId(callingUid);
5396        synchronized (mPackages) {
5397            if (canViewInstantApps(callingUid, callingUserId)) {
5398                return new ArrayList<String>(mPackages.keySet());
5399            }
5400            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5401            final List<String> result = new ArrayList<>();
5402            if (instantAppPkgName != null) {
5403                // caller is an instant application; filter unexposed applications
5404                for (PackageParser.Package pkg : mPackages.values()) {
5405                    if (!pkg.visibleToInstantApps) {
5406                        continue;
5407                    }
5408                    result.add(pkg.packageName);
5409                }
5410            } else {
5411                // caller is a normal application; filter instant applications
5412                for (PackageParser.Package pkg : mPackages.values()) {
5413                    final PackageSetting ps =
5414                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5415                    if (ps != null
5416                            && ps.getInstantApp(callingUserId)
5417                            && !mInstantAppRegistry.isInstantAccessGranted(
5418                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5419                        continue;
5420                    }
5421                    result.add(pkg.packageName);
5422                }
5423            }
5424            return result;
5425        }
5426    }
5427
5428    @Override
5429    public String[] getPackagesForUid(int uid) {
5430        final int callingUid = Binder.getCallingUid();
5431        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5432        final int userId = UserHandle.getUserId(uid);
5433        uid = UserHandle.getAppId(uid);
5434        // reader
5435        synchronized (mPackages) {
5436            Object obj = mSettings.getUserIdLPr(uid);
5437            if (obj instanceof SharedUserSetting) {
5438                if (isCallerInstantApp) {
5439                    return null;
5440                }
5441                final SharedUserSetting sus = (SharedUserSetting) obj;
5442                final int N = sus.packages.size();
5443                String[] res = new String[N];
5444                final Iterator<PackageSetting> it = sus.packages.iterator();
5445                int i = 0;
5446                while (it.hasNext()) {
5447                    PackageSetting ps = it.next();
5448                    if (ps.getInstalled(userId)) {
5449                        res[i++] = ps.name;
5450                    } else {
5451                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5452                    }
5453                }
5454                return res;
5455            } else if (obj instanceof PackageSetting) {
5456                final PackageSetting ps = (PackageSetting) obj;
5457                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5458                    return new String[]{ps.name};
5459                }
5460            }
5461        }
5462        return null;
5463    }
5464
5465    @Override
5466    public String getNameForUid(int uid) {
5467        final int callingUid = Binder.getCallingUid();
5468        if (getInstantAppPackageName(callingUid) != null) {
5469            return null;
5470        }
5471        synchronized (mPackages) {
5472            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5473            if (obj instanceof SharedUserSetting) {
5474                final SharedUserSetting sus = (SharedUserSetting) obj;
5475                return sus.name + ":" + sus.userId;
5476            } else if (obj instanceof PackageSetting) {
5477                final PackageSetting ps = (PackageSetting) obj;
5478                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5479                    return null;
5480                }
5481                return ps.name;
5482            }
5483            return null;
5484        }
5485    }
5486
5487    @Override
5488    public String[] getNamesForUids(int[] uids) {
5489        if (uids == null || uids.length == 0) {
5490            return null;
5491        }
5492        final int callingUid = Binder.getCallingUid();
5493        if (getInstantAppPackageName(callingUid) != null) {
5494            return null;
5495        }
5496        final String[] names = new String[uids.length];
5497        synchronized (mPackages) {
5498            for (int i = uids.length - 1; i >= 0; i--) {
5499                final int uid = uids[i];
5500                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5501                if (obj instanceof SharedUserSetting) {
5502                    final SharedUserSetting sus = (SharedUserSetting) obj;
5503                    names[i] = "shared:" + sus.name;
5504                } else if (obj instanceof PackageSetting) {
5505                    final PackageSetting ps = (PackageSetting) obj;
5506                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5507                        names[i] = null;
5508                    } else {
5509                        names[i] = ps.name;
5510                    }
5511                } else {
5512                    names[i] = null;
5513                }
5514            }
5515        }
5516        return names;
5517    }
5518
5519    @Override
5520    public int getUidForSharedUser(String sharedUserName) {
5521        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5522            return -1;
5523        }
5524        if (sharedUserName == null) {
5525            return -1;
5526        }
5527        // reader
5528        synchronized (mPackages) {
5529            SharedUserSetting suid;
5530            try {
5531                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5532                if (suid != null) {
5533                    return suid.userId;
5534                }
5535            } catch (PackageManagerException ignore) {
5536                // can't happen, but, still need to catch it
5537            }
5538            return -1;
5539        }
5540    }
5541
5542    @Override
5543    public int getFlagsForUid(int uid) {
5544        final int callingUid = Binder.getCallingUid();
5545        if (getInstantAppPackageName(callingUid) != null) {
5546            return 0;
5547        }
5548        synchronized (mPackages) {
5549            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5550            if (obj instanceof SharedUserSetting) {
5551                final SharedUserSetting sus = (SharedUserSetting) obj;
5552                return sus.pkgFlags;
5553            } else if (obj instanceof PackageSetting) {
5554                final PackageSetting ps = (PackageSetting) obj;
5555                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5556                    return 0;
5557                }
5558                return ps.pkgFlags;
5559            }
5560        }
5561        return 0;
5562    }
5563
5564    @Override
5565    public int getPrivateFlagsForUid(int uid) {
5566        final int callingUid = Binder.getCallingUid();
5567        if (getInstantAppPackageName(callingUid) != null) {
5568            return 0;
5569        }
5570        synchronized (mPackages) {
5571            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5572            if (obj instanceof SharedUserSetting) {
5573                final SharedUserSetting sus = (SharedUserSetting) obj;
5574                return sus.pkgPrivateFlags;
5575            } else if (obj instanceof PackageSetting) {
5576                final PackageSetting ps = (PackageSetting) obj;
5577                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5578                    return 0;
5579                }
5580                return ps.pkgPrivateFlags;
5581            }
5582        }
5583        return 0;
5584    }
5585
5586    @Override
5587    public boolean isUidPrivileged(int uid) {
5588        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5589            return false;
5590        }
5591        uid = UserHandle.getAppId(uid);
5592        // reader
5593        synchronized (mPackages) {
5594            Object obj = mSettings.getUserIdLPr(uid);
5595            if (obj instanceof SharedUserSetting) {
5596                final SharedUserSetting sus = (SharedUserSetting) obj;
5597                final Iterator<PackageSetting> it = sus.packages.iterator();
5598                while (it.hasNext()) {
5599                    if (it.next().isPrivileged()) {
5600                        return true;
5601                    }
5602                }
5603            } else if (obj instanceof PackageSetting) {
5604                final PackageSetting ps = (PackageSetting) obj;
5605                return ps.isPrivileged();
5606            }
5607        }
5608        return false;
5609    }
5610
5611    @Override
5612    public String[] getAppOpPermissionPackages(String permName) {
5613        return mPermissionManager.getAppOpPermissionPackages(permName);
5614    }
5615
5616    @Override
5617    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5618            int flags, int userId) {
5619        return resolveIntentInternal(
5620                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5621    }
5622
5623    /**
5624     * Normally instant apps can only be resolved when they're visible to the caller.
5625     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5626     * since we need to allow the system to start any installed application.
5627     */
5628    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5629            int flags, int userId, boolean resolveForStart) {
5630        try {
5631            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5632
5633            if (!sUserManager.exists(userId)) return null;
5634            final int callingUid = Binder.getCallingUid();
5635            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5636            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5637                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5638
5639            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5640            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5641                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5642            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5643
5644            final ResolveInfo bestChoice =
5645                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5646            return bestChoice;
5647        } finally {
5648            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5649        }
5650    }
5651
5652    @Override
5653    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5654        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5655            throw new SecurityException(
5656                    "findPersistentPreferredActivity can only be run by the system");
5657        }
5658        if (!sUserManager.exists(userId)) {
5659            return null;
5660        }
5661        final int callingUid = Binder.getCallingUid();
5662        intent = updateIntentForResolve(intent);
5663        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5664        final int flags = updateFlagsForResolve(
5665                0, userId, intent, callingUid, false /*includeInstantApps*/);
5666        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5667                userId);
5668        synchronized (mPackages) {
5669            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5670                    userId);
5671        }
5672    }
5673
5674    @Override
5675    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5676            IntentFilter filter, int match, ComponentName activity) {
5677        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5678            return;
5679        }
5680        final int userId = UserHandle.getCallingUserId();
5681        if (DEBUG_PREFERRED) {
5682            Log.v(TAG, "setLastChosenActivity intent=" + intent
5683                + " resolvedType=" + resolvedType
5684                + " flags=" + flags
5685                + " filter=" + filter
5686                + " match=" + match
5687                + " activity=" + activity);
5688            filter.dump(new PrintStreamPrinter(System.out), "    ");
5689        }
5690        intent.setComponent(null);
5691        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5692                userId);
5693        // Find any earlier preferred or last chosen entries and nuke them
5694        findPreferredActivity(intent, resolvedType,
5695                flags, query, 0, false, true, false, userId);
5696        // Add the new activity as the last chosen for this filter
5697        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5698                "Setting last chosen");
5699    }
5700
5701    @Override
5702    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5703        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5704            return null;
5705        }
5706        final int userId = UserHandle.getCallingUserId();
5707        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5708        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5709                userId);
5710        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5711                false, false, false, userId);
5712    }
5713
5714    /**
5715     * Returns whether or not instant apps have been disabled remotely.
5716     */
5717    private boolean isEphemeralDisabled() {
5718        return mEphemeralAppsDisabled;
5719    }
5720
5721    private boolean isInstantAppAllowed(
5722            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5723            boolean skipPackageCheck) {
5724        if (mInstantAppResolverConnection == null) {
5725            return false;
5726        }
5727        if (mInstantAppInstallerActivity == null) {
5728            return false;
5729        }
5730        if (intent.getComponent() != null) {
5731            return false;
5732        }
5733        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5734            return false;
5735        }
5736        if (!skipPackageCheck && intent.getPackage() != null) {
5737            return false;
5738        }
5739        final boolean isWebUri = hasWebURI(intent);
5740        if (!isWebUri || intent.getData().getHost() == null) {
5741            return false;
5742        }
5743        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5744        // Or if there's already an ephemeral app installed that handles the action
5745        synchronized (mPackages) {
5746            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5747            for (int n = 0; n < count; n++) {
5748                final ResolveInfo info = resolvedActivities.get(n);
5749                final String packageName = info.activityInfo.packageName;
5750                final PackageSetting ps = mSettings.mPackages.get(packageName);
5751                if (ps != null) {
5752                    // only check domain verification status if the app is not a browser
5753                    if (!info.handleAllWebDataURI) {
5754                        // Try to get the status from User settings first
5755                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5756                        final int status = (int) (packedStatus >> 32);
5757                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5758                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5759                            if (DEBUG_EPHEMERAL) {
5760                                Slog.v(TAG, "DENY instant app;"
5761                                    + " pkg: " + packageName + ", status: " + status);
5762                            }
5763                            return false;
5764                        }
5765                    }
5766                    if (ps.getInstantApp(userId)) {
5767                        if (DEBUG_EPHEMERAL) {
5768                            Slog.v(TAG, "DENY instant app installed;"
5769                                    + " pkg: " + packageName);
5770                        }
5771                        return false;
5772                    }
5773                }
5774            }
5775        }
5776        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5777        return true;
5778    }
5779
5780    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5781            Intent origIntent, String resolvedType, String callingPackage,
5782            Bundle verificationBundle, int userId) {
5783        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5784                new InstantAppRequest(responseObj, origIntent, resolvedType,
5785                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5786        mHandler.sendMessage(msg);
5787    }
5788
5789    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5790            int flags, List<ResolveInfo> query, int userId) {
5791        if (query != null) {
5792            final int N = query.size();
5793            if (N == 1) {
5794                return query.get(0);
5795            } else if (N > 1) {
5796                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5797                // If there is more than one activity with the same priority,
5798                // then let the user decide between them.
5799                ResolveInfo r0 = query.get(0);
5800                ResolveInfo r1 = query.get(1);
5801                if (DEBUG_INTENT_MATCHING || debug) {
5802                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5803                            + r1.activityInfo.name + "=" + r1.priority);
5804                }
5805                // If the first activity has a higher priority, or a different
5806                // default, then it is always desirable to pick it.
5807                if (r0.priority != r1.priority
5808                        || r0.preferredOrder != r1.preferredOrder
5809                        || r0.isDefault != r1.isDefault) {
5810                    return query.get(0);
5811                }
5812                // If we have saved a preference for a preferred activity for
5813                // this Intent, use that.
5814                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5815                        flags, query, r0.priority, true, false, debug, userId);
5816                if (ri != null) {
5817                    return ri;
5818                }
5819                // If we have an ephemeral app, use it
5820                for (int i = 0; i < N; i++) {
5821                    ri = query.get(i);
5822                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5823                        final String packageName = ri.activityInfo.packageName;
5824                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5825                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5826                        final int status = (int)(packedStatus >> 32);
5827                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5828                            return ri;
5829                        }
5830                    }
5831                }
5832                ri = new ResolveInfo(mResolveInfo);
5833                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5834                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5835                // If all of the options come from the same package, show the application's
5836                // label and icon instead of the generic resolver's.
5837                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5838                // and then throw away the ResolveInfo itself, meaning that the caller loses
5839                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5840                // a fallback for this case; we only set the target package's resources on
5841                // the ResolveInfo, not the ActivityInfo.
5842                final String intentPackage = intent.getPackage();
5843                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5844                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5845                    ri.resolvePackageName = intentPackage;
5846                    if (userNeedsBadging(userId)) {
5847                        ri.noResourceId = true;
5848                    } else {
5849                        ri.icon = appi.icon;
5850                    }
5851                    ri.iconResourceId = appi.icon;
5852                    ri.labelRes = appi.labelRes;
5853                }
5854                ri.activityInfo.applicationInfo = new ApplicationInfo(
5855                        ri.activityInfo.applicationInfo);
5856                if (userId != 0) {
5857                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5858                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5859                }
5860                // Make sure that the resolver is displayable in car mode
5861                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5862                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5863                return ri;
5864            }
5865        }
5866        return null;
5867    }
5868
5869    /**
5870     * Return true if the given list is not empty and all of its contents have
5871     * an activityInfo with the given package name.
5872     */
5873    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5874        if (ArrayUtils.isEmpty(list)) {
5875            return false;
5876        }
5877        for (int i = 0, N = list.size(); i < N; i++) {
5878            final ResolveInfo ri = list.get(i);
5879            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5880            if (ai == null || !packageName.equals(ai.packageName)) {
5881                return false;
5882            }
5883        }
5884        return true;
5885    }
5886
5887    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5888            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5889        final int N = query.size();
5890        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5891                .get(userId);
5892        // Get the list of persistent preferred activities that handle the intent
5893        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5894        List<PersistentPreferredActivity> pprefs = ppir != null
5895                ? ppir.queryIntent(intent, resolvedType,
5896                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5897                        userId)
5898                : null;
5899        if (pprefs != null && pprefs.size() > 0) {
5900            final int M = pprefs.size();
5901            for (int i=0; i<M; i++) {
5902                final PersistentPreferredActivity ppa = pprefs.get(i);
5903                if (DEBUG_PREFERRED || debug) {
5904                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5905                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5906                            + "\n  component=" + ppa.mComponent);
5907                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5908                }
5909                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5910                        flags | MATCH_DISABLED_COMPONENTS, userId);
5911                if (DEBUG_PREFERRED || debug) {
5912                    Slog.v(TAG, "Found persistent preferred activity:");
5913                    if (ai != null) {
5914                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5915                    } else {
5916                        Slog.v(TAG, "  null");
5917                    }
5918                }
5919                if (ai == null) {
5920                    // This previously registered persistent preferred activity
5921                    // component is no longer known. Ignore it and do NOT remove it.
5922                    continue;
5923                }
5924                for (int j=0; j<N; j++) {
5925                    final ResolveInfo ri = query.get(j);
5926                    if (!ri.activityInfo.applicationInfo.packageName
5927                            .equals(ai.applicationInfo.packageName)) {
5928                        continue;
5929                    }
5930                    if (!ri.activityInfo.name.equals(ai.name)) {
5931                        continue;
5932                    }
5933                    //  Found a persistent preference that can handle the intent.
5934                    if (DEBUG_PREFERRED || debug) {
5935                        Slog.v(TAG, "Returning persistent preferred activity: " +
5936                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5937                    }
5938                    return ri;
5939                }
5940            }
5941        }
5942        return null;
5943    }
5944
5945    // TODO: handle preferred activities missing while user has amnesia
5946    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5947            List<ResolveInfo> query, int priority, boolean always,
5948            boolean removeMatches, boolean debug, int userId) {
5949        if (!sUserManager.exists(userId)) return null;
5950        final int callingUid = Binder.getCallingUid();
5951        flags = updateFlagsForResolve(
5952                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5953        intent = updateIntentForResolve(intent);
5954        // writer
5955        synchronized (mPackages) {
5956            // Try to find a matching persistent preferred activity.
5957            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5958                    debug, userId);
5959
5960            // If a persistent preferred activity matched, use it.
5961            if (pri != null) {
5962                return pri;
5963            }
5964
5965            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5966            // Get the list of preferred activities that handle the intent
5967            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5968            List<PreferredActivity> prefs = pir != null
5969                    ? pir.queryIntent(intent, resolvedType,
5970                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5971                            userId)
5972                    : null;
5973            if (prefs != null && prefs.size() > 0) {
5974                boolean changed = false;
5975                try {
5976                    // First figure out how good the original match set is.
5977                    // We will only allow preferred activities that came
5978                    // from the same match quality.
5979                    int match = 0;
5980
5981                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5982
5983                    final int N = query.size();
5984                    for (int j=0; j<N; j++) {
5985                        final ResolveInfo ri = query.get(j);
5986                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5987                                + ": 0x" + Integer.toHexString(match));
5988                        if (ri.match > match) {
5989                            match = ri.match;
5990                        }
5991                    }
5992
5993                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5994                            + Integer.toHexString(match));
5995
5996                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5997                    final int M = prefs.size();
5998                    for (int i=0; i<M; i++) {
5999                        final PreferredActivity pa = prefs.get(i);
6000                        if (DEBUG_PREFERRED || debug) {
6001                            Slog.v(TAG, "Checking PreferredActivity ds="
6002                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6003                                    + "\n  component=" + pa.mPref.mComponent);
6004                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6005                        }
6006                        if (pa.mPref.mMatch != match) {
6007                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6008                                    + Integer.toHexString(pa.mPref.mMatch));
6009                            continue;
6010                        }
6011                        // If it's not an "always" type preferred activity and that's what we're
6012                        // looking for, skip it.
6013                        if (always && !pa.mPref.mAlways) {
6014                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6015                            continue;
6016                        }
6017                        final ActivityInfo ai = getActivityInfo(
6018                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6019                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6020                                userId);
6021                        if (DEBUG_PREFERRED || debug) {
6022                            Slog.v(TAG, "Found preferred activity:");
6023                            if (ai != null) {
6024                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6025                            } else {
6026                                Slog.v(TAG, "  null");
6027                            }
6028                        }
6029                        if (ai == null) {
6030                            // This previously registered preferred activity
6031                            // component is no longer known.  Most likely an update
6032                            // to the app was installed and in the new version this
6033                            // component no longer exists.  Clean it up by removing
6034                            // it from the preferred activities list, and skip it.
6035                            Slog.w(TAG, "Removing dangling preferred activity: "
6036                                    + pa.mPref.mComponent);
6037                            pir.removeFilter(pa);
6038                            changed = true;
6039                            continue;
6040                        }
6041                        for (int j=0; j<N; j++) {
6042                            final ResolveInfo ri = query.get(j);
6043                            if (!ri.activityInfo.applicationInfo.packageName
6044                                    .equals(ai.applicationInfo.packageName)) {
6045                                continue;
6046                            }
6047                            if (!ri.activityInfo.name.equals(ai.name)) {
6048                                continue;
6049                            }
6050
6051                            if (removeMatches) {
6052                                pir.removeFilter(pa);
6053                                changed = true;
6054                                if (DEBUG_PREFERRED) {
6055                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6056                                }
6057                                break;
6058                            }
6059
6060                            // Okay we found a previously set preferred or last chosen app.
6061                            // If the result set is different from when this
6062                            // was created, and is not a subset of the preferred set, we need to
6063                            // clear it and re-ask the user their preference, if we're looking for
6064                            // an "always" type entry.
6065                            if (always && !pa.mPref.sameSet(query)) {
6066                                if (pa.mPref.isSuperset(query)) {
6067                                    // some components of the set are no longer present in
6068                                    // the query, but the preferred activity can still be reused
6069                                    if (DEBUG_PREFERRED) {
6070                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6071                                                + " still valid as only non-preferred components"
6072                                                + " were removed for " + intent + " type "
6073                                                + resolvedType);
6074                                    }
6075                                    // remove obsolete components and re-add the up-to-date filter
6076                                    PreferredActivity freshPa = new PreferredActivity(pa,
6077                                            pa.mPref.mMatch,
6078                                            pa.mPref.discardObsoleteComponents(query),
6079                                            pa.mPref.mComponent,
6080                                            pa.mPref.mAlways);
6081                                    pir.removeFilter(pa);
6082                                    pir.addFilter(freshPa);
6083                                    changed = true;
6084                                } else {
6085                                    Slog.i(TAG,
6086                                            "Result set changed, dropping preferred activity for "
6087                                                    + intent + " type " + resolvedType);
6088                                    if (DEBUG_PREFERRED) {
6089                                        Slog.v(TAG, "Removing preferred activity since set changed "
6090                                                + pa.mPref.mComponent);
6091                                    }
6092                                    pir.removeFilter(pa);
6093                                    // Re-add the filter as a "last chosen" entry (!always)
6094                                    PreferredActivity lastChosen = new PreferredActivity(
6095                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6096                                    pir.addFilter(lastChosen);
6097                                    changed = true;
6098                                    return null;
6099                                }
6100                            }
6101
6102                            // Yay! Either the set matched or we're looking for the last chosen
6103                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6104                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6105                            return ri;
6106                        }
6107                    }
6108                } finally {
6109                    if (changed) {
6110                        if (DEBUG_PREFERRED) {
6111                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6112                        }
6113                        scheduleWritePackageRestrictionsLocked(userId);
6114                    }
6115                }
6116            }
6117        }
6118        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6119        return null;
6120    }
6121
6122    /*
6123     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6124     */
6125    @Override
6126    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6127            int targetUserId) {
6128        mContext.enforceCallingOrSelfPermission(
6129                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6130        List<CrossProfileIntentFilter> matches =
6131                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6132        if (matches != null) {
6133            int size = matches.size();
6134            for (int i = 0; i < size; i++) {
6135                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6136            }
6137        }
6138        if (hasWebURI(intent)) {
6139            // cross-profile app linking works only towards the parent.
6140            final int callingUid = Binder.getCallingUid();
6141            final UserInfo parent = getProfileParent(sourceUserId);
6142            synchronized(mPackages) {
6143                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6144                        false /*includeInstantApps*/);
6145                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6146                        intent, resolvedType, flags, sourceUserId, parent.id);
6147                return xpDomainInfo != null;
6148            }
6149        }
6150        return false;
6151    }
6152
6153    private UserInfo getProfileParent(int userId) {
6154        final long identity = Binder.clearCallingIdentity();
6155        try {
6156            return sUserManager.getProfileParent(userId);
6157        } finally {
6158            Binder.restoreCallingIdentity(identity);
6159        }
6160    }
6161
6162    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6163            String resolvedType, int userId) {
6164        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6165        if (resolver != null) {
6166            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6167        }
6168        return null;
6169    }
6170
6171    @Override
6172    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6173            String resolvedType, int flags, int userId) {
6174        try {
6175            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6176
6177            return new ParceledListSlice<>(
6178                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6179        } finally {
6180            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6181        }
6182    }
6183
6184    /**
6185     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6186     * instant, returns {@code null}.
6187     */
6188    private String getInstantAppPackageName(int callingUid) {
6189        synchronized (mPackages) {
6190            // If the caller is an isolated app use the owner's uid for the lookup.
6191            if (Process.isIsolated(callingUid)) {
6192                callingUid = mIsolatedOwners.get(callingUid);
6193            }
6194            final int appId = UserHandle.getAppId(callingUid);
6195            final Object obj = mSettings.getUserIdLPr(appId);
6196            if (obj instanceof PackageSetting) {
6197                final PackageSetting ps = (PackageSetting) obj;
6198                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6199                return isInstantApp ? ps.pkg.packageName : null;
6200            }
6201        }
6202        return null;
6203    }
6204
6205    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6206            String resolvedType, int flags, int userId) {
6207        return queryIntentActivitiesInternal(
6208                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6209                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6210    }
6211
6212    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6213            String resolvedType, int flags, int filterCallingUid, int userId,
6214            boolean resolveForStart, boolean allowDynamicSplits) {
6215        if (!sUserManager.exists(userId)) return Collections.emptyList();
6216        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6217        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6218                false /* requireFullPermission */, false /* checkShell */,
6219                "query intent activities");
6220        final String pkgName = intent.getPackage();
6221        ComponentName comp = intent.getComponent();
6222        if (comp == null) {
6223            if (intent.getSelector() != null) {
6224                intent = intent.getSelector();
6225                comp = intent.getComponent();
6226            }
6227        }
6228
6229        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6230                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6231        if (comp != null) {
6232            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6233            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6234            if (ai != null) {
6235                // When specifying an explicit component, we prevent the activity from being
6236                // used when either 1) the calling package is normal and the activity is within
6237                // an ephemeral application or 2) the calling package is ephemeral and the
6238                // activity is not visible to ephemeral applications.
6239                final boolean matchInstantApp =
6240                        (flags & PackageManager.MATCH_INSTANT) != 0;
6241                final boolean matchVisibleToInstantAppOnly =
6242                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6243                final boolean matchExplicitlyVisibleOnly =
6244                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6245                final boolean isCallerInstantApp =
6246                        instantAppPkgName != null;
6247                final boolean isTargetSameInstantApp =
6248                        comp.getPackageName().equals(instantAppPkgName);
6249                final boolean isTargetInstantApp =
6250                        (ai.applicationInfo.privateFlags
6251                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6252                final boolean isTargetVisibleToInstantApp =
6253                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6254                final boolean isTargetExplicitlyVisibleToInstantApp =
6255                        isTargetVisibleToInstantApp
6256                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6257                final boolean isTargetHiddenFromInstantApp =
6258                        !isTargetVisibleToInstantApp
6259                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6260                final boolean blockResolution =
6261                        !isTargetSameInstantApp
6262                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6263                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6264                                        && isTargetHiddenFromInstantApp));
6265                if (!blockResolution) {
6266                    final ResolveInfo ri = new ResolveInfo();
6267                    ri.activityInfo = ai;
6268                    list.add(ri);
6269                }
6270            }
6271            return applyPostResolutionFilter(
6272                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6273        }
6274
6275        // reader
6276        boolean sortResult = false;
6277        boolean addEphemeral = false;
6278        List<ResolveInfo> result;
6279        final boolean ephemeralDisabled = isEphemeralDisabled();
6280        synchronized (mPackages) {
6281            if (pkgName == null) {
6282                List<CrossProfileIntentFilter> matchingFilters =
6283                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6284                // Check for results that need to skip the current profile.
6285                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6286                        resolvedType, flags, userId);
6287                if (xpResolveInfo != null) {
6288                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6289                    xpResult.add(xpResolveInfo);
6290                    return applyPostResolutionFilter(
6291                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6292                            allowDynamicSplits, filterCallingUid, userId);
6293                }
6294
6295                // Check for results in the current profile.
6296                result = filterIfNotSystemUser(mActivities.queryIntent(
6297                        intent, resolvedType, flags, userId), userId);
6298                addEphemeral = !ephemeralDisabled
6299                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6300                // Check for cross profile results.
6301                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6302                xpResolveInfo = queryCrossProfileIntents(
6303                        matchingFilters, intent, resolvedType, flags, userId,
6304                        hasNonNegativePriorityResult);
6305                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6306                    boolean isVisibleToUser = filterIfNotSystemUser(
6307                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6308                    if (isVisibleToUser) {
6309                        result.add(xpResolveInfo);
6310                        sortResult = true;
6311                    }
6312                }
6313                if (hasWebURI(intent)) {
6314                    CrossProfileDomainInfo xpDomainInfo = null;
6315                    final UserInfo parent = getProfileParent(userId);
6316                    if (parent != null) {
6317                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6318                                flags, userId, parent.id);
6319                    }
6320                    if (xpDomainInfo != null) {
6321                        if (xpResolveInfo != null) {
6322                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6323                            // in the result.
6324                            result.remove(xpResolveInfo);
6325                        }
6326                        if (result.size() == 0 && !addEphemeral) {
6327                            // No result in current profile, but found candidate in parent user.
6328                            // And we are not going to add emphemeral app, so we can return the
6329                            // result straight away.
6330                            result.add(xpDomainInfo.resolveInfo);
6331                            return applyPostResolutionFilter(result, instantAppPkgName,
6332                                    allowDynamicSplits, filterCallingUid, userId);
6333                        }
6334                    } else if (result.size() <= 1 && !addEphemeral) {
6335                        // No result in parent user and <= 1 result in current profile, and we
6336                        // are not going to add emphemeral app, so we can return the result without
6337                        // further processing.
6338                        return applyPostResolutionFilter(result, instantAppPkgName,
6339                                allowDynamicSplits, filterCallingUid, userId);
6340                    }
6341                    // We have more than one candidate (combining results from current and parent
6342                    // profile), so we need filtering and sorting.
6343                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6344                            intent, flags, result, xpDomainInfo, userId);
6345                    sortResult = true;
6346                }
6347            } else {
6348                final PackageParser.Package pkg = mPackages.get(pkgName);
6349                result = null;
6350                if (pkg != null) {
6351                    result = filterIfNotSystemUser(
6352                            mActivities.queryIntentForPackage(
6353                                    intent, resolvedType, flags, pkg.activities, userId),
6354                            userId);
6355                }
6356                if (result == null || result.size() == 0) {
6357                    // the caller wants to resolve for a particular package; however, there
6358                    // were no installed results, so, try to find an ephemeral result
6359                    addEphemeral = !ephemeralDisabled
6360                            && isInstantAppAllowed(
6361                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6362                    if (result == null) {
6363                        result = new ArrayList<>();
6364                    }
6365                }
6366            }
6367        }
6368        if (addEphemeral) {
6369            result = maybeAddInstantAppInstaller(
6370                    result, intent, resolvedType, flags, userId, resolveForStart);
6371        }
6372        if (sortResult) {
6373            Collections.sort(result, mResolvePrioritySorter);
6374        }
6375        return applyPostResolutionFilter(
6376                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6377    }
6378
6379    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6380            String resolvedType, int flags, int userId, boolean resolveForStart) {
6381        // first, check to see if we've got an instant app already installed
6382        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6383        ResolveInfo localInstantApp = null;
6384        boolean blockResolution = false;
6385        if (!alreadyResolvedLocally) {
6386            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6387                    flags
6388                        | PackageManager.GET_RESOLVED_FILTER
6389                        | PackageManager.MATCH_INSTANT
6390                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6391                    userId);
6392            for (int i = instantApps.size() - 1; i >= 0; --i) {
6393                final ResolveInfo info = instantApps.get(i);
6394                final String packageName = info.activityInfo.packageName;
6395                final PackageSetting ps = mSettings.mPackages.get(packageName);
6396                if (ps.getInstantApp(userId)) {
6397                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6398                    final int status = (int)(packedStatus >> 32);
6399                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6400                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6401                        // there's a local instant application installed, but, the user has
6402                        // chosen to never use it; skip resolution and don't acknowledge
6403                        // an instant application is even available
6404                        if (DEBUG_EPHEMERAL) {
6405                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6406                        }
6407                        blockResolution = true;
6408                        break;
6409                    } else {
6410                        // we have a locally installed instant application; skip resolution
6411                        // but acknowledge there's an instant application available
6412                        if (DEBUG_EPHEMERAL) {
6413                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6414                        }
6415                        localInstantApp = info;
6416                        break;
6417                    }
6418                }
6419            }
6420        }
6421        // no app installed, let's see if one's available
6422        AuxiliaryResolveInfo auxiliaryResponse = null;
6423        if (!blockResolution) {
6424            if (localInstantApp == null) {
6425                // we don't have an instant app locally, resolve externally
6426                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6427                final InstantAppRequest requestObject = new InstantAppRequest(
6428                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6429                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6430                        resolveForStart);
6431                auxiliaryResponse =
6432                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6433                                mContext, mInstantAppResolverConnection, requestObject);
6434                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6435            } else {
6436                // we have an instant application locally, but, we can't admit that since
6437                // callers shouldn't be able to determine prior browsing. create a dummy
6438                // auxiliary response so the downstream code behaves as if there's an
6439                // instant application available externally. when it comes time to start
6440                // the instant application, we'll do the right thing.
6441                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6442                auxiliaryResponse = new AuxiliaryResolveInfo(
6443                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6444                        ai.versionCode, null /*failureIntent*/);
6445            }
6446        }
6447        if (auxiliaryResponse != null) {
6448            if (DEBUG_EPHEMERAL) {
6449                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6450            }
6451            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6452            final PackageSetting ps =
6453                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6454            if (ps != null) {
6455                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6456                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6457                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6458                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6459                // make sure this resolver is the default
6460                ephemeralInstaller.isDefault = true;
6461                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6462                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6463                // add a non-generic filter
6464                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6465                ephemeralInstaller.filter.addDataPath(
6466                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6467                ephemeralInstaller.isInstantAppAvailable = true;
6468                result.add(ephemeralInstaller);
6469            }
6470        }
6471        return result;
6472    }
6473
6474    private static class CrossProfileDomainInfo {
6475        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6476        ResolveInfo resolveInfo;
6477        /* Best domain verification status of the activities found in the other profile */
6478        int bestDomainVerificationStatus;
6479    }
6480
6481    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6482            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6483        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6484                sourceUserId)) {
6485            return null;
6486        }
6487        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6488                resolvedType, flags, parentUserId);
6489
6490        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6491            return null;
6492        }
6493        CrossProfileDomainInfo result = null;
6494        int size = resultTargetUser.size();
6495        for (int i = 0; i < size; i++) {
6496            ResolveInfo riTargetUser = resultTargetUser.get(i);
6497            // Intent filter verification is only for filters that specify a host. So don't return
6498            // those that handle all web uris.
6499            if (riTargetUser.handleAllWebDataURI) {
6500                continue;
6501            }
6502            String packageName = riTargetUser.activityInfo.packageName;
6503            PackageSetting ps = mSettings.mPackages.get(packageName);
6504            if (ps == null) {
6505                continue;
6506            }
6507            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6508            int status = (int)(verificationState >> 32);
6509            if (result == null) {
6510                result = new CrossProfileDomainInfo();
6511                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6512                        sourceUserId, parentUserId);
6513                result.bestDomainVerificationStatus = status;
6514            } else {
6515                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6516                        result.bestDomainVerificationStatus);
6517            }
6518        }
6519        // Don't consider matches with status NEVER across profiles.
6520        if (result != null && result.bestDomainVerificationStatus
6521                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6522            return null;
6523        }
6524        return result;
6525    }
6526
6527    /**
6528     * Verification statuses are ordered from the worse to the best, except for
6529     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6530     */
6531    private int bestDomainVerificationStatus(int status1, int status2) {
6532        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6533            return status2;
6534        }
6535        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6536            return status1;
6537        }
6538        return (int) MathUtils.max(status1, status2);
6539    }
6540
6541    private boolean isUserEnabled(int userId) {
6542        long callingId = Binder.clearCallingIdentity();
6543        try {
6544            UserInfo userInfo = sUserManager.getUserInfo(userId);
6545            return userInfo != null && userInfo.isEnabled();
6546        } finally {
6547            Binder.restoreCallingIdentity(callingId);
6548        }
6549    }
6550
6551    /**
6552     * Filter out activities with systemUserOnly flag set, when current user is not System.
6553     *
6554     * @return filtered list
6555     */
6556    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6557        if (userId == UserHandle.USER_SYSTEM) {
6558            return resolveInfos;
6559        }
6560        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6561            ResolveInfo info = resolveInfos.get(i);
6562            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6563                resolveInfos.remove(i);
6564            }
6565        }
6566        return resolveInfos;
6567    }
6568
6569    /**
6570     * Filters out ephemeral activities.
6571     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6572     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6573     *
6574     * @param resolveInfos The pre-filtered list of resolved activities
6575     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6576     *          is performed.
6577     * @return A filtered list of resolved activities.
6578     */
6579    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6580            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6581        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6582            final ResolveInfo info = resolveInfos.get(i);
6583            // allow activities that are defined in the provided package
6584            if (allowDynamicSplits
6585                    && info.activityInfo.splitName != null
6586                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6587                            info.activityInfo.splitName)) {
6588                if (mInstantAppInstallerInfo == null) {
6589                    if (DEBUG_INSTALL) {
6590                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6591                    }
6592                    resolveInfos.remove(i);
6593                    continue;
6594                }
6595                // requested activity is defined in a split that hasn't been installed yet.
6596                // add the installer to the resolve list
6597                if (DEBUG_INSTALL) {
6598                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6599                }
6600                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6601                final ComponentName installFailureActivity = findInstallFailureActivity(
6602                        info.activityInfo.packageName,  filterCallingUid, userId);
6603                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6604                        info.activityInfo.packageName, info.activityInfo.splitName,
6605                        installFailureActivity,
6606                        info.activityInfo.applicationInfo.versionCode,
6607                        null /*failureIntent*/);
6608                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6609                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6610                // add a non-generic filter
6611                installerInfo.filter = new IntentFilter();
6612
6613                // This resolve info may appear in the chooser UI, so let us make it
6614                // look as the one it replaces as far as the user is concerned which
6615                // requires loading the correct label and icon for the resolve info.
6616                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6617                installerInfo.labelRes = info.resolveLabelResId();
6618                installerInfo.icon = info.resolveIconResId();
6619
6620                // propagate priority/preferred order/default
6621                installerInfo.priority = info.priority;
6622                installerInfo.preferredOrder = info.preferredOrder;
6623                installerInfo.isDefault = info.isDefault;
6624                resolveInfos.set(i, installerInfo);
6625                continue;
6626            }
6627            // caller is a full app, don't need to apply any other filtering
6628            if (ephemeralPkgName == null) {
6629                continue;
6630            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6631                // caller is same app; don't need to apply any other filtering
6632                continue;
6633            }
6634            // allow activities that have been explicitly exposed to ephemeral apps
6635            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6636            if (!isEphemeralApp
6637                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6638                continue;
6639            }
6640            resolveInfos.remove(i);
6641        }
6642        return resolveInfos;
6643    }
6644
6645    /**
6646     * Returns the activity component that can handle install failures.
6647     * <p>By default, the instant application installer handles failures. However, an
6648     * application may want to handle failures on its own. Applications do this by
6649     * creating an activity with an intent filter that handles the action
6650     * {@link Intent#ACTION_INSTALL_FAILURE}.
6651     */
6652    private @Nullable ComponentName findInstallFailureActivity(
6653            String packageName, int filterCallingUid, int userId) {
6654        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6655        failureActivityIntent.setPackage(packageName);
6656        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6657        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6658                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6659                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6660        final int NR = result.size();
6661        if (NR > 0) {
6662            for (int i = 0; i < NR; i++) {
6663                final ResolveInfo info = result.get(i);
6664                if (info.activityInfo.splitName != null) {
6665                    continue;
6666                }
6667                return new ComponentName(packageName, info.activityInfo.name);
6668            }
6669        }
6670        return null;
6671    }
6672
6673    /**
6674     * @param resolveInfos list of resolve infos in descending priority order
6675     * @return if the list contains a resolve info with non-negative priority
6676     */
6677    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6678        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6679    }
6680
6681    private static boolean hasWebURI(Intent intent) {
6682        if (intent.getData() == null) {
6683            return false;
6684        }
6685        final String scheme = intent.getScheme();
6686        if (TextUtils.isEmpty(scheme)) {
6687            return false;
6688        }
6689        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6690    }
6691
6692    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6693            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6694            int userId) {
6695        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6696
6697        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6698            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6699                    candidates.size());
6700        }
6701
6702        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6703        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6704        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6705        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6706        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6707        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6708
6709        synchronized (mPackages) {
6710            final int count = candidates.size();
6711            // First, try to use linked apps. Partition the candidates into four lists:
6712            // one for the final results, one for the "do not use ever", one for "undefined status"
6713            // and finally one for "browser app type".
6714            for (int n=0; n<count; n++) {
6715                ResolveInfo info = candidates.get(n);
6716                String packageName = info.activityInfo.packageName;
6717                PackageSetting ps = mSettings.mPackages.get(packageName);
6718                if (ps != null) {
6719                    // Add to the special match all list (Browser use case)
6720                    if (info.handleAllWebDataURI) {
6721                        matchAllList.add(info);
6722                        continue;
6723                    }
6724                    // Try to get the status from User settings first
6725                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6726                    int status = (int)(packedStatus >> 32);
6727                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6728                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6729                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6730                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6731                                    + " : linkgen=" + linkGeneration);
6732                        }
6733                        // Use link-enabled generation as preferredOrder, i.e.
6734                        // prefer newly-enabled over earlier-enabled.
6735                        info.preferredOrder = linkGeneration;
6736                        alwaysList.add(info);
6737                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6738                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6739                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6740                        }
6741                        neverList.add(info);
6742                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6743                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6744                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6745                        }
6746                        alwaysAskList.add(info);
6747                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6748                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6749                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6750                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6751                        }
6752                        undefinedList.add(info);
6753                    }
6754                }
6755            }
6756
6757            // We'll want to include browser possibilities in a few cases
6758            boolean includeBrowser = false;
6759
6760            // First try to add the "always" resolution(s) for the current user, if any
6761            if (alwaysList.size() > 0) {
6762                result.addAll(alwaysList);
6763            } else {
6764                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6765                result.addAll(undefinedList);
6766                // Maybe add one for the other profile.
6767                if (xpDomainInfo != null && (
6768                        xpDomainInfo.bestDomainVerificationStatus
6769                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6770                    result.add(xpDomainInfo.resolveInfo);
6771                }
6772                includeBrowser = true;
6773            }
6774
6775            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6776            // If there were 'always' entries their preferred order has been set, so we also
6777            // back that off to make the alternatives equivalent
6778            if (alwaysAskList.size() > 0) {
6779                for (ResolveInfo i : result) {
6780                    i.preferredOrder = 0;
6781                }
6782                result.addAll(alwaysAskList);
6783                includeBrowser = true;
6784            }
6785
6786            if (includeBrowser) {
6787                // Also add browsers (all of them or only the default one)
6788                if (DEBUG_DOMAIN_VERIFICATION) {
6789                    Slog.v(TAG, "   ...including browsers in candidate set");
6790                }
6791                if ((matchFlags & MATCH_ALL) != 0) {
6792                    result.addAll(matchAllList);
6793                } else {
6794                    // Browser/generic handling case.  If there's a default browser, go straight
6795                    // to that (but only if there is no other higher-priority match).
6796                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6797                    int maxMatchPrio = 0;
6798                    ResolveInfo defaultBrowserMatch = null;
6799                    final int numCandidates = matchAllList.size();
6800                    for (int n = 0; n < numCandidates; n++) {
6801                        ResolveInfo info = matchAllList.get(n);
6802                        // track the highest overall match priority...
6803                        if (info.priority > maxMatchPrio) {
6804                            maxMatchPrio = info.priority;
6805                        }
6806                        // ...and the highest-priority default browser match
6807                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6808                            if (defaultBrowserMatch == null
6809                                    || (defaultBrowserMatch.priority < info.priority)) {
6810                                if (debug) {
6811                                    Slog.v(TAG, "Considering default browser match " + info);
6812                                }
6813                                defaultBrowserMatch = info;
6814                            }
6815                        }
6816                    }
6817                    if (defaultBrowserMatch != null
6818                            && defaultBrowserMatch.priority >= maxMatchPrio
6819                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6820                    {
6821                        if (debug) {
6822                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6823                        }
6824                        result.add(defaultBrowserMatch);
6825                    } else {
6826                        result.addAll(matchAllList);
6827                    }
6828                }
6829
6830                // If there is nothing selected, add all candidates and remove the ones that the user
6831                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6832                if (result.size() == 0) {
6833                    result.addAll(candidates);
6834                    result.removeAll(neverList);
6835                }
6836            }
6837        }
6838        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6839            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6840                    result.size());
6841            for (ResolveInfo info : result) {
6842                Slog.v(TAG, "  + " + info.activityInfo);
6843            }
6844        }
6845        return result;
6846    }
6847
6848    // Returns a packed value as a long:
6849    //
6850    // high 'int'-sized word: link status: undefined/ask/never/always.
6851    // low 'int'-sized word: relative priority among 'always' results.
6852    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6853        long result = ps.getDomainVerificationStatusForUser(userId);
6854        // if none available, get the master status
6855        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6856            if (ps.getIntentFilterVerificationInfo() != null) {
6857                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6858            }
6859        }
6860        return result;
6861    }
6862
6863    private ResolveInfo querySkipCurrentProfileIntents(
6864            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6865            int flags, int sourceUserId) {
6866        if (matchingFilters != null) {
6867            int size = matchingFilters.size();
6868            for (int i = 0; i < size; i ++) {
6869                CrossProfileIntentFilter filter = matchingFilters.get(i);
6870                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6871                    // Checking if there are activities in the target user that can handle the
6872                    // intent.
6873                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6874                            resolvedType, flags, sourceUserId);
6875                    if (resolveInfo != null) {
6876                        return resolveInfo;
6877                    }
6878                }
6879            }
6880        }
6881        return null;
6882    }
6883
6884    // Return matching ResolveInfo in target user if any.
6885    private ResolveInfo queryCrossProfileIntents(
6886            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6887            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6888        if (matchingFilters != null) {
6889            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6890            // match the same intent. For performance reasons, it is better not to
6891            // run queryIntent twice for the same userId
6892            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6893            int size = matchingFilters.size();
6894            for (int i = 0; i < size; i++) {
6895                CrossProfileIntentFilter filter = matchingFilters.get(i);
6896                int targetUserId = filter.getTargetUserId();
6897                boolean skipCurrentProfile =
6898                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6899                boolean skipCurrentProfileIfNoMatchFound =
6900                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6901                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6902                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6903                    // Checking if there are activities in the target user that can handle the
6904                    // intent.
6905                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6906                            resolvedType, flags, sourceUserId);
6907                    if (resolveInfo != null) return resolveInfo;
6908                    alreadyTriedUserIds.put(targetUserId, true);
6909                }
6910            }
6911        }
6912        return null;
6913    }
6914
6915    /**
6916     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6917     * will forward the intent to the filter's target user.
6918     * Otherwise, returns null.
6919     */
6920    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6921            String resolvedType, int flags, int sourceUserId) {
6922        int targetUserId = filter.getTargetUserId();
6923        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6924                resolvedType, flags, targetUserId);
6925        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6926            // If all the matches in the target profile are suspended, return null.
6927            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6928                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6929                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6930                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6931                            targetUserId);
6932                }
6933            }
6934        }
6935        return null;
6936    }
6937
6938    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6939            int sourceUserId, int targetUserId) {
6940        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6941        long ident = Binder.clearCallingIdentity();
6942        boolean targetIsProfile;
6943        try {
6944            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6945        } finally {
6946            Binder.restoreCallingIdentity(ident);
6947        }
6948        String className;
6949        if (targetIsProfile) {
6950            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6951        } else {
6952            className = FORWARD_INTENT_TO_PARENT;
6953        }
6954        ComponentName forwardingActivityComponentName = new ComponentName(
6955                mAndroidApplication.packageName, className);
6956        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6957                sourceUserId);
6958        if (!targetIsProfile) {
6959            forwardingActivityInfo.showUserIcon = targetUserId;
6960            forwardingResolveInfo.noResourceId = true;
6961        }
6962        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6963        forwardingResolveInfo.priority = 0;
6964        forwardingResolveInfo.preferredOrder = 0;
6965        forwardingResolveInfo.match = 0;
6966        forwardingResolveInfo.isDefault = true;
6967        forwardingResolveInfo.filter = filter;
6968        forwardingResolveInfo.targetUserId = targetUserId;
6969        return forwardingResolveInfo;
6970    }
6971
6972    @Override
6973    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6974            Intent[] specifics, String[] specificTypes, Intent intent,
6975            String resolvedType, int flags, int userId) {
6976        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6977                specificTypes, intent, resolvedType, flags, userId));
6978    }
6979
6980    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6981            Intent[] specifics, String[] specificTypes, Intent intent,
6982            String resolvedType, int flags, int userId) {
6983        if (!sUserManager.exists(userId)) return Collections.emptyList();
6984        final int callingUid = Binder.getCallingUid();
6985        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6986                false /*includeInstantApps*/);
6987        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
6988                false /*requireFullPermission*/, false /*checkShell*/,
6989                "query intent activity options");
6990        final String resultsAction = intent.getAction();
6991
6992        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6993                | PackageManager.GET_RESOLVED_FILTER, userId);
6994
6995        if (DEBUG_INTENT_MATCHING) {
6996            Log.v(TAG, "Query " + intent + ": " + results);
6997        }
6998
6999        int specificsPos = 0;
7000        int N;
7001
7002        // todo: note that the algorithm used here is O(N^2).  This
7003        // isn't a problem in our current environment, but if we start running
7004        // into situations where we have more than 5 or 10 matches then this
7005        // should probably be changed to something smarter...
7006
7007        // First we go through and resolve each of the specific items
7008        // that were supplied, taking care of removing any corresponding
7009        // duplicate items in the generic resolve list.
7010        if (specifics != null) {
7011            for (int i=0; i<specifics.length; i++) {
7012                final Intent sintent = specifics[i];
7013                if (sintent == null) {
7014                    continue;
7015                }
7016
7017                if (DEBUG_INTENT_MATCHING) {
7018                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7019                }
7020
7021                String action = sintent.getAction();
7022                if (resultsAction != null && resultsAction.equals(action)) {
7023                    // If this action was explicitly requested, then don't
7024                    // remove things that have it.
7025                    action = null;
7026                }
7027
7028                ResolveInfo ri = null;
7029                ActivityInfo ai = null;
7030
7031                ComponentName comp = sintent.getComponent();
7032                if (comp == null) {
7033                    ri = resolveIntent(
7034                        sintent,
7035                        specificTypes != null ? specificTypes[i] : null,
7036                            flags, userId);
7037                    if (ri == null) {
7038                        continue;
7039                    }
7040                    if (ri == mResolveInfo) {
7041                        // ACK!  Must do something better with this.
7042                    }
7043                    ai = ri.activityInfo;
7044                    comp = new ComponentName(ai.applicationInfo.packageName,
7045                            ai.name);
7046                } else {
7047                    ai = getActivityInfo(comp, flags, userId);
7048                    if (ai == null) {
7049                        continue;
7050                    }
7051                }
7052
7053                // Look for any generic query activities that are duplicates
7054                // of this specific one, and remove them from the results.
7055                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7056                N = results.size();
7057                int j;
7058                for (j=specificsPos; j<N; j++) {
7059                    ResolveInfo sri = results.get(j);
7060                    if ((sri.activityInfo.name.equals(comp.getClassName())
7061                            && sri.activityInfo.applicationInfo.packageName.equals(
7062                                    comp.getPackageName()))
7063                        || (action != null && sri.filter.matchAction(action))) {
7064                        results.remove(j);
7065                        if (DEBUG_INTENT_MATCHING) Log.v(
7066                            TAG, "Removing duplicate item from " + j
7067                            + " due to specific " + specificsPos);
7068                        if (ri == null) {
7069                            ri = sri;
7070                        }
7071                        j--;
7072                        N--;
7073                    }
7074                }
7075
7076                // Add this specific item to its proper place.
7077                if (ri == null) {
7078                    ri = new ResolveInfo();
7079                    ri.activityInfo = ai;
7080                }
7081                results.add(specificsPos, ri);
7082                ri.specificIndex = i;
7083                specificsPos++;
7084            }
7085        }
7086
7087        // Now we go through the remaining generic results and remove any
7088        // duplicate actions that are found here.
7089        N = results.size();
7090        for (int i=specificsPos; i<N-1; i++) {
7091            final ResolveInfo rii = results.get(i);
7092            if (rii.filter == null) {
7093                continue;
7094            }
7095
7096            // Iterate over all of the actions of this result's intent
7097            // filter...  typically this should be just one.
7098            final Iterator<String> it = rii.filter.actionsIterator();
7099            if (it == null) {
7100                continue;
7101            }
7102            while (it.hasNext()) {
7103                final String action = it.next();
7104                if (resultsAction != null && resultsAction.equals(action)) {
7105                    // If this action was explicitly requested, then don't
7106                    // remove things that have it.
7107                    continue;
7108                }
7109                for (int j=i+1; j<N; j++) {
7110                    final ResolveInfo rij = results.get(j);
7111                    if (rij.filter != null && rij.filter.hasAction(action)) {
7112                        results.remove(j);
7113                        if (DEBUG_INTENT_MATCHING) Log.v(
7114                            TAG, "Removing duplicate item from " + j
7115                            + " due to action " + action + " at " + i);
7116                        j--;
7117                        N--;
7118                    }
7119                }
7120            }
7121
7122            // If the caller didn't request filter information, drop it now
7123            // so we don't have to marshall/unmarshall it.
7124            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7125                rii.filter = null;
7126            }
7127        }
7128
7129        // Filter out the caller activity if so requested.
7130        if (caller != null) {
7131            N = results.size();
7132            for (int i=0; i<N; i++) {
7133                ActivityInfo ainfo = results.get(i).activityInfo;
7134                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7135                        && caller.getClassName().equals(ainfo.name)) {
7136                    results.remove(i);
7137                    break;
7138                }
7139            }
7140        }
7141
7142        // If the caller didn't request filter information,
7143        // drop them now so we don't have to
7144        // marshall/unmarshall it.
7145        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7146            N = results.size();
7147            for (int i=0; i<N; i++) {
7148                results.get(i).filter = null;
7149            }
7150        }
7151
7152        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7153        return results;
7154    }
7155
7156    @Override
7157    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7158            String resolvedType, int flags, int userId) {
7159        return new ParceledListSlice<>(
7160                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7161                        false /*allowDynamicSplits*/));
7162    }
7163
7164    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7165            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7166        if (!sUserManager.exists(userId)) return Collections.emptyList();
7167        final int callingUid = Binder.getCallingUid();
7168        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7169                false /*requireFullPermission*/, false /*checkShell*/,
7170                "query intent receivers");
7171        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7172        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7173                false /*includeInstantApps*/);
7174        ComponentName comp = intent.getComponent();
7175        if (comp == null) {
7176            if (intent.getSelector() != null) {
7177                intent = intent.getSelector();
7178                comp = intent.getComponent();
7179            }
7180        }
7181        if (comp != null) {
7182            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7183            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7184            if (ai != null) {
7185                // When specifying an explicit component, we prevent the activity from being
7186                // used when either 1) the calling package is normal and the activity is within
7187                // an instant application or 2) the calling package is ephemeral and the
7188                // activity is not visible to instant applications.
7189                final boolean matchInstantApp =
7190                        (flags & PackageManager.MATCH_INSTANT) != 0;
7191                final boolean matchVisibleToInstantAppOnly =
7192                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7193                final boolean matchExplicitlyVisibleOnly =
7194                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7195                final boolean isCallerInstantApp =
7196                        instantAppPkgName != null;
7197                final boolean isTargetSameInstantApp =
7198                        comp.getPackageName().equals(instantAppPkgName);
7199                final boolean isTargetInstantApp =
7200                        (ai.applicationInfo.privateFlags
7201                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7202                final boolean isTargetVisibleToInstantApp =
7203                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7204                final boolean isTargetExplicitlyVisibleToInstantApp =
7205                        isTargetVisibleToInstantApp
7206                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7207                final boolean isTargetHiddenFromInstantApp =
7208                        !isTargetVisibleToInstantApp
7209                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7210                final boolean blockResolution =
7211                        !isTargetSameInstantApp
7212                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7213                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7214                                        && isTargetHiddenFromInstantApp));
7215                if (!blockResolution) {
7216                    ResolveInfo ri = new ResolveInfo();
7217                    ri.activityInfo = ai;
7218                    list.add(ri);
7219                }
7220            }
7221            return applyPostResolutionFilter(
7222                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7223        }
7224
7225        // reader
7226        synchronized (mPackages) {
7227            String pkgName = intent.getPackage();
7228            if (pkgName == null) {
7229                final List<ResolveInfo> result =
7230                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7231                return applyPostResolutionFilter(
7232                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7233            }
7234            final PackageParser.Package pkg = mPackages.get(pkgName);
7235            if (pkg != null) {
7236                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7237                        intent, resolvedType, flags, pkg.receivers, userId);
7238                return applyPostResolutionFilter(
7239                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7240            }
7241            return Collections.emptyList();
7242        }
7243    }
7244
7245    @Override
7246    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7247        final int callingUid = Binder.getCallingUid();
7248        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7249    }
7250
7251    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7252            int userId, int callingUid) {
7253        if (!sUserManager.exists(userId)) return null;
7254        flags = updateFlagsForResolve(
7255                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7256        List<ResolveInfo> query = queryIntentServicesInternal(
7257                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7258        if (query != null) {
7259            if (query.size() >= 1) {
7260                // If there is more than one service with the same priority,
7261                // just arbitrarily pick the first one.
7262                return query.get(0);
7263            }
7264        }
7265        return null;
7266    }
7267
7268    @Override
7269    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7270            String resolvedType, int flags, int userId) {
7271        final int callingUid = Binder.getCallingUid();
7272        return new ParceledListSlice<>(queryIntentServicesInternal(
7273                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7274    }
7275
7276    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7277            String resolvedType, int flags, int userId, int callingUid,
7278            boolean includeInstantApps) {
7279        if (!sUserManager.exists(userId)) return Collections.emptyList();
7280        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7281                false /*requireFullPermission*/, false /*checkShell*/,
7282                "query intent receivers");
7283        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7284        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7285        ComponentName comp = intent.getComponent();
7286        if (comp == null) {
7287            if (intent.getSelector() != null) {
7288                intent = intent.getSelector();
7289                comp = intent.getComponent();
7290            }
7291        }
7292        if (comp != null) {
7293            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7294            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7295            if (si != null) {
7296                // When specifying an explicit component, we prevent the service from being
7297                // used when either 1) the service is in an instant application and the
7298                // caller is not the same instant application or 2) the calling package is
7299                // ephemeral and the activity is not visible to ephemeral applications.
7300                final boolean matchInstantApp =
7301                        (flags & PackageManager.MATCH_INSTANT) != 0;
7302                final boolean matchVisibleToInstantAppOnly =
7303                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7304                final boolean isCallerInstantApp =
7305                        instantAppPkgName != null;
7306                final boolean isTargetSameInstantApp =
7307                        comp.getPackageName().equals(instantAppPkgName);
7308                final boolean isTargetInstantApp =
7309                        (si.applicationInfo.privateFlags
7310                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7311                final boolean isTargetHiddenFromInstantApp =
7312                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7313                final boolean blockResolution =
7314                        !isTargetSameInstantApp
7315                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7316                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7317                                        && isTargetHiddenFromInstantApp));
7318                if (!blockResolution) {
7319                    final ResolveInfo ri = new ResolveInfo();
7320                    ri.serviceInfo = si;
7321                    list.add(ri);
7322                }
7323            }
7324            return list;
7325        }
7326
7327        // reader
7328        synchronized (mPackages) {
7329            String pkgName = intent.getPackage();
7330            if (pkgName == null) {
7331                return applyPostServiceResolutionFilter(
7332                        mServices.queryIntent(intent, resolvedType, flags, userId),
7333                        instantAppPkgName);
7334            }
7335            final PackageParser.Package pkg = mPackages.get(pkgName);
7336            if (pkg != null) {
7337                return applyPostServiceResolutionFilter(
7338                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7339                                userId),
7340                        instantAppPkgName);
7341            }
7342            return Collections.emptyList();
7343        }
7344    }
7345
7346    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7347            String instantAppPkgName) {
7348        if (instantAppPkgName == null) {
7349            return resolveInfos;
7350        }
7351        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7352            final ResolveInfo info = resolveInfos.get(i);
7353            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7354            // allow services that are defined in the provided package
7355            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7356                if (info.serviceInfo.splitName != null
7357                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7358                                info.serviceInfo.splitName)) {
7359                    // requested service is defined in a split that hasn't been installed yet.
7360                    // add the installer to the resolve list
7361                    if (DEBUG_EPHEMERAL) {
7362                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7363                    }
7364                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7365                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7366                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7367                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7368                            null /*failureIntent*/);
7369                    // make sure this resolver is the default
7370                    installerInfo.isDefault = true;
7371                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7372                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7373                    // add a non-generic filter
7374                    installerInfo.filter = new IntentFilter();
7375                    // load resources from the correct package
7376                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7377                    resolveInfos.set(i, installerInfo);
7378                }
7379                continue;
7380            }
7381            // allow services that have been explicitly exposed to ephemeral apps
7382            if (!isEphemeralApp
7383                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7384                continue;
7385            }
7386            resolveInfos.remove(i);
7387        }
7388        return resolveInfos;
7389    }
7390
7391    @Override
7392    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7393            String resolvedType, int flags, int userId) {
7394        return new ParceledListSlice<>(
7395                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7396    }
7397
7398    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7399            Intent intent, String resolvedType, int flags, int userId) {
7400        if (!sUserManager.exists(userId)) return Collections.emptyList();
7401        final int callingUid = Binder.getCallingUid();
7402        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7403        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7404                false /*includeInstantApps*/);
7405        ComponentName comp = intent.getComponent();
7406        if (comp == null) {
7407            if (intent.getSelector() != null) {
7408                intent = intent.getSelector();
7409                comp = intent.getComponent();
7410            }
7411        }
7412        if (comp != null) {
7413            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7414            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7415            if (pi != null) {
7416                // When specifying an explicit component, we prevent the provider from being
7417                // used when either 1) the provider is in an instant application and the
7418                // caller is not the same instant application or 2) the calling package is an
7419                // instant application and the provider is not visible to instant applications.
7420                final boolean matchInstantApp =
7421                        (flags & PackageManager.MATCH_INSTANT) != 0;
7422                final boolean matchVisibleToInstantAppOnly =
7423                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7424                final boolean isCallerInstantApp =
7425                        instantAppPkgName != null;
7426                final boolean isTargetSameInstantApp =
7427                        comp.getPackageName().equals(instantAppPkgName);
7428                final boolean isTargetInstantApp =
7429                        (pi.applicationInfo.privateFlags
7430                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7431                final boolean isTargetHiddenFromInstantApp =
7432                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7433                final boolean blockResolution =
7434                        !isTargetSameInstantApp
7435                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7436                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7437                                        && isTargetHiddenFromInstantApp));
7438                if (!blockResolution) {
7439                    final ResolveInfo ri = new ResolveInfo();
7440                    ri.providerInfo = pi;
7441                    list.add(ri);
7442                }
7443            }
7444            return list;
7445        }
7446
7447        // reader
7448        synchronized (mPackages) {
7449            String pkgName = intent.getPackage();
7450            if (pkgName == null) {
7451                return applyPostContentProviderResolutionFilter(
7452                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7453                        instantAppPkgName);
7454            }
7455            final PackageParser.Package pkg = mPackages.get(pkgName);
7456            if (pkg != null) {
7457                return applyPostContentProviderResolutionFilter(
7458                        mProviders.queryIntentForPackage(
7459                        intent, resolvedType, flags, pkg.providers, userId),
7460                        instantAppPkgName);
7461            }
7462            return Collections.emptyList();
7463        }
7464    }
7465
7466    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7467            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7468        if (instantAppPkgName == null) {
7469            return resolveInfos;
7470        }
7471        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7472            final ResolveInfo info = resolveInfos.get(i);
7473            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7474            // allow providers that are defined in the provided package
7475            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7476                if (info.providerInfo.splitName != null
7477                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7478                                info.providerInfo.splitName)) {
7479                    // requested provider is defined in a split that hasn't been installed yet.
7480                    // add the installer to the resolve list
7481                    if (DEBUG_EPHEMERAL) {
7482                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7483                    }
7484                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7485                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7486                            info.providerInfo.packageName, info.providerInfo.splitName,
7487                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7488                            null /*failureIntent*/);
7489                    // make sure this resolver is the default
7490                    installerInfo.isDefault = true;
7491                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7492                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7493                    // add a non-generic filter
7494                    installerInfo.filter = new IntentFilter();
7495                    // load resources from the correct package
7496                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7497                    resolveInfos.set(i, installerInfo);
7498                }
7499                continue;
7500            }
7501            // allow providers that have been explicitly exposed to instant applications
7502            if (!isEphemeralApp
7503                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7504                continue;
7505            }
7506            resolveInfos.remove(i);
7507        }
7508        return resolveInfos;
7509    }
7510
7511    @Override
7512    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7513        final int callingUid = Binder.getCallingUid();
7514        if (getInstantAppPackageName(callingUid) != null) {
7515            return ParceledListSlice.emptyList();
7516        }
7517        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7518        flags = updateFlagsForPackage(flags, userId, null);
7519        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7520        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7521                true /* requireFullPermission */, false /* checkShell */,
7522                "get installed packages");
7523
7524        // writer
7525        synchronized (mPackages) {
7526            ArrayList<PackageInfo> list;
7527            if (listUninstalled) {
7528                list = new ArrayList<>(mSettings.mPackages.size());
7529                for (PackageSetting ps : mSettings.mPackages.values()) {
7530                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7531                        continue;
7532                    }
7533                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7534                        continue;
7535                    }
7536                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7537                    if (pi != null) {
7538                        list.add(pi);
7539                    }
7540                }
7541            } else {
7542                list = new ArrayList<>(mPackages.size());
7543                for (PackageParser.Package p : mPackages.values()) {
7544                    final PackageSetting ps = (PackageSetting) p.mExtras;
7545                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7546                        continue;
7547                    }
7548                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7549                        continue;
7550                    }
7551                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7552                            p.mExtras, flags, userId);
7553                    if (pi != null) {
7554                        list.add(pi);
7555                    }
7556                }
7557            }
7558
7559            return new ParceledListSlice<>(list);
7560        }
7561    }
7562
7563    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7564            String[] permissions, boolean[] tmp, int flags, int userId) {
7565        int numMatch = 0;
7566        final PermissionsState permissionsState = ps.getPermissionsState();
7567        for (int i=0; i<permissions.length; i++) {
7568            final String permission = permissions[i];
7569            if (permissionsState.hasPermission(permission, userId)) {
7570                tmp[i] = true;
7571                numMatch++;
7572            } else {
7573                tmp[i] = false;
7574            }
7575        }
7576        if (numMatch == 0) {
7577            return;
7578        }
7579        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7580
7581        // The above might return null in cases of uninstalled apps or install-state
7582        // skew across users/profiles.
7583        if (pi != null) {
7584            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7585                if (numMatch == permissions.length) {
7586                    pi.requestedPermissions = permissions;
7587                } else {
7588                    pi.requestedPermissions = new String[numMatch];
7589                    numMatch = 0;
7590                    for (int i=0; i<permissions.length; i++) {
7591                        if (tmp[i]) {
7592                            pi.requestedPermissions[numMatch] = permissions[i];
7593                            numMatch++;
7594                        }
7595                    }
7596                }
7597            }
7598            list.add(pi);
7599        }
7600    }
7601
7602    @Override
7603    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7604            String[] permissions, int flags, int userId) {
7605        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7606        flags = updateFlagsForPackage(flags, userId, permissions);
7607        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7608                true /* requireFullPermission */, false /* checkShell */,
7609                "get packages holding permissions");
7610        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7611
7612        // writer
7613        synchronized (mPackages) {
7614            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7615            boolean[] tmpBools = new boolean[permissions.length];
7616            if (listUninstalled) {
7617                for (PackageSetting ps : mSettings.mPackages.values()) {
7618                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7619                            userId);
7620                }
7621            } else {
7622                for (PackageParser.Package pkg : mPackages.values()) {
7623                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7624                    if (ps != null) {
7625                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7626                                userId);
7627                    }
7628                }
7629            }
7630
7631            return new ParceledListSlice<PackageInfo>(list);
7632        }
7633    }
7634
7635    @Override
7636    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7637        final int callingUid = Binder.getCallingUid();
7638        if (getInstantAppPackageName(callingUid) != null) {
7639            return ParceledListSlice.emptyList();
7640        }
7641        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7642        flags = updateFlagsForApplication(flags, userId, null);
7643        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7644
7645        // writer
7646        synchronized (mPackages) {
7647            ArrayList<ApplicationInfo> list;
7648            if (listUninstalled) {
7649                list = new ArrayList<>(mSettings.mPackages.size());
7650                for (PackageSetting ps : mSettings.mPackages.values()) {
7651                    ApplicationInfo ai;
7652                    int effectiveFlags = flags;
7653                    if (ps.isSystem()) {
7654                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7655                    }
7656                    if (ps.pkg != null) {
7657                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7658                            continue;
7659                        }
7660                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7661                            continue;
7662                        }
7663                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7664                                ps.readUserState(userId), userId);
7665                        if (ai != null) {
7666                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7667                        }
7668                    } else {
7669                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7670                        // and already converts to externally visible package name
7671                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7672                                callingUid, effectiveFlags, userId);
7673                    }
7674                    if (ai != null) {
7675                        list.add(ai);
7676                    }
7677                }
7678            } else {
7679                list = new ArrayList<>(mPackages.size());
7680                for (PackageParser.Package p : mPackages.values()) {
7681                    if (p.mExtras != null) {
7682                        PackageSetting ps = (PackageSetting) p.mExtras;
7683                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7684                            continue;
7685                        }
7686                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7687                            continue;
7688                        }
7689                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7690                                ps.readUserState(userId), userId);
7691                        if (ai != null) {
7692                            ai.packageName = resolveExternalPackageNameLPr(p);
7693                            list.add(ai);
7694                        }
7695                    }
7696                }
7697            }
7698
7699            return new ParceledListSlice<>(list);
7700        }
7701    }
7702
7703    @Override
7704    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7705        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7706            return null;
7707        }
7708        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7709            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7710                    "getEphemeralApplications");
7711        }
7712        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7713                true /* requireFullPermission */, false /* checkShell */,
7714                "getEphemeralApplications");
7715        synchronized (mPackages) {
7716            List<InstantAppInfo> instantApps = mInstantAppRegistry
7717                    .getInstantAppsLPr(userId);
7718            if (instantApps != null) {
7719                return new ParceledListSlice<>(instantApps);
7720            }
7721        }
7722        return null;
7723    }
7724
7725    @Override
7726    public boolean isInstantApp(String packageName, int userId) {
7727        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7728                true /* requireFullPermission */, false /* checkShell */,
7729                "isInstantApp");
7730        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7731            return false;
7732        }
7733
7734        synchronized (mPackages) {
7735            int callingUid = Binder.getCallingUid();
7736            if (Process.isIsolated(callingUid)) {
7737                callingUid = mIsolatedOwners.get(callingUid);
7738            }
7739            final PackageSetting ps = mSettings.mPackages.get(packageName);
7740            PackageParser.Package pkg = mPackages.get(packageName);
7741            final boolean returnAllowed =
7742                    ps != null
7743                    && (isCallerSameApp(packageName, callingUid)
7744                            || canViewInstantApps(callingUid, userId)
7745                            || mInstantAppRegistry.isInstantAccessGranted(
7746                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7747            if (returnAllowed) {
7748                return ps.getInstantApp(userId);
7749            }
7750        }
7751        return false;
7752    }
7753
7754    @Override
7755    public byte[] getInstantAppCookie(String packageName, int userId) {
7756        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7757            return null;
7758        }
7759
7760        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7761                true /* requireFullPermission */, false /* checkShell */,
7762                "getInstantAppCookie");
7763        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7764            return null;
7765        }
7766        synchronized (mPackages) {
7767            return mInstantAppRegistry.getInstantAppCookieLPw(
7768                    packageName, userId);
7769        }
7770    }
7771
7772    @Override
7773    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7774        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7775            return true;
7776        }
7777
7778        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7779                true /* requireFullPermission */, true /* checkShell */,
7780                "setInstantAppCookie");
7781        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7782            return false;
7783        }
7784        synchronized (mPackages) {
7785            return mInstantAppRegistry.setInstantAppCookieLPw(
7786                    packageName, cookie, userId);
7787        }
7788    }
7789
7790    @Override
7791    public Bitmap getInstantAppIcon(String packageName, int userId) {
7792        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7793            return null;
7794        }
7795
7796        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7797            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7798                    "getInstantAppIcon");
7799        }
7800        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7801                true /* requireFullPermission */, false /* checkShell */,
7802                "getInstantAppIcon");
7803
7804        synchronized (mPackages) {
7805            return mInstantAppRegistry.getInstantAppIconLPw(
7806                    packageName, userId);
7807        }
7808    }
7809
7810    private boolean isCallerSameApp(String packageName, int uid) {
7811        PackageParser.Package pkg = mPackages.get(packageName);
7812        return pkg != null
7813                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7814    }
7815
7816    @Override
7817    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7818        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7819            return ParceledListSlice.emptyList();
7820        }
7821        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7822    }
7823
7824    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7825        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7826
7827        // reader
7828        synchronized (mPackages) {
7829            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7830            final int userId = UserHandle.getCallingUserId();
7831            while (i.hasNext()) {
7832                final PackageParser.Package p = i.next();
7833                if (p.applicationInfo == null) continue;
7834
7835                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7836                        && !p.applicationInfo.isDirectBootAware();
7837                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7838                        && p.applicationInfo.isDirectBootAware();
7839
7840                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7841                        && (!mSafeMode || isSystemApp(p))
7842                        && (matchesUnaware || matchesAware)) {
7843                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7844                    if (ps != null) {
7845                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7846                                ps.readUserState(userId), userId);
7847                        if (ai != null) {
7848                            finalList.add(ai);
7849                        }
7850                    }
7851                }
7852            }
7853        }
7854
7855        return finalList;
7856    }
7857
7858    @Override
7859    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7860        return resolveContentProviderInternal(name, flags, userId);
7861    }
7862
7863    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7864        if (!sUserManager.exists(userId)) return null;
7865        flags = updateFlagsForComponent(flags, userId, name);
7866        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7867        // reader
7868        synchronized (mPackages) {
7869            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7870            PackageSetting ps = provider != null
7871                    ? mSettings.mPackages.get(provider.owner.packageName)
7872                    : null;
7873            if (ps != null) {
7874                final boolean isInstantApp = ps.getInstantApp(userId);
7875                // normal application; filter out instant application provider
7876                if (instantAppPkgName == null && isInstantApp) {
7877                    return null;
7878                }
7879                // instant application; filter out other instant applications
7880                if (instantAppPkgName != null
7881                        && isInstantApp
7882                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7883                    return null;
7884                }
7885                // instant application; filter out non-exposed provider
7886                if (instantAppPkgName != null
7887                        && !isInstantApp
7888                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7889                    return null;
7890                }
7891                // provider not enabled
7892                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7893                    return null;
7894                }
7895                return PackageParser.generateProviderInfo(
7896                        provider, flags, ps.readUserState(userId), userId);
7897            }
7898            return null;
7899        }
7900    }
7901
7902    /**
7903     * @deprecated
7904     */
7905    @Deprecated
7906    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7907        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7908            return;
7909        }
7910        // reader
7911        synchronized (mPackages) {
7912            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7913                    .entrySet().iterator();
7914            final int userId = UserHandle.getCallingUserId();
7915            while (i.hasNext()) {
7916                Map.Entry<String, PackageParser.Provider> entry = i.next();
7917                PackageParser.Provider p = entry.getValue();
7918                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7919
7920                if (ps != null && p.syncable
7921                        && (!mSafeMode || (p.info.applicationInfo.flags
7922                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7923                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7924                            ps.readUserState(userId), userId);
7925                    if (info != null) {
7926                        outNames.add(entry.getKey());
7927                        outInfo.add(info);
7928                    }
7929                }
7930            }
7931        }
7932    }
7933
7934    @Override
7935    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7936            int uid, int flags, String metaDataKey) {
7937        final int callingUid = Binder.getCallingUid();
7938        final int userId = processName != null ? UserHandle.getUserId(uid)
7939                : UserHandle.getCallingUserId();
7940        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7941        flags = updateFlagsForComponent(flags, userId, processName);
7942        ArrayList<ProviderInfo> finalList = null;
7943        // reader
7944        synchronized (mPackages) {
7945            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7946            while (i.hasNext()) {
7947                final PackageParser.Provider p = i.next();
7948                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7949                if (ps != null && p.info.authority != null
7950                        && (processName == null
7951                                || (p.info.processName.equals(processName)
7952                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7953                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7954
7955                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7956                    // parameter.
7957                    if (metaDataKey != null
7958                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7959                        continue;
7960                    }
7961                    final ComponentName component =
7962                            new ComponentName(p.info.packageName, p.info.name);
7963                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
7964                        continue;
7965                    }
7966                    if (finalList == null) {
7967                        finalList = new ArrayList<ProviderInfo>(3);
7968                    }
7969                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7970                            ps.readUserState(userId), userId);
7971                    if (info != null) {
7972                        finalList.add(info);
7973                    }
7974                }
7975            }
7976        }
7977
7978        if (finalList != null) {
7979            Collections.sort(finalList, mProviderInitOrderSorter);
7980            return new ParceledListSlice<ProviderInfo>(finalList);
7981        }
7982
7983        return ParceledListSlice.emptyList();
7984    }
7985
7986    @Override
7987    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
7988        // reader
7989        synchronized (mPackages) {
7990            final int callingUid = Binder.getCallingUid();
7991            final int callingUserId = UserHandle.getUserId(callingUid);
7992            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
7993            if (ps == null) return null;
7994            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
7995                return null;
7996            }
7997            final PackageParser.Instrumentation i = mInstrumentation.get(component);
7998            return PackageParser.generateInstrumentationInfo(i, flags);
7999        }
8000    }
8001
8002    @Override
8003    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8004            String targetPackage, int flags) {
8005        final int callingUid = Binder.getCallingUid();
8006        final int callingUserId = UserHandle.getUserId(callingUid);
8007        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8008        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8009            return ParceledListSlice.emptyList();
8010        }
8011        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8012    }
8013
8014    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8015            int flags) {
8016        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8017
8018        // reader
8019        synchronized (mPackages) {
8020            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8021            while (i.hasNext()) {
8022                final PackageParser.Instrumentation p = i.next();
8023                if (targetPackage == null
8024                        || targetPackage.equals(p.info.targetPackage)) {
8025                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8026                            flags);
8027                    if (ii != null) {
8028                        finalList.add(ii);
8029                    }
8030                }
8031            }
8032        }
8033
8034        return finalList;
8035    }
8036
8037    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8038        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8039        try {
8040            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8041        } finally {
8042            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8043        }
8044    }
8045
8046    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8047        final File[] files = scanDir.listFiles();
8048        if (ArrayUtils.isEmpty(files)) {
8049            Log.d(TAG, "No files in app dir " + scanDir);
8050            return;
8051        }
8052
8053        if (DEBUG_PACKAGE_SCANNING) {
8054            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8055                    + " flags=0x" + Integer.toHexString(parseFlags));
8056        }
8057        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8058                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8059                mParallelPackageParserCallback)) {
8060            // Submit files for parsing in parallel
8061            int fileCount = 0;
8062            for (File file : files) {
8063                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8064                        && !PackageInstallerService.isStageName(file.getName());
8065                if (!isPackage) {
8066                    // Ignore entries which are not packages
8067                    continue;
8068                }
8069                parallelPackageParser.submit(file, parseFlags);
8070                fileCount++;
8071            }
8072
8073            // Process results one by one
8074            for (; fileCount > 0; fileCount--) {
8075                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8076                Throwable throwable = parseResult.throwable;
8077                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8078
8079                if (throwable == null) {
8080                    // Static shared libraries have synthetic package names
8081                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8082                        renameStaticSharedLibraryPackage(parseResult.pkg);
8083                    }
8084                    try {
8085                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8086                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8087                                    currentTime, null);
8088                        }
8089                    } catch (PackageManagerException e) {
8090                        errorCode = e.error;
8091                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8092                    }
8093                } else if (throwable instanceof PackageParser.PackageParserException) {
8094                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8095                            throwable;
8096                    errorCode = e.error;
8097                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8098                } else {
8099                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8100                            + parseResult.scanFile, throwable);
8101                }
8102
8103                // Delete invalid userdata apps
8104                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8105                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8106                    logCriticalInfo(Log.WARN,
8107                            "Deleting invalid package at " + parseResult.scanFile);
8108                    removeCodePathLI(parseResult.scanFile);
8109                }
8110            }
8111        }
8112    }
8113
8114    public static void reportSettingsProblem(int priority, String msg) {
8115        logCriticalInfo(priority, msg);
8116    }
8117
8118    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8119            final @ParseFlags int parseFlags) throws PackageManagerException {
8120        // When upgrading from pre-N MR1, verify the package time stamp using the package
8121        // directory and not the APK file.
8122        final long lastModifiedTime = mIsPreNMR1Upgrade
8123                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8124        if (ps != null
8125                && ps.codePathString.equals(pkg.codePath)
8126                && ps.timeStamp == lastModifiedTime
8127                && !isCompatSignatureUpdateNeeded(pkg)
8128                && !isRecoverSignatureUpdateNeeded(pkg)) {
8129            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8130            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
8131            ArraySet<PublicKey> signingKs;
8132            synchronized (mPackages) {
8133                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8134            }
8135            if (ps.signatures.mSignatures != null
8136                    && ps.signatures.mSignatures.length != 0
8137                    && signingKs != null) {
8138                // Optimization: reuse the existing cached certificates
8139                // if the package appears to be unchanged.
8140                pkg.mSignatures = ps.signatures.mSignatures;
8141                pkg.mSigningKeys = signingKs;
8142                return;
8143            }
8144
8145            Slog.w(TAG, "PackageSetting for " + ps.name
8146                    + " is missing signatures.  Collecting certs again to recover them.");
8147        } else {
8148            Slog.i(TAG, toString() + " changed; collecting certs");
8149        }
8150
8151        try {
8152            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8153            PackageParser.collectCertificates(pkg, parseFlags);
8154        } catch (PackageParserException e) {
8155            throw PackageManagerException.from(e);
8156        } finally {
8157            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8158        }
8159    }
8160
8161    /**
8162     *  Traces a package scan.
8163     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8164     */
8165    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8166            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8167        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8168        try {
8169            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8170        } finally {
8171            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8172        }
8173    }
8174
8175    /**
8176     *  Scans a package and returns the newly parsed package.
8177     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8178     */
8179    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8180            long currentTime, UserHandle user) throws PackageManagerException {
8181        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8182        PackageParser pp = new PackageParser();
8183        pp.setSeparateProcesses(mSeparateProcesses);
8184        pp.setOnlyCoreApps(mOnlyCore);
8185        pp.setDisplayMetrics(mMetrics);
8186        pp.setCallback(mPackageParserCallback);
8187
8188        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8189        final PackageParser.Package pkg;
8190        try {
8191            pkg = pp.parsePackage(scanFile, parseFlags);
8192        } catch (PackageParserException e) {
8193            throw PackageManagerException.from(e);
8194        } finally {
8195            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8196        }
8197
8198        // Static shared libraries have synthetic package names
8199        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8200            renameStaticSharedLibraryPackage(pkg);
8201        }
8202
8203        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8204    }
8205
8206    /**
8207     *  Scans a package and returns the newly parsed package.
8208     *  @throws PackageManagerException on a parse error.
8209     */
8210    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8211            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8212            @Nullable UserHandle user)
8213                    throws PackageManagerException {
8214        // If the package has children and this is the first dive in the function
8215        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8216        // packages (parent and children) would be successfully scanned before the
8217        // actual scan since scanning mutates internal state and we want to atomically
8218        // install the package and its children.
8219        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8220            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8221                scanFlags |= SCAN_CHECK_ONLY;
8222            }
8223        } else {
8224            scanFlags &= ~SCAN_CHECK_ONLY;
8225        }
8226
8227        // Scan the parent
8228        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, parseFlags,
8229                scanFlags, currentTime, user);
8230
8231        // Scan the children
8232        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8233        for (int i = 0; i < childCount; i++) {
8234            PackageParser.Package childPackage = pkg.childPackages.get(i);
8235            scanPackageInternalLI(childPackage, parseFlags, scanFlags,
8236                    currentTime, user);
8237        }
8238
8239
8240        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8241            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8242        }
8243
8244        return scannedPkg;
8245    }
8246
8247    /**
8248     *  Scans a package and returns the newly parsed package.
8249     *  @throws PackageManagerException on a parse error.
8250     */
8251    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg,
8252            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8253            @Nullable UserHandle user)
8254                    throws PackageManagerException {
8255        PackageSetting ps = null;
8256        PackageSetting updatedPs;
8257        // reader
8258        synchronized (mPackages) {
8259            // Look to see if we already know about this package.
8260            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8261            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8262                // This package has been renamed to its original name.  Let's
8263                // use that.
8264                ps = mSettings.getPackageLPr(oldName);
8265            }
8266            // If there was no original package, see one for the real package name.
8267            if (ps == null) {
8268                ps = mSettings.getPackageLPr(pkg.packageName);
8269            }
8270            // Check to see if this package could be hiding/updating a system
8271            // package.  Must look for it either under the original or real
8272            // package name depending on our state.
8273            updatedPs = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8274            if (DEBUG_INSTALL && updatedPs != null) Slog.d(TAG, "updatedPkg = " + updatedPs);
8275
8276            // If this is a package we don't know about on the system partition, we
8277            // may need to remove disabled child packages on the system partition
8278            // or may need to not add child packages if the parent apk is updated
8279            // on the data partition and no longer defines this child package.
8280            if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
8281                // If this is a parent package for an updated system app and this system
8282                // app got an OTA update which no longer defines some of the child packages
8283                // we have to prune them from the disabled system packages.
8284                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8285                if (disabledPs != null) {
8286                    final int scannedChildCount = (pkg.childPackages != null)
8287                            ? pkg.childPackages.size() : 0;
8288                    final int disabledChildCount = disabledPs.childPackageNames != null
8289                            ? disabledPs.childPackageNames.size() : 0;
8290                    for (int i = 0; i < disabledChildCount; i++) {
8291                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8292                        boolean disabledPackageAvailable = false;
8293                        for (int j = 0; j < scannedChildCount; j++) {
8294                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8295                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8296                                disabledPackageAvailable = true;
8297                                break;
8298                            }
8299                         }
8300                         if (!disabledPackageAvailable) {
8301                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8302                         }
8303                    }
8304                }
8305            }
8306        }
8307
8308        final boolean isUpdatedPkg = updatedPs != null;
8309        final boolean isUpdatedSystemPkg = isUpdatedPkg && (scanFlags & SCAN_AS_SYSTEM) != 0;
8310        boolean isUpdatedPkgBetter = false;
8311        // First check if this is a system package that may involve an update
8312        if (isUpdatedSystemPkg) {
8313            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8314            // it needs to drop FLAG_PRIVILEGED.
8315            if (locationIsPrivileged(pkg.codePath)) {
8316                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8317            } else {
8318                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8319            }
8320            // If new package is not located in "/oem" (e.g. due to an OTA),
8321            // it needs to drop FLAG_OEM.
8322            if (locationIsOem(pkg.codePath)) {
8323                updatedPs.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8324            } else {
8325                updatedPs.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8326            }
8327
8328            if (ps != null && !ps.codePathString.equals(pkg.codePath)) {
8329                // The path has changed from what was last scanned...  check the
8330                // version of the new path against what we have stored to determine
8331                // what to do.
8332                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8333                if (pkg.getLongVersionCode() <= ps.versionCode) {
8334                    // The system package has been updated and the code path does not match
8335                    // Ignore entry. Skip it.
8336                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + pkg.codePath
8337                            + " ignored: updated version " + ps.versionCode
8338                            + " better than this " + pkg.getLongVersionCode());
8339                    if (!updatedPs.codePathString.equals(pkg.codePath)) {
8340                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8341                                + ps.name + " changing from " + updatedPs.codePathString
8342                                + " to " + pkg.codePath);
8343                        final File codePath = new File(pkg.codePath);
8344                        updatedPs.codePath = codePath;
8345                        updatedPs.codePathString = pkg.codePath;
8346                        updatedPs.resourcePath = codePath;
8347                        updatedPs.resourcePathString = pkg.codePath;
8348                    }
8349                    updatedPs.pkg = pkg;
8350                    updatedPs.versionCode = pkg.getLongVersionCode();
8351
8352                    // Update the disabled system child packages to point to the package too.
8353                    final int childCount = updatedPs.childPackageNames != null
8354                            ? updatedPs.childPackageNames.size() : 0;
8355                    for (int i = 0; i < childCount; i++) {
8356                        String childPackageName = updatedPs.childPackageNames.get(i);
8357                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8358                                childPackageName);
8359                        if (updatedChildPkg != null) {
8360                            updatedChildPkg.pkg = pkg;
8361                            updatedChildPkg.versionCode = pkg.getLongVersionCode();
8362                        }
8363                    }
8364                } else {
8365                    // The current app on the system partition is better than
8366                    // what we have updated to on the data partition; switch
8367                    // back to the system partition version.
8368                    // At this point, its safely assumed that package installation for
8369                    // apps in system partition will go through. If not there won't be a working
8370                    // version of the app
8371                    // writer
8372                    synchronized (mPackages) {
8373                        // Just remove the loaded entries from package lists.
8374                        mPackages.remove(ps.name);
8375                    }
8376
8377                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath
8378                            + " reverting from " + ps.codePathString
8379                            + ": new version " + pkg.getLongVersionCode()
8380                            + " better than installed " + ps.versionCode);
8381
8382                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8383                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8384                    synchronized (mInstallLock) {
8385                        args.cleanUpResourcesLI();
8386                    }
8387                    synchronized (mPackages) {
8388                        mSettings.enableSystemPackageLPw(ps.name);
8389                    }
8390                    isUpdatedPkgBetter = true;
8391                }
8392            }
8393        }
8394
8395        String resourcePath = null;
8396        String baseResourcePath = null;
8397        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8398            if (ps != null && ps.resourcePathString != null) {
8399                resourcePath = ps.resourcePathString;
8400                baseResourcePath = ps.resourcePathString;
8401            } else {
8402                // Should not happen at all. Just log an error.
8403                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8404            }
8405        } else {
8406            resourcePath = pkg.codePath;
8407            baseResourcePath = pkg.baseCodePath;
8408        }
8409
8410        // Set application objects path explicitly.
8411        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8412        pkg.setApplicationInfoCodePath(pkg.codePath);
8413        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8414        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8415        pkg.setApplicationInfoResourcePath(resourcePath);
8416        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8417        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8418
8419        // throw an exception if we have an update to a system application, but, it's not more
8420        // recent than the package we've already scanned
8421        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8422            // Set CPU Abis to application info.
8423            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8424                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPs);
8425                derivePackageAbi(pkg, cpuAbiOverride, false, mAppLib32InstallDir);
8426            } else {
8427                pkg.applicationInfo.primaryCpuAbi = updatedPs.primaryCpuAbiString;
8428                pkg.applicationInfo.secondaryCpuAbi = updatedPs.secondaryCpuAbiString;
8429            }
8430            pkg.mExtras = updatedPs;
8431
8432            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8433                    + pkg.codePath + " ignored: updated version " + updatedPs.versionCode
8434                    + " better than this " + pkg.getLongVersionCode());
8435        }
8436
8437        if (isUpdatedPkg) {
8438            // updated system applications don't initially have the SCAN_AS_SYSTEM flag set
8439            scanFlags |= SCAN_AS_SYSTEM;
8440
8441            // An updated privileged application will not have the PARSE_IS_PRIVILEGED
8442            // flag set initially
8443            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8444                scanFlags |= SCAN_AS_PRIVILEGED;
8445            }
8446
8447            // An updated OEM app will not have the PARSE_IS_OEM
8448            // flag set initially
8449            if ((updatedPs.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8450                scanFlags |= SCAN_AS_OEM;
8451            }
8452        }
8453
8454        // Verify certificates against what was last scanned
8455        collectCertificatesLI(ps, pkg, parseFlags);
8456
8457        /*
8458         * A new system app appeared, but we already had a non-system one of the
8459         * same name installed earlier.
8460         */
8461        boolean shouldHideSystemApp = false;
8462        if (!isUpdatedPkg && ps != null
8463                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8464            /*
8465             * Check to make sure the signatures match first. If they don't,
8466             * wipe the installed application and its data.
8467             */
8468            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8469                    != PackageManager.SIGNATURE_MATCH) {
8470                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8471                        + " signatures don't match existing userdata copy; removing");
8472                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8473                        "scanPackageInternalLI")) {
8474                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8475                }
8476                ps = null;
8477            } else {
8478                /*
8479                 * If the newly-added system app is an older version than the
8480                 * already installed version, hide it. It will be scanned later
8481                 * and re-added like an update.
8482                 */
8483                if (pkg.getLongVersionCode() <= ps.versionCode) {
8484                    shouldHideSystemApp = true;
8485                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + pkg.codePath
8486                            + " but new version " + pkg.getLongVersionCode()
8487                            + " better than installed " + ps.versionCode + "; hiding system");
8488                } else {
8489                    /*
8490                     * The newly found system app is a newer version that the
8491                     * one previously installed. Simply remove the
8492                     * already-installed application and replace it with our own
8493                     * while keeping the application data.
8494                     */
8495                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + pkg.codePath
8496                            + " reverting from " + ps.codePathString + ": new version "
8497                            + pkg.getLongVersionCode() + " better than installed "
8498                            + ps.versionCode);
8499                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8500                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8501                    synchronized (mInstallLock) {
8502                        args.cleanUpResourcesLI();
8503                    }
8504                }
8505            }
8506        }
8507
8508        // The apk is forward locked (not public) if its code and resources
8509        // are kept in different files. (except for app in either system or
8510        // vendor path).
8511        // TODO grab this value from PackageSettings
8512        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8513            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8514                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
8515            }
8516        }
8517
8518        final int userId = ((user == null) ? 0 : user.getIdentifier());
8519        if (ps != null && ps.getInstantApp(userId)) {
8520            scanFlags |= SCAN_AS_INSTANT_APP;
8521        }
8522        if (ps != null && ps.getVirtulalPreload(userId)) {
8523            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8524        }
8525
8526        // Note that we invoke the following method only if we are about to unpack an application
8527        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
8528                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8529
8530        /*
8531         * If the system app should be overridden by a previously installed
8532         * data, hide the system app now and let the /data/app scan pick it up
8533         * again.
8534         */
8535        if (shouldHideSystemApp) {
8536            synchronized (mPackages) {
8537                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8538            }
8539        }
8540
8541        return scannedPkg;
8542    }
8543
8544    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8545        // Derive the new package synthetic package name
8546        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8547                + pkg.staticSharedLibVersion);
8548    }
8549
8550    private static String fixProcessName(String defProcessName,
8551            String processName) {
8552        if (processName == null) {
8553            return defProcessName;
8554        }
8555        return processName;
8556    }
8557
8558    /**
8559     * Enforces that only the system UID or root's UID can call a method exposed
8560     * via Binder.
8561     *
8562     * @param message used as message if SecurityException is thrown
8563     * @throws SecurityException if the caller is not system or root
8564     */
8565    private static final void enforceSystemOrRoot(String message) {
8566        final int uid = Binder.getCallingUid();
8567        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8568            throw new SecurityException(message);
8569        }
8570    }
8571
8572    @Override
8573    public void performFstrimIfNeeded() {
8574        enforceSystemOrRoot("Only the system can request fstrim");
8575
8576        // Before everything else, see whether we need to fstrim.
8577        try {
8578            IStorageManager sm = PackageHelper.getStorageManager();
8579            if (sm != null) {
8580                boolean doTrim = false;
8581                final long interval = android.provider.Settings.Global.getLong(
8582                        mContext.getContentResolver(),
8583                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8584                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8585                if (interval > 0) {
8586                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8587                    if (timeSinceLast > interval) {
8588                        doTrim = true;
8589                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8590                                + "; running immediately");
8591                    }
8592                }
8593                if (doTrim) {
8594                    final boolean dexOptDialogShown;
8595                    synchronized (mPackages) {
8596                        dexOptDialogShown = mDexOptDialogShown;
8597                    }
8598                    if (!isFirstBoot() && dexOptDialogShown) {
8599                        try {
8600                            ActivityManager.getService().showBootMessage(
8601                                    mContext.getResources().getString(
8602                                            R.string.android_upgrading_fstrim), true);
8603                        } catch (RemoteException e) {
8604                        }
8605                    }
8606                    sm.runMaintenance();
8607                }
8608            } else {
8609                Slog.e(TAG, "storageManager service unavailable!");
8610            }
8611        } catch (RemoteException e) {
8612            // Can't happen; StorageManagerService is local
8613        }
8614    }
8615
8616    @Override
8617    public void updatePackagesIfNeeded() {
8618        enforceSystemOrRoot("Only the system can request package update");
8619
8620        // We need to re-extract after an OTA.
8621        boolean causeUpgrade = isUpgrade();
8622
8623        // First boot or factory reset.
8624        // Note: we also handle devices that are upgrading to N right now as if it is their
8625        //       first boot, as they do not have profile data.
8626        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8627
8628        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8629        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8630
8631        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8632            return;
8633        }
8634
8635        List<PackageParser.Package> pkgs;
8636        synchronized (mPackages) {
8637            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8638        }
8639
8640        final long startTime = System.nanoTime();
8641        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8642                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8643                    false /* bootComplete */);
8644
8645        final int elapsedTimeSeconds =
8646                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8647
8648        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8649        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8650        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8651        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8652        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8653    }
8654
8655    /*
8656     * Return the prebuilt profile path given a package base code path.
8657     */
8658    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8659        return pkg.baseCodePath + ".prof";
8660    }
8661
8662    /**
8663     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8664     * containing statistics about the invocation. The array consists of three elements,
8665     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8666     * and {@code numberOfPackagesFailed}.
8667     */
8668    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8669            final String compilerFilter, boolean bootComplete) {
8670
8671        int numberOfPackagesVisited = 0;
8672        int numberOfPackagesOptimized = 0;
8673        int numberOfPackagesSkipped = 0;
8674        int numberOfPackagesFailed = 0;
8675        final int numberOfPackagesToDexopt = pkgs.size();
8676
8677        for (PackageParser.Package pkg : pkgs) {
8678            numberOfPackagesVisited++;
8679
8680            boolean useProfileForDexopt = false;
8681
8682            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8683                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8684                // that are already compiled.
8685                File profileFile = new File(getPrebuildProfilePath(pkg));
8686                // Copy profile if it exists.
8687                if (profileFile.exists()) {
8688                    try {
8689                        // We could also do this lazily before calling dexopt in
8690                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8691                        // is that we don't have a good way to say "do this only once".
8692                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8693                                pkg.applicationInfo.uid, pkg.packageName)) {
8694                            Log.e(TAG, "Installer failed to copy system profile!");
8695                        } else {
8696                            // Disabled as this causes speed-profile compilation during first boot
8697                            // even if things are already compiled.
8698                            // useProfileForDexopt = true;
8699                        }
8700                    } catch (Exception e) {
8701                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8702                                e);
8703                    }
8704                } else {
8705                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8706                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8707                    // minimize the number off apps being speed-profile compiled during first boot.
8708                    // The other paths will not change the filter.
8709                    if (disabledPs != null && disabledPs.pkg.isStub) {
8710                        // The package is the stub one, remove the stub suffix to get the normal
8711                        // package and APK names.
8712                        String systemProfilePath =
8713                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8714                        profileFile = new File(systemProfilePath);
8715                        // If we have a profile for a compressed APK, copy it to the reference
8716                        // location.
8717                        // Note that copying the profile here will cause it to override the
8718                        // reference profile every OTA even though the existing reference profile
8719                        // may have more data. We can't copy during decompression since the
8720                        // directories are not set up at that point.
8721                        if (profileFile.exists()) {
8722                            try {
8723                                // We could also do this lazily before calling dexopt in
8724                                // PackageDexOptimizer to prevent this happening on first boot. The
8725                                // issue is that we don't have a good way to say "do this only
8726                                // once".
8727                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8728                                        pkg.applicationInfo.uid, pkg.packageName)) {
8729                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8730                                } else {
8731                                    useProfileForDexopt = true;
8732                                }
8733                            } catch (Exception e) {
8734                                Log.e(TAG, "Failed to copy profile " +
8735                                        profileFile.getAbsolutePath() + " ", e);
8736                            }
8737                        }
8738                    }
8739                }
8740            }
8741
8742            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8743                if (DEBUG_DEXOPT) {
8744                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8745                }
8746                numberOfPackagesSkipped++;
8747                continue;
8748            }
8749
8750            if (DEBUG_DEXOPT) {
8751                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8752                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8753            }
8754
8755            if (showDialog) {
8756                try {
8757                    ActivityManager.getService().showBootMessage(
8758                            mContext.getResources().getString(R.string.android_upgrading_apk,
8759                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8760                } catch (RemoteException e) {
8761                }
8762                synchronized (mPackages) {
8763                    mDexOptDialogShown = true;
8764                }
8765            }
8766
8767            String pkgCompilerFilter = compilerFilter;
8768            if (useProfileForDexopt) {
8769                // Use background dexopt mode to try and use the profile. Note that this does not
8770                // guarantee usage of the profile.
8771                pkgCompilerFilter =
8772                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8773                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8774            }
8775
8776            // checkProfiles is false to avoid merging profiles during boot which
8777            // might interfere with background compilation (b/28612421).
8778            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8779            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8780            // trade-off worth doing to save boot time work.
8781            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8782            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8783                    pkg.packageName,
8784                    pkgCompilerFilter,
8785                    dexoptFlags));
8786
8787            switch (primaryDexOptStaus) {
8788                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8789                    numberOfPackagesOptimized++;
8790                    break;
8791                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8792                    numberOfPackagesSkipped++;
8793                    break;
8794                case PackageDexOptimizer.DEX_OPT_FAILED:
8795                    numberOfPackagesFailed++;
8796                    break;
8797                default:
8798                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8799                    break;
8800            }
8801        }
8802
8803        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8804                numberOfPackagesFailed };
8805    }
8806
8807    @Override
8808    public void notifyPackageUse(String packageName, int reason) {
8809        synchronized (mPackages) {
8810            final int callingUid = Binder.getCallingUid();
8811            final int callingUserId = UserHandle.getUserId(callingUid);
8812            if (getInstantAppPackageName(callingUid) != null) {
8813                if (!isCallerSameApp(packageName, callingUid)) {
8814                    return;
8815                }
8816            } else {
8817                if (isInstantApp(packageName, callingUserId)) {
8818                    return;
8819                }
8820            }
8821            notifyPackageUseLocked(packageName, reason);
8822        }
8823    }
8824
8825    private void notifyPackageUseLocked(String packageName, int reason) {
8826        final PackageParser.Package p = mPackages.get(packageName);
8827        if (p == null) {
8828            return;
8829        }
8830        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8831    }
8832
8833    @Override
8834    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
8835            List<String> classPaths, String loaderIsa) {
8836        int userId = UserHandle.getCallingUserId();
8837        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8838        if (ai == null) {
8839            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8840                + loadingPackageName + ", user=" + userId);
8841            return;
8842        }
8843        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
8844    }
8845
8846    @Override
8847    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
8848            IDexModuleRegisterCallback callback) {
8849        int userId = UserHandle.getCallingUserId();
8850        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
8851        DexManager.RegisterDexModuleResult result;
8852        if (ai == null) {
8853            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
8854                     " calling user. package=" + packageName + ", user=" + userId);
8855            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
8856        } else {
8857            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
8858        }
8859
8860        if (callback != null) {
8861            mHandler.post(() -> {
8862                try {
8863                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
8864                } catch (RemoteException e) {
8865                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
8866                }
8867            });
8868        }
8869    }
8870
8871    /**
8872     * Ask the package manager to perform a dex-opt with the given compiler filter.
8873     *
8874     * Note: exposed only for the shell command to allow moving packages explicitly to a
8875     *       definite state.
8876     */
8877    @Override
8878    public boolean performDexOptMode(String packageName,
8879            boolean checkProfiles, String targetCompilerFilter, boolean force,
8880            boolean bootComplete, String splitName) {
8881        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
8882                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
8883                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
8884        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
8885                splitName, flags));
8886    }
8887
8888    /**
8889     * Ask the package manager to perform a dex-opt with the given compiler filter on the
8890     * secondary dex files belonging to the given package.
8891     *
8892     * Note: exposed only for the shell command to allow moving packages explicitly to a
8893     *       definite state.
8894     */
8895    @Override
8896    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8897            boolean force) {
8898        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
8899                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
8900                DexoptOptions.DEXOPT_BOOT_COMPLETE |
8901                (force ? DexoptOptions.DEXOPT_FORCE : 0);
8902        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
8903    }
8904
8905    /*package*/ boolean performDexOpt(DexoptOptions options) {
8906        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8907            return false;
8908        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
8909            return false;
8910        }
8911
8912        if (options.isDexoptOnlySecondaryDex()) {
8913            return mDexManager.dexoptSecondaryDex(options);
8914        } else {
8915            int dexoptStatus = performDexOptWithStatus(options);
8916            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8917        }
8918    }
8919
8920    /**
8921     * Perform dexopt on the given package and return one of following result:
8922     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
8923     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
8924     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
8925     */
8926    /* package */ int performDexOptWithStatus(DexoptOptions options) {
8927        return performDexOptTraced(options);
8928    }
8929
8930    private int performDexOptTraced(DexoptOptions options) {
8931        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8932        try {
8933            return performDexOptInternal(options);
8934        } finally {
8935            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8936        }
8937    }
8938
8939    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8940    // if the package can now be considered up to date for the given filter.
8941    private int performDexOptInternal(DexoptOptions options) {
8942        PackageParser.Package p;
8943        synchronized (mPackages) {
8944            p = mPackages.get(options.getPackageName());
8945            if (p == null) {
8946                // Package could not be found. Report failure.
8947                return PackageDexOptimizer.DEX_OPT_FAILED;
8948            }
8949            mPackageUsage.maybeWriteAsync(mPackages);
8950            mCompilerStats.maybeWriteAsync();
8951        }
8952        long callingId = Binder.clearCallingIdentity();
8953        try {
8954            synchronized (mInstallLock) {
8955                return performDexOptInternalWithDependenciesLI(p, options);
8956            }
8957        } finally {
8958            Binder.restoreCallingIdentity(callingId);
8959        }
8960    }
8961
8962    public ArraySet<String> getOptimizablePackages() {
8963        ArraySet<String> pkgs = new ArraySet<String>();
8964        synchronized (mPackages) {
8965            for (PackageParser.Package p : mPackages.values()) {
8966                if (PackageDexOptimizer.canOptimizePackage(p)) {
8967                    pkgs.add(p.packageName);
8968                }
8969            }
8970        }
8971        return pkgs;
8972    }
8973
8974    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8975            DexoptOptions options) {
8976        // Select the dex optimizer based on the force parameter.
8977        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8978        //       allocate an object here.
8979        PackageDexOptimizer pdo = options.isForce()
8980                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8981                : mPackageDexOptimizer;
8982
8983        // Dexopt all dependencies first. Note: we ignore the return value and march on
8984        // on errors.
8985        // Note that we are going to call performDexOpt on those libraries as many times as
8986        // they are referenced in packages. When we do a batch of performDexOpt (for example
8987        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8988        // and the first package that uses the library will dexopt it. The
8989        // others will see that the compiled code for the library is up to date.
8990        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8991        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8992        if (!deps.isEmpty()) {
8993            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
8994                    options.getCompilerFilter(), options.getSplitName(),
8995                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
8996            for (PackageParser.Package depPackage : deps) {
8997                // TODO: Analyze and investigate if we (should) profile libraries.
8998                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8999                        getOrCreateCompilerPackageStats(depPackage),
9000                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9001            }
9002        }
9003        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9004                getOrCreateCompilerPackageStats(p),
9005                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9006    }
9007
9008    /**
9009     * Reconcile the information we have about the secondary dex files belonging to
9010     * {@code packagName} and the actual dex files. For all dex files that were
9011     * deleted, update the internal records and delete the generated oat files.
9012     */
9013    @Override
9014    public void reconcileSecondaryDexFiles(String packageName) {
9015        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9016            return;
9017        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9018            return;
9019        }
9020        mDexManager.reconcileSecondaryDexFiles(packageName);
9021    }
9022
9023    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9024    // a reference there.
9025    /*package*/ DexManager getDexManager() {
9026        return mDexManager;
9027    }
9028
9029    /**
9030     * Execute the background dexopt job immediately.
9031     */
9032    @Override
9033    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9034        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9035            return false;
9036        }
9037        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9038    }
9039
9040    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9041        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9042                || p.usesStaticLibraries != null) {
9043            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9044            Set<String> collectedNames = new HashSet<>();
9045            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9046
9047            retValue.remove(p);
9048
9049            return retValue;
9050        } else {
9051            return Collections.emptyList();
9052        }
9053    }
9054
9055    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9056            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9057        if (!collectedNames.contains(p.packageName)) {
9058            collectedNames.add(p.packageName);
9059            collected.add(p);
9060
9061            if (p.usesLibraries != null) {
9062                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9063                        null, collected, collectedNames);
9064            }
9065            if (p.usesOptionalLibraries != null) {
9066                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9067                        null, collected, collectedNames);
9068            }
9069            if (p.usesStaticLibraries != null) {
9070                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9071                        p.usesStaticLibrariesVersions, collected, collectedNames);
9072            }
9073        }
9074    }
9075
9076    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9077            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9078        final int libNameCount = libs.size();
9079        for (int i = 0; i < libNameCount; i++) {
9080            String libName = libs.get(i);
9081            long version = (versions != null && versions.length == libNameCount)
9082                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9083            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9084            if (libPkg != null) {
9085                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9086            }
9087        }
9088    }
9089
9090    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9091        synchronized (mPackages) {
9092            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9093            if (libEntry != null) {
9094                return mPackages.get(libEntry.apk);
9095            }
9096            return null;
9097        }
9098    }
9099
9100    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9101        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9102        if (versionedLib == null) {
9103            return null;
9104        }
9105        return versionedLib.get(version);
9106    }
9107
9108    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9109        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9110                pkg.staticSharedLibName);
9111        if (versionedLib == null) {
9112            return null;
9113        }
9114        long previousLibVersion = -1;
9115        final int versionCount = versionedLib.size();
9116        for (int i = 0; i < versionCount; i++) {
9117            final long libVersion = versionedLib.keyAt(i);
9118            if (libVersion < pkg.staticSharedLibVersion) {
9119                previousLibVersion = Math.max(previousLibVersion, libVersion);
9120            }
9121        }
9122        if (previousLibVersion >= 0) {
9123            return versionedLib.get(previousLibVersion);
9124        }
9125        return null;
9126    }
9127
9128    public void shutdown() {
9129        mPackageUsage.writeNow(mPackages);
9130        mCompilerStats.writeNow();
9131        mDexManager.writePackageDexUsageNow();
9132    }
9133
9134    @Override
9135    public void dumpProfiles(String packageName) {
9136        PackageParser.Package pkg;
9137        synchronized (mPackages) {
9138            pkg = mPackages.get(packageName);
9139            if (pkg == null) {
9140                throw new IllegalArgumentException("Unknown package: " + packageName);
9141            }
9142        }
9143        /* Only the shell, root, or the app user should be able to dump profiles. */
9144        int callingUid = Binder.getCallingUid();
9145        if (callingUid != Process.SHELL_UID &&
9146            callingUid != Process.ROOT_UID &&
9147            callingUid != pkg.applicationInfo.uid) {
9148            throw new SecurityException("dumpProfiles");
9149        }
9150
9151        synchronized (mInstallLock) {
9152            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9153            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9154            try {
9155                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9156                String codePaths = TextUtils.join(";", allCodePaths);
9157                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9158            } catch (InstallerException e) {
9159                Slog.w(TAG, "Failed to dump profiles", e);
9160            }
9161            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9162        }
9163    }
9164
9165    @Override
9166    public void forceDexOpt(String packageName) {
9167        enforceSystemOrRoot("forceDexOpt");
9168
9169        PackageParser.Package pkg;
9170        synchronized (mPackages) {
9171            pkg = mPackages.get(packageName);
9172            if (pkg == null) {
9173                throw new IllegalArgumentException("Unknown package: " + packageName);
9174            }
9175        }
9176
9177        synchronized (mInstallLock) {
9178            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9179
9180            // Whoever is calling forceDexOpt wants a compiled package.
9181            // Don't use profiles since that may cause compilation to be skipped.
9182            final int res = performDexOptInternalWithDependenciesLI(
9183                    pkg,
9184                    new DexoptOptions(packageName,
9185                            getDefaultCompilerFilter(),
9186                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9187
9188            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9189            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9190                throw new IllegalStateException("Failed to dexopt: " + res);
9191            }
9192        }
9193    }
9194
9195    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9196        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9197            Slog.w(TAG, "Unable to update from " + oldPkg.name
9198                    + " to " + newPkg.packageName
9199                    + ": old package not in system partition");
9200            return false;
9201        } else if (mPackages.get(oldPkg.name) != null) {
9202            Slog.w(TAG, "Unable to update from " + oldPkg.name
9203                    + " to " + newPkg.packageName
9204                    + ": old package still exists");
9205            return false;
9206        }
9207        return true;
9208    }
9209
9210    void removeCodePathLI(File codePath) {
9211        if (codePath.isDirectory()) {
9212            try {
9213                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9214            } catch (InstallerException e) {
9215                Slog.w(TAG, "Failed to remove code path", e);
9216            }
9217        } else {
9218            codePath.delete();
9219        }
9220    }
9221
9222    private int[] resolveUserIds(int userId) {
9223        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9224    }
9225
9226    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9227        if (pkg == null) {
9228            Slog.wtf(TAG, "Package was null!", new Throwable());
9229            return;
9230        }
9231        clearAppDataLeafLIF(pkg, userId, flags);
9232        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9233        for (int i = 0; i < childCount; i++) {
9234            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9235        }
9236    }
9237
9238    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9239        final PackageSetting ps;
9240        synchronized (mPackages) {
9241            ps = mSettings.mPackages.get(pkg.packageName);
9242        }
9243        for (int realUserId : resolveUserIds(userId)) {
9244            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9245            try {
9246                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9247                        ceDataInode);
9248            } catch (InstallerException e) {
9249                Slog.w(TAG, String.valueOf(e));
9250            }
9251        }
9252    }
9253
9254    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9255        if (pkg == null) {
9256            Slog.wtf(TAG, "Package was null!", new Throwable());
9257            return;
9258        }
9259        destroyAppDataLeafLIF(pkg, userId, flags);
9260        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9261        for (int i = 0; i < childCount; i++) {
9262            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9263        }
9264    }
9265
9266    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9267        final PackageSetting ps;
9268        synchronized (mPackages) {
9269            ps = mSettings.mPackages.get(pkg.packageName);
9270        }
9271        for (int realUserId : resolveUserIds(userId)) {
9272            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9273            try {
9274                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9275                        ceDataInode);
9276            } catch (InstallerException e) {
9277                Slog.w(TAG, String.valueOf(e));
9278            }
9279            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9280        }
9281    }
9282
9283    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9284        if (pkg == null) {
9285            Slog.wtf(TAG, "Package was null!", new Throwable());
9286            return;
9287        }
9288        destroyAppProfilesLeafLIF(pkg);
9289        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9290        for (int i = 0; i < childCount; i++) {
9291            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9292        }
9293    }
9294
9295    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9296        try {
9297            mInstaller.destroyAppProfiles(pkg.packageName);
9298        } catch (InstallerException e) {
9299            Slog.w(TAG, String.valueOf(e));
9300        }
9301    }
9302
9303    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9304        if (pkg == null) {
9305            Slog.wtf(TAG, "Package was null!", new Throwable());
9306            return;
9307        }
9308        clearAppProfilesLeafLIF(pkg);
9309        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9310        for (int i = 0; i < childCount; i++) {
9311            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9312        }
9313    }
9314
9315    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9316        try {
9317            mInstaller.clearAppProfiles(pkg.packageName);
9318        } catch (InstallerException e) {
9319            Slog.w(TAG, String.valueOf(e));
9320        }
9321    }
9322
9323    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9324            long lastUpdateTime) {
9325        // Set parent install/update time
9326        PackageSetting ps = (PackageSetting) pkg.mExtras;
9327        if (ps != null) {
9328            ps.firstInstallTime = firstInstallTime;
9329            ps.lastUpdateTime = lastUpdateTime;
9330        }
9331        // Set children install/update time
9332        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9333        for (int i = 0; i < childCount; i++) {
9334            PackageParser.Package childPkg = pkg.childPackages.get(i);
9335            ps = (PackageSetting) childPkg.mExtras;
9336            if (ps != null) {
9337                ps.firstInstallTime = firstInstallTime;
9338                ps.lastUpdateTime = lastUpdateTime;
9339            }
9340        }
9341    }
9342
9343    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9344            SharedLibraryEntry file,
9345            PackageParser.Package changingLib) {
9346        if (file.path != null) {
9347            usesLibraryFiles.add(file.path);
9348            return;
9349        }
9350        PackageParser.Package p = mPackages.get(file.apk);
9351        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9352            // If we are doing this while in the middle of updating a library apk,
9353            // then we need to make sure to use that new apk for determining the
9354            // dependencies here.  (We haven't yet finished committing the new apk
9355            // to the package manager state.)
9356            if (p == null || p.packageName.equals(changingLib.packageName)) {
9357                p = changingLib;
9358            }
9359        }
9360        if (p != null) {
9361            usesLibraryFiles.addAll(p.getAllCodePaths());
9362            if (p.usesLibraryFiles != null) {
9363                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9364            }
9365        }
9366    }
9367
9368    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9369            PackageParser.Package changingLib) throws PackageManagerException {
9370        if (pkg == null) {
9371            return;
9372        }
9373        // The collection used here must maintain the order of addition (so
9374        // that libraries are searched in the correct order) and must have no
9375        // duplicates.
9376        Set<String> usesLibraryFiles = null;
9377        if (pkg.usesLibraries != null) {
9378            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9379                    null, null, pkg.packageName, changingLib, true,
9380                    pkg.applicationInfo.targetSdkVersion, null);
9381        }
9382        if (pkg.usesStaticLibraries != null) {
9383            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9384                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9385                    pkg.packageName, changingLib, true,
9386                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9387        }
9388        if (pkg.usesOptionalLibraries != null) {
9389            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9390                    null, null, pkg.packageName, changingLib, false,
9391                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9392        }
9393        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9394            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9395        } else {
9396            pkg.usesLibraryFiles = null;
9397        }
9398    }
9399
9400    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9401            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9402            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9403            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9404            throws PackageManagerException {
9405        final int libCount = requestedLibraries.size();
9406        for (int i = 0; i < libCount; i++) {
9407            final String libName = requestedLibraries.get(i);
9408            final long libVersion = requiredVersions != null ? requiredVersions[i]
9409                    : SharedLibraryInfo.VERSION_UNDEFINED;
9410            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9411            if (libEntry == null) {
9412                if (required) {
9413                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9414                            "Package " + packageName + " requires unavailable shared library "
9415                                    + libName + "; failing!");
9416                } else if (DEBUG_SHARED_LIBRARIES) {
9417                    Slog.i(TAG, "Package " + packageName
9418                            + " desires unavailable shared library "
9419                            + libName + "; ignoring!");
9420                }
9421            } else {
9422                if (requiredVersions != null && requiredCertDigests != null) {
9423                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9424                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9425                            "Package " + packageName + " requires unavailable static shared"
9426                                    + " library " + libName + " version "
9427                                    + libEntry.info.getLongVersion() + "; failing!");
9428                    }
9429
9430                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9431                    if (libPkg == null) {
9432                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9433                                "Package " + packageName + " requires unavailable static shared"
9434                                        + " library; failing!");
9435                    }
9436
9437                    final String[] expectedCertDigests = requiredCertDigests[i];
9438                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9439                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9440                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9441                            : PackageUtils.computeSignaturesSha256Digests(
9442                                    new Signature[]{libPkg.mSignatures[0]});
9443
9444                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9445                    // target O we don't parse the "additional-certificate" tags similarly
9446                    // how we only consider all certs only for apps targeting O (see above).
9447                    // Therefore, the size check is safe to make.
9448                    if (expectedCertDigests.length != libCertDigests.length) {
9449                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9450                                "Package " + packageName + " requires differently signed" +
9451                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9452                    }
9453
9454                    // Use a predictable order as signature order may vary
9455                    Arrays.sort(libCertDigests);
9456                    Arrays.sort(expectedCertDigests);
9457
9458                    final int certCount = libCertDigests.length;
9459                    for (int j = 0; j < certCount; j++) {
9460                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9461                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9462                                    "Package " + packageName + " requires differently signed" +
9463                                            " static shared library; failing!");
9464                        }
9465                    }
9466                }
9467
9468                if (outUsedLibraries == null) {
9469                    // Use LinkedHashSet to preserve the order of files added to
9470                    // usesLibraryFiles while eliminating duplicates.
9471                    outUsedLibraries = new LinkedHashSet<>();
9472                }
9473                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9474            }
9475        }
9476        return outUsedLibraries;
9477    }
9478
9479    private static boolean hasString(List<String> list, List<String> which) {
9480        if (list == null) {
9481            return false;
9482        }
9483        for (int i=list.size()-1; i>=0; i--) {
9484            for (int j=which.size()-1; j>=0; j--) {
9485                if (which.get(j).equals(list.get(i))) {
9486                    return true;
9487                }
9488            }
9489        }
9490        return false;
9491    }
9492
9493    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9494            PackageParser.Package changingPkg) {
9495        ArrayList<PackageParser.Package> res = null;
9496        for (PackageParser.Package pkg : mPackages.values()) {
9497            if (changingPkg != null
9498                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9499                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9500                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9501                            changingPkg.staticSharedLibName)) {
9502                return null;
9503            }
9504            if (res == null) {
9505                res = new ArrayList<>();
9506            }
9507            res.add(pkg);
9508            try {
9509                updateSharedLibrariesLPr(pkg, changingPkg);
9510            } catch (PackageManagerException e) {
9511                // If a system app update or an app and a required lib missing we
9512                // delete the package and for updated system apps keep the data as
9513                // it is better for the user to reinstall than to be in an limbo
9514                // state. Also libs disappearing under an app should never happen
9515                // - just in case.
9516                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9517                    final int flags = pkg.isUpdatedSystemApp()
9518                            ? PackageManager.DELETE_KEEP_DATA : 0;
9519                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9520                            flags , null, true, null);
9521                }
9522                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9523            }
9524        }
9525        return res;
9526    }
9527
9528    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9529            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9530            @Nullable UserHandle user) throws PackageManagerException {
9531        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9532        // If the package has children and this is the first dive in the function
9533        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9534        // whether all packages (parent and children) would be successfully scanned
9535        // before the actual scan since scanning mutates internal state and we want
9536        // to atomically install the package and its children.
9537        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9538            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9539                scanFlags |= SCAN_CHECK_ONLY;
9540            }
9541        } else {
9542            scanFlags &= ~SCAN_CHECK_ONLY;
9543        }
9544
9545        final PackageParser.Package scannedPkg;
9546        try {
9547            // Scan the parent
9548            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
9549            // Scan the children
9550            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9551            for (int i = 0; i < childCount; i++) {
9552                PackageParser.Package childPkg = pkg.childPackages.get(i);
9553                scanPackageLI(childPkg, parseFlags,
9554                        scanFlags, currentTime, user);
9555            }
9556        } finally {
9557            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9558        }
9559
9560        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9561            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9562        }
9563
9564        return scannedPkg;
9565    }
9566
9567    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
9568            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9569            @Nullable UserHandle user) throws PackageManagerException {
9570        boolean success = false;
9571        try {
9572            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
9573                    currentTime, user);
9574            success = true;
9575            return res;
9576        } finally {
9577            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9578                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9579                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9580                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9581                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9582            }
9583        }
9584    }
9585
9586    /**
9587     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9588     */
9589    private static boolean apkHasCode(String fileName) {
9590        StrictJarFile jarFile = null;
9591        try {
9592            jarFile = new StrictJarFile(fileName,
9593                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9594            return jarFile.findEntry("classes.dex") != null;
9595        } catch (IOException ignore) {
9596        } finally {
9597            try {
9598                if (jarFile != null) {
9599                    jarFile.close();
9600                }
9601            } catch (IOException ignore) {}
9602        }
9603        return false;
9604    }
9605
9606    /**
9607     * Enforces code policy for the package. This ensures that if an APK has
9608     * declared hasCode="true" in its manifest that the APK actually contains
9609     * code.
9610     *
9611     * @throws PackageManagerException If bytecode could not be found when it should exist
9612     */
9613    private static void assertCodePolicy(PackageParser.Package pkg)
9614            throws PackageManagerException {
9615        final boolean shouldHaveCode =
9616                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9617        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9618            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9619                    "Package " + pkg.baseCodePath + " code is missing");
9620        }
9621
9622        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9623            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9624                final boolean splitShouldHaveCode =
9625                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9626                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9627                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9628                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9629                }
9630            }
9631        }
9632    }
9633
9634    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9635            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9636            @Nullable UserHandle user)
9637                    throws PackageManagerException {
9638        if (DEBUG_PACKAGE_SCANNING) {
9639            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9640                Log.d(TAG, "Scanning package " + pkg.packageName);
9641        }
9642
9643        applyPolicy(pkg, parseFlags, scanFlags);
9644
9645        assertPackageIsValid(pkg, parseFlags, scanFlags);
9646
9647        if (Build.IS_DEBUGGABLE &&
9648                pkg.isPrivileged() &&
9649                SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, false)) {
9650            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
9651        }
9652
9653        // Initialize package source and resource directories
9654        final File scanFile = new File(pkg.codePath);
9655        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9656        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9657
9658        SharedUserSetting suid = null;
9659        PackageSetting pkgSetting = null;
9660
9661        // Getting the package setting may have a side-effect, so if we
9662        // are only checking if scan would succeed, stash a copy of the
9663        // old setting to restore at the end.
9664        PackageSetting nonMutatedPs = null;
9665
9666        // We keep references to the derived CPU Abis from settings in oder to reuse
9667        // them in the case where we're not upgrading or booting for the first time.
9668        String primaryCpuAbiFromSettings = null;
9669        String secondaryCpuAbiFromSettings = null;
9670
9671        // writer
9672        synchronized (mPackages) {
9673            if (pkg.mSharedUserId != null) {
9674                // SIDE EFFECTS; may potentially allocate a new shared user
9675                suid = mSettings.getSharedUserLPw(
9676                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9677                if (DEBUG_PACKAGE_SCANNING) {
9678                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9679                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9680                                + "): packages=" + suid.packages);
9681                }
9682            }
9683
9684            // Check if we are renaming from an original package name.
9685            PackageSetting origPackage = null;
9686            String realName = null;
9687            if (pkg.mOriginalPackages != null) {
9688                // This package may need to be renamed to a previously
9689                // installed name.  Let's check on that...
9690                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9691                if (pkg.mOriginalPackages.contains(renamed)) {
9692                    // This package had originally been installed as the
9693                    // original name, and we have already taken care of
9694                    // transitioning to the new one.  Just update the new
9695                    // one to continue using the old name.
9696                    realName = pkg.mRealPackage;
9697                    if (!pkg.packageName.equals(renamed)) {
9698                        // Callers into this function may have already taken
9699                        // care of renaming the package; only do it here if
9700                        // it is not already done.
9701                        pkg.setPackageName(renamed);
9702                    }
9703                } else {
9704                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9705                        if ((origPackage = mSettings.getPackageLPr(
9706                                pkg.mOriginalPackages.get(i))) != null) {
9707                            // We do have the package already installed under its
9708                            // original name...  should we use it?
9709                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9710                                // New package is not compatible with original.
9711                                origPackage = null;
9712                                continue;
9713                            } else if (origPackage.sharedUser != null) {
9714                                // Make sure uid is compatible between packages.
9715                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9716                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9717                                            + " to " + pkg.packageName + ": old uid "
9718                                            + origPackage.sharedUser.name
9719                                            + " differs from " + pkg.mSharedUserId);
9720                                    origPackage = null;
9721                                    continue;
9722                                }
9723                                // TODO: Add case when shared user id is added [b/28144775]
9724                            } else {
9725                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9726                                        + pkg.packageName + " to old name " + origPackage.name);
9727                            }
9728                            break;
9729                        }
9730                    }
9731                }
9732            }
9733
9734            if (mTransferedPackages.contains(pkg.packageName)) {
9735                Slog.w(TAG, "Package " + pkg.packageName
9736                        + " was transferred to another, but its .apk remains");
9737            }
9738
9739            // See comments in nonMutatedPs declaration
9740            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9741                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9742                if (foundPs != null) {
9743                    nonMutatedPs = new PackageSetting(foundPs);
9744                }
9745            }
9746
9747            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9748                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9749                if (foundPs != null) {
9750                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9751                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9752                }
9753            }
9754
9755            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9756            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9757                PackageManagerService.reportSettingsProblem(Log.WARN,
9758                        "Package " + pkg.packageName + " shared user changed from "
9759                                + (pkgSetting.sharedUser != null
9760                                        ? pkgSetting.sharedUser.name : "<nothing>")
9761                                + " to "
9762                                + (suid != null ? suid.name : "<nothing>")
9763                                + "; replacing with new");
9764                pkgSetting = null;
9765            }
9766            final PackageSetting oldPkgSetting =
9767                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9768            final PackageSetting disabledPkgSetting =
9769                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9770
9771            String[] usesStaticLibraries = null;
9772            if (pkg.usesStaticLibraries != null) {
9773                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9774                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9775            }
9776
9777            if (pkgSetting == null) {
9778                final String parentPackageName = (pkg.parentPackage != null)
9779                        ? pkg.parentPackage.packageName : null;
9780                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9781                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
9782                // REMOVE SharedUserSetting from method; update in a separate call
9783                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9784                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9785                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9786                        pkg.applicationInfo.secondaryCpuAbi, pkg.getLongVersionCode(),
9787                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9788                        true /*allowInstall*/, instantApp, virtualPreload,
9789                        parentPackageName, pkg.getChildPackageNames(),
9790                        UserManagerService.getInstance(), usesStaticLibraries,
9791                        pkg.usesStaticLibrariesVersions);
9792                // SIDE EFFECTS; updates system state; move elsewhere
9793                if (origPackage != null) {
9794                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9795                }
9796                mSettings.addUserToSettingLPw(pkgSetting);
9797            } else {
9798                // REMOVE SharedUserSetting from method; update in a separate call.
9799                //
9800                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9801                // secondaryCpuAbi are not known at this point so we always update them
9802                // to null here, only to reset them at a later point.
9803                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9804                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9805                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9806                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9807                        UserManagerService.getInstance(), usesStaticLibraries,
9808                        pkg.usesStaticLibrariesVersions);
9809            }
9810            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9811            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9812
9813            // SIDE EFFECTS; modifies system state; move elsewhere
9814            if (pkgSetting.origPackage != null) {
9815                // If we are first transitioning from an original package,
9816                // fix up the new package's name now.  We need to do this after
9817                // looking up the package under its new name, so getPackageLP
9818                // can take care of fiddling things correctly.
9819                pkg.setPackageName(origPackage.name);
9820
9821                // File a report about this.
9822                String msg = "New package " + pkgSetting.realName
9823                        + " renamed to replace old package " + pkgSetting.name;
9824                reportSettingsProblem(Log.WARN, msg);
9825
9826                // Make a note of it.
9827                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9828                    mTransferedPackages.add(origPackage.name);
9829                }
9830
9831                // No longer need to retain this.
9832                pkgSetting.origPackage = null;
9833            }
9834
9835            // SIDE EFFECTS; modifies system state; move elsewhere
9836            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9837                // Make a note of it.
9838                mTransferedPackages.add(pkg.packageName);
9839            }
9840
9841            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9842                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9843            }
9844
9845            if ((scanFlags & SCAN_BOOTING) == 0
9846                    && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9847                // Check all shared libraries and map to their actual file path.
9848                // We only do this here for apps not on a system dir, because those
9849                // are the only ones that can fail an install due to this.  We
9850                // will take care of the system apps by updating all of their
9851                // library paths after the scan is done. Also during the initial
9852                // scan don't update any libs as we do this wholesale after all
9853                // apps are scanned to avoid dependency based scanning.
9854                updateSharedLibrariesLPr(pkg, null);
9855            }
9856
9857            if (mFoundPolicyFile) {
9858                SELinuxMMAC.assignSeInfoValue(pkg);
9859            }
9860            pkg.applicationInfo.uid = pkgSetting.appId;
9861            pkg.mExtras = pkgSetting;
9862
9863
9864            // Static shared libs have same package with different versions where
9865            // we internally use a synthetic package name to allow multiple versions
9866            // of the same package, therefore we need to compare signatures against
9867            // the package setting for the latest library version.
9868            PackageSetting signatureCheckPs = pkgSetting;
9869            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9870                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9871                if (libraryEntry != null) {
9872                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9873                }
9874            }
9875
9876            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9877            if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9878                if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9879                    // We just determined the app is signed correctly, so bring
9880                    // over the latest parsed certs.
9881                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9882                } else {
9883                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9884                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9885                                "Package " + pkg.packageName + " upgrade keys do not match the "
9886                                + "previously installed version");
9887                    } else {
9888                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9889                        String msg = "System package " + pkg.packageName
9890                                + " signature changed; retaining data.";
9891                        reportSettingsProblem(Log.WARN, msg);
9892                    }
9893                }
9894            } else {
9895                try {
9896                    final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9897                    final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9898                    final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures,
9899                            compareCompat, compareRecover);
9900                    // The new KeySets will be re-added later in the scanning process.
9901                    if (compatMatch) {
9902                        synchronized (mPackages) {
9903                            ksms.removeAppKeySetDataLPw(pkg.packageName);
9904                        }
9905                    }
9906                    // We just determined the app is signed correctly, so bring
9907                    // over the latest parsed certs.
9908                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9909                } catch (PackageManagerException e) {
9910                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9911                        throw e;
9912                    }
9913                    // The signature has changed, but this package is in the system
9914                    // image...  let's recover!
9915                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9916                    // However...  if this package is part of a shared user, but it
9917                    // doesn't match the signature of the shared user, let's fail.
9918                    // What this means is that you can't change the signatures
9919                    // associated with an overall shared user, which doesn't seem all
9920                    // that unreasonable.
9921                    if (signatureCheckPs.sharedUser != null) {
9922                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9923                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9924                            throw new PackageManagerException(
9925                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9926                                    "Signature mismatch for shared user: "
9927                                            + pkgSetting.sharedUser);
9928                        }
9929                    }
9930                    // File a report about this.
9931                    String msg = "System package " + pkg.packageName
9932                            + " signature changed; retaining data.";
9933                    reportSettingsProblem(Log.WARN, msg);
9934                }
9935            }
9936
9937            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9938                // This package wants to adopt ownership of permissions from
9939                // another package.
9940                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9941                    final String origName = pkg.mAdoptPermissions.get(i);
9942                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9943                    if (orig != null) {
9944                        if (verifyPackageUpdateLPr(orig, pkg)) {
9945                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9946                                    + pkg.packageName);
9947                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9948                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9949                        }
9950                    }
9951                }
9952            }
9953        }
9954
9955        pkg.applicationInfo.processName = fixProcessName(
9956                pkg.applicationInfo.packageName,
9957                pkg.applicationInfo.processName);
9958
9959        if (pkg != mPlatformPackage) {
9960            // Get all of our default paths setup
9961            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9962        }
9963
9964        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9965
9966        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9967            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9968                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9969                final boolean extractNativeLibs = !pkg.isLibrary();
9970                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs, mAppLib32InstallDir);
9971                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9972
9973                // Some system apps still use directory structure for native libraries
9974                // in which case we might end up not detecting abi solely based on apk
9975                // structure. Try to detect abi based on directory structure.
9976                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9977                        pkg.applicationInfo.primaryCpuAbi == null) {
9978                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9979                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9980                }
9981            } else {
9982                // This is not a first boot or an upgrade, don't bother deriving the
9983                // ABI during the scan. Instead, trust the value that was stored in the
9984                // package setting.
9985                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9986                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9987
9988                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9989
9990                if (DEBUG_ABI_SELECTION) {
9991                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9992                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9993                        pkg.applicationInfo.secondaryCpuAbi);
9994                }
9995            }
9996        } else {
9997            if ((scanFlags & SCAN_MOVE) != 0) {
9998                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9999                // but we already have this packages package info in the PackageSetting. We just
10000                // use that and derive the native library path based on the new codepath.
10001                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10002                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10003            }
10004
10005            // Set native library paths again. For moves, the path will be updated based on the
10006            // ABIs we've determined above. For non-moves, the path will be updated based on the
10007            // ABIs we determined during compilation, but the path will depend on the final
10008            // package path (after the rename away from the stage path).
10009            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10010        }
10011
10012        // This is a special case for the "system" package, where the ABI is
10013        // dictated by the zygote configuration (and init.rc). We should keep track
10014        // of this ABI so that we can deal with "normal" applications that run under
10015        // the same UID correctly.
10016        if (mPlatformPackage == pkg) {
10017            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10018                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10019        }
10020
10021        // If there's a mismatch between the abi-override in the package setting
10022        // and the abiOverride specified for the install. Warn about this because we
10023        // would've already compiled the app without taking the package setting into
10024        // account.
10025        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10026            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10027                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10028                        " for package " + pkg.packageName);
10029            }
10030        }
10031
10032        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10033        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10034        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10035
10036        // Copy the derived override back to the parsed package, so that we can
10037        // update the package settings accordingly.
10038        pkg.cpuAbiOverride = cpuAbiOverride;
10039
10040        if (DEBUG_ABI_SELECTION) {
10041            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10042                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10043                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10044        }
10045
10046        // Push the derived path down into PackageSettings so we know what to
10047        // clean up at uninstall time.
10048        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10049
10050        if (DEBUG_ABI_SELECTION) {
10051            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10052                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10053                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10054        }
10055
10056        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10057        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10058            // We don't do this here during boot because we can do it all
10059            // at once after scanning all existing packages.
10060            //
10061            // We also do this *before* we perform dexopt on this package, so that
10062            // we can avoid redundant dexopts, and also to make sure we've got the
10063            // code and package path correct.
10064            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10065        }
10066
10067        if (mFactoryTest && pkg.requestedPermissions.contains(
10068                android.Manifest.permission.FACTORY_TEST)) {
10069            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10070        }
10071
10072        if (isSystemApp(pkg)) {
10073            pkgSetting.isOrphaned = true;
10074        }
10075
10076        // Take care of first install / last update times.
10077        final long scanFileTime = getLastModifiedTime(pkg);
10078        if (currentTime != 0) {
10079            if (pkgSetting.firstInstallTime == 0) {
10080                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10081            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10082                pkgSetting.lastUpdateTime = currentTime;
10083            }
10084        } else if (pkgSetting.firstInstallTime == 0) {
10085            // We need *something*.  Take time time stamp of the file.
10086            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10087        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10088            if (scanFileTime != pkgSetting.timeStamp) {
10089                // A package on the system image has changed; consider this
10090                // to be an update.
10091                pkgSetting.lastUpdateTime = scanFileTime;
10092            }
10093        }
10094        pkgSetting.setTimeStamp(scanFileTime);
10095
10096        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10097            if (nonMutatedPs != null) {
10098                synchronized (mPackages) {
10099                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10100                }
10101            }
10102        } else {
10103            final int userId = user == null ? 0 : user.getIdentifier();
10104            // Modify state for the given package setting
10105            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10106                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10107            if (pkgSetting.getInstantApp(userId)) {
10108                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10109            }
10110        }
10111        return pkg;
10112    }
10113
10114    /**
10115     * Applies policy to the parsed package based upon the given policy flags.
10116     * Ensures the package is in a good state.
10117     * <p>
10118     * Implementation detail: This method must NOT have any side effect. It would
10119     * ideally be static, but, it requires locks to read system state.
10120     */
10121    private void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10122            final @ScanFlags int scanFlags) {
10123        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10124            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10125            if (pkg.applicationInfo.isDirectBootAware()) {
10126                // we're direct boot aware; set for all components
10127                for (PackageParser.Service s : pkg.services) {
10128                    s.info.encryptionAware = s.info.directBootAware = true;
10129                }
10130                for (PackageParser.Provider p : pkg.providers) {
10131                    p.info.encryptionAware = p.info.directBootAware = true;
10132                }
10133                for (PackageParser.Activity a : pkg.activities) {
10134                    a.info.encryptionAware = a.info.directBootAware = true;
10135                }
10136                for (PackageParser.Activity r : pkg.receivers) {
10137                    r.info.encryptionAware = r.info.directBootAware = true;
10138                }
10139            }
10140            if (compressedFileExists(pkg.codePath)) {
10141                pkg.isStub = true;
10142            }
10143        } else {
10144            // non system apps can't be flagged as core
10145            pkg.coreApp = false;
10146            // clear flags not applicable to regular apps
10147            pkg.applicationInfo.flags &=
10148                    ~ApplicationInfo.FLAG_PERSISTENT;
10149            pkg.applicationInfo.privateFlags &=
10150                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10151            pkg.applicationInfo.privateFlags &=
10152                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10153            // clear protected broadcasts
10154            pkg.protectedBroadcasts = null;
10155            // cap permission priorities
10156            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10157                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10158                    pkg.permissionGroups.get(i).info.priority = 0;
10159                }
10160            }
10161        }
10162        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10163            // ignore export request for single user receivers
10164            if (pkg.receivers != null) {
10165                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10166                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10167                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10168                        receiver.info.exported = false;
10169                    }
10170                }
10171            }
10172            // ignore export request for single user services
10173            if (pkg.services != null) {
10174                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10175                    final PackageParser.Service service = pkg.services.get(i);
10176                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10177                        service.info.exported = false;
10178                    }
10179                }
10180            }
10181            // ignore export request for single user providers
10182            if (pkg.providers != null) {
10183                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10184                    final PackageParser.Provider provider = pkg.providers.get(i);
10185                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10186                        provider.info.exported = false;
10187                    }
10188                }
10189            }
10190        }
10191        pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0;
10192
10193        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10194            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10195        }
10196
10197        if ((scanFlags & SCAN_AS_OEM) != 0) {
10198            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10199        }
10200
10201        if (!isSystemApp(pkg)) {
10202            // Only system apps can use these features.
10203            pkg.mOriginalPackages = null;
10204            pkg.mRealPackage = null;
10205            pkg.mAdoptPermissions = null;
10206        }
10207    }
10208
10209    /**
10210     * Asserts the parsed package is valid according to the given policy. If the
10211     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10212     * <p>
10213     * Implementation detail: This method must NOT have any side effects. It would
10214     * ideally be static, but, it requires locks to read system state.
10215     *
10216     * @throws PackageManagerException If the package fails any of the validation checks
10217     */
10218    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10219            final @ScanFlags int scanFlags)
10220                    throws PackageManagerException {
10221        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10222            assertCodePolicy(pkg);
10223        }
10224
10225        if (pkg.applicationInfo.getCodePath() == null ||
10226                pkg.applicationInfo.getResourcePath() == null) {
10227            // Bail out. The resource and code paths haven't been set.
10228            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10229                    "Code and resource paths haven't been set correctly");
10230        }
10231
10232        // Make sure we're not adding any bogus keyset info
10233        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10234        ksms.assertScannedPackageValid(pkg);
10235
10236        synchronized (mPackages) {
10237            // The special "android" package can only be defined once
10238            if (pkg.packageName.equals("android")) {
10239                if (mAndroidApplication != null) {
10240                    Slog.w(TAG, "*************************************************");
10241                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10242                    Slog.w(TAG, " codePath=" + pkg.codePath);
10243                    Slog.w(TAG, "*************************************************");
10244                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10245                            "Core android package being redefined.  Skipping.");
10246                }
10247            }
10248
10249            // A package name must be unique; don't allow duplicates
10250            if (mPackages.containsKey(pkg.packageName)) {
10251                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10252                        "Application package " + pkg.packageName
10253                        + " already installed.  Skipping duplicate.");
10254            }
10255
10256            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10257                // Static libs have a synthetic package name containing the version
10258                // but we still want the base name to be unique.
10259                if (mPackages.containsKey(pkg.manifestPackageName)) {
10260                    throw new PackageManagerException(
10261                            "Duplicate static shared lib provider package");
10262                }
10263
10264                // Static shared libraries should have at least O target SDK
10265                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10266                    throw new PackageManagerException(
10267                            "Packages declaring static-shared libs must target O SDK or higher");
10268                }
10269
10270                // Package declaring static a shared lib cannot be instant apps
10271                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10272                    throw new PackageManagerException(
10273                            "Packages declaring static-shared libs cannot be instant apps");
10274                }
10275
10276                // Package declaring static a shared lib cannot be renamed since the package
10277                // name is synthetic and apps can't code around package manager internals.
10278                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10279                    throw new PackageManagerException(
10280                            "Packages declaring static-shared libs cannot be renamed");
10281                }
10282
10283                // Package declaring static a shared lib cannot declare child packages
10284                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10285                    throw new PackageManagerException(
10286                            "Packages declaring static-shared libs cannot have child packages");
10287                }
10288
10289                // Package declaring static a shared lib cannot declare dynamic libs
10290                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10291                    throw new PackageManagerException(
10292                            "Packages declaring static-shared libs cannot declare dynamic libs");
10293                }
10294
10295                // Package declaring static a shared lib cannot declare shared users
10296                if (pkg.mSharedUserId != null) {
10297                    throw new PackageManagerException(
10298                            "Packages declaring static-shared libs cannot declare shared users");
10299                }
10300
10301                // Static shared libs cannot declare activities
10302                if (!pkg.activities.isEmpty()) {
10303                    throw new PackageManagerException(
10304                            "Static shared libs cannot declare activities");
10305                }
10306
10307                // Static shared libs cannot declare services
10308                if (!pkg.services.isEmpty()) {
10309                    throw new PackageManagerException(
10310                            "Static shared libs cannot declare services");
10311                }
10312
10313                // Static shared libs cannot declare providers
10314                if (!pkg.providers.isEmpty()) {
10315                    throw new PackageManagerException(
10316                            "Static shared libs cannot declare content providers");
10317                }
10318
10319                // Static shared libs cannot declare receivers
10320                if (!pkg.receivers.isEmpty()) {
10321                    throw new PackageManagerException(
10322                            "Static shared libs cannot declare broadcast receivers");
10323                }
10324
10325                // Static shared libs cannot declare permission groups
10326                if (!pkg.permissionGroups.isEmpty()) {
10327                    throw new PackageManagerException(
10328                            "Static shared libs cannot declare permission groups");
10329                }
10330
10331                // Static shared libs cannot declare permissions
10332                if (!pkg.permissions.isEmpty()) {
10333                    throw new PackageManagerException(
10334                            "Static shared libs cannot declare permissions");
10335                }
10336
10337                // Static shared libs cannot declare protected broadcasts
10338                if (pkg.protectedBroadcasts != null) {
10339                    throw new PackageManagerException(
10340                            "Static shared libs cannot declare protected broadcasts");
10341                }
10342
10343                // Static shared libs cannot be overlay targets
10344                if (pkg.mOverlayTarget != null) {
10345                    throw new PackageManagerException(
10346                            "Static shared libs cannot be overlay targets");
10347                }
10348
10349                // The version codes must be ordered as lib versions
10350                long minVersionCode = Long.MIN_VALUE;
10351                long maxVersionCode = Long.MAX_VALUE;
10352
10353                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10354                        pkg.staticSharedLibName);
10355                if (versionedLib != null) {
10356                    final int versionCount = versionedLib.size();
10357                    for (int i = 0; i < versionCount; i++) {
10358                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10359                        final long libVersionCode = libInfo.getDeclaringPackage()
10360                                .getLongVersionCode();
10361                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10362                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10363                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10364                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10365                        } else {
10366                            minVersionCode = maxVersionCode = libVersionCode;
10367                            break;
10368                        }
10369                    }
10370                }
10371                if (pkg.getLongVersionCode() < minVersionCode
10372                        || pkg.getLongVersionCode() > maxVersionCode) {
10373                    throw new PackageManagerException("Static shared"
10374                            + " lib version codes must be ordered as lib versions");
10375                }
10376            }
10377
10378            // Only privileged apps and updated privileged apps can add child packages.
10379            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10380                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10381                    throw new PackageManagerException("Only privileged apps can add child "
10382                            + "packages. Ignoring package " + pkg.packageName);
10383                }
10384                final int childCount = pkg.childPackages.size();
10385                for (int i = 0; i < childCount; i++) {
10386                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10387                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10388                            childPkg.packageName)) {
10389                        throw new PackageManagerException("Can't override child of "
10390                                + "another disabled app. Ignoring package " + pkg.packageName);
10391                    }
10392                }
10393            }
10394
10395            // If we're only installing presumed-existing packages, require that the
10396            // scanned APK is both already known and at the path previously established
10397            // for it.  Previously unknown packages we pick up normally, but if we have an
10398            // a priori expectation about this package's install presence, enforce it.
10399            // With a singular exception for new system packages. When an OTA contains
10400            // a new system package, we allow the codepath to change from a system location
10401            // to the user-installed location. If we don't allow this change, any newer,
10402            // user-installed version of the application will be ignored.
10403            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10404                if (mExpectingBetter.containsKey(pkg.packageName)) {
10405                    logCriticalInfo(Log.WARN,
10406                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10407                } else {
10408                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10409                    if (known != null) {
10410                        if (DEBUG_PACKAGE_SCANNING) {
10411                            Log.d(TAG, "Examining " + pkg.codePath
10412                                    + " and requiring known paths " + known.codePathString
10413                                    + " & " + known.resourcePathString);
10414                        }
10415                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10416                                || !pkg.applicationInfo.getResourcePath().equals(
10417                                        known.resourcePathString)) {
10418                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10419                                    "Application package " + pkg.packageName
10420                                    + " found at " + pkg.applicationInfo.getCodePath()
10421                                    + " but expected at " + known.codePathString
10422                                    + "; ignoring.");
10423                        }
10424                    } else {
10425                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10426                                "Application package " + pkg.packageName
10427                                + " not found; ignoring.");
10428                    }
10429                }
10430            }
10431
10432            // Verify that this new package doesn't have any content providers
10433            // that conflict with existing packages.  Only do this if the
10434            // package isn't already installed, since we don't want to break
10435            // things that are installed.
10436            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10437                final int N = pkg.providers.size();
10438                int i;
10439                for (i=0; i<N; i++) {
10440                    PackageParser.Provider p = pkg.providers.get(i);
10441                    if (p.info.authority != null) {
10442                        String names[] = p.info.authority.split(";");
10443                        for (int j = 0; j < names.length; j++) {
10444                            if (mProvidersByAuthority.containsKey(names[j])) {
10445                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10446                                final String otherPackageName =
10447                                        ((other != null && other.getComponentName() != null) ?
10448                                                other.getComponentName().getPackageName() : "?");
10449                                throw new PackageManagerException(
10450                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10451                                        "Can't install because provider name " + names[j]
10452                                                + " (in package " + pkg.applicationInfo.packageName
10453                                                + ") is already used by " + otherPackageName);
10454                            }
10455                        }
10456                    }
10457                }
10458            }
10459        }
10460    }
10461
10462    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
10463            int type, String declaringPackageName, long declaringVersionCode) {
10464        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10465        if (versionedLib == null) {
10466            versionedLib = new LongSparseArray<>();
10467            mSharedLibraries.put(name, versionedLib);
10468            if (type == SharedLibraryInfo.TYPE_STATIC) {
10469                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10470            }
10471        } else if (versionedLib.indexOfKey(version) >= 0) {
10472            return false;
10473        }
10474        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10475                version, type, declaringPackageName, declaringVersionCode);
10476        versionedLib.put(version, libEntry);
10477        return true;
10478    }
10479
10480    private boolean removeSharedLibraryLPw(String name, long version) {
10481        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10482        if (versionedLib == null) {
10483            return false;
10484        }
10485        final int libIdx = versionedLib.indexOfKey(version);
10486        if (libIdx < 0) {
10487            return false;
10488        }
10489        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10490        versionedLib.remove(version);
10491        if (versionedLib.size() <= 0) {
10492            mSharedLibraries.remove(name);
10493            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10494                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10495                        .getPackageName());
10496            }
10497        }
10498        return true;
10499    }
10500
10501    /**
10502     * Adds a scanned package to the system. When this method is finished, the package will
10503     * be available for query, resolution, etc...
10504     */
10505    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10506            UserHandle user, final @ScanFlags int scanFlags, boolean chatty)
10507                    throws PackageManagerException {
10508        final String pkgName = pkg.packageName;
10509        if (mCustomResolverComponentName != null &&
10510                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10511            setUpCustomResolverActivity(pkg);
10512        }
10513
10514        if (pkg.packageName.equals("android")) {
10515            synchronized (mPackages) {
10516                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10517                    // Set up information for our fall-back user intent resolution activity.
10518                    mPlatformPackage = pkg;
10519                    pkg.mVersionCode = mSdkVersion;
10520                    pkg.mVersionCodeMajor = 0;
10521                    mAndroidApplication = pkg.applicationInfo;
10522                    if (!mResolverReplaced) {
10523                        mResolveActivity.applicationInfo = mAndroidApplication;
10524                        mResolveActivity.name = ResolverActivity.class.getName();
10525                        mResolveActivity.packageName = mAndroidApplication.packageName;
10526                        mResolveActivity.processName = "system:ui";
10527                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10528                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10529                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10530                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10531                        mResolveActivity.exported = true;
10532                        mResolveActivity.enabled = true;
10533                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10534                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10535                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10536                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10537                                | ActivityInfo.CONFIG_ORIENTATION
10538                                | ActivityInfo.CONFIG_KEYBOARD
10539                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10540                        mResolveInfo.activityInfo = mResolveActivity;
10541                        mResolveInfo.priority = 0;
10542                        mResolveInfo.preferredOrder = 0;
10543                        mResolveInfo.match = 0;
10544                        mResolveComponentName = new ComponentName(
10545                                mAndroidApplication.packageName, mResolveActivity.name);
10546                    }
10547                }
10548            }
10549        }
10550
10551        ArrayList<PackageParser.Package> clientLibPkgs = null;
10552        // writer
10553        synchronized (mPackages) {
10554            boolean hasStaticSharedLibs = false;
10555
10556            // Any app can add new static shared libraries
10557            if (pkg.staticSharedLibName != null) {
10558                // Static shared libs don't allow renaming as they have synthetic package
10559                // names to allow install of multiple versions, so use name from manifest.
10560                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10561                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10562                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
10563                    hasStaticSharedLibs = true;
10564                } else {
10565                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10566                                + pkg.staticSharedLibName + " already exists; skipping");
10567                }
10568                // Static shared libs cannot be updated once installed since they
10569                // use synthetic package name which includes the version code, so
10570                // not need to update other packages's shared lib dependencies.
10571            }
10572
10573            if (!hasStaticSharedLibs
10574                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10575                // Only system apps can add new dynamic shared libraries.
10576                if (pkg.libraryNames != null) {
10577                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10578                        String name = pkg.libraryNames.get(i);
10579                        boolean allowed = false;
10580                        if (pkg.isUpdatedSystemApp()) {
10581                            // New library entries can only be added through the
10582                            // system image.  This is important to get rid of a lot
10583                            // of nasty edge cases: for example if we allowed a non-
10584                            // system update of the app to add a library, then uninstalling
10585                            // the update would make the library go away, and assumptions
10586                            // we made such as through app install filtering would now
10587                            // have allowed apps on the device which aren't compatible
10588                            // with it.  Better to just have the restriction here, be
10589                            // conservative, and create many fewer cases that can negatively
10590                            // impact the user experience.
10591                            final PackageSetting sysPs = mSettings
10592                                    .getDisabledSystemPkgLPr(pkg.packageName);
10593                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10594                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10595                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10596                                        allowed = true;
10597                                        break;
10598                                    }
10599                                }
10600                            }
10601                        } else {
10602                            allowed = true;
10603                        }
10604                        if (allowed) {
10605                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10606                                    SharedLibraryInfo.VERSION_UNDEFINED,
10607                                    SharedLibraryInfo.TYPE_DYNAMIC,
10608                                    pkg.packageName, pkg.getLongVersionCode())) {
10609                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10610                                        + name + " already exists; skipping");
10611                            }
10612                        } else {
10613                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10614                                    + name + " that is not declared on system image; skipping");
10615                        }
10616                    }
10617
10618                    if ((scanFlags & SCAN_BOOTING) == 0) {
10619                        // If we are not booting, we need to update any applications
10620                        // that are clients of our shared library.  If we are booting,
10621                        // this will all be done once the scan is complete.
10622                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10623                    }
10624                }
10625            }
10626        }
10627
10628        if ((scanFlags & SCAN_BOOTING) != 0) {
10629            // No apps can run during boot scan, so they don't need to be frozen
10630        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10631            // Caller asked to not kill app, so it's probably not frozen
10632        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10633            // Caller asked us to ignore frozen check for some reason; they
10634            // probably didn't know the package name
10635        } else {
10636            // We're doing major surgery on this package, so it better be frozen
10637            // right now to keep it from launching
10638            checkPackageFrozen(pkgName);
10639        }
10640
10641        // Also need to kill any apps that are dependent on the library.
10642        if (clientLibPkgs != null) {
10643            for (int i=0; i<clientLibPkgs.size(); i++) {
10644                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10645                killApplication(clientPkg.applicationInfo.packageName,
10646                        clientPkg.applicationInfo.uid, "update lib");
10647            }
10648        }
10649
10650        // writer
10651        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10652
10653        synchronized (mPackages) {
10654            // We don't expect installation to fail beyond this point
10655
10656            // Add the new setting to mSettings
10657            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10658            // Add the new setting to mPackages
10659            mPackages.put(pkg.applicationInfo.packageName, pkg);
10660            // Make sure we don't accidentally delete its data.
10661            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10662            while (iter.hasNext()) {
10663                PackageCleanItem item = iter.next();
10664                if (pkgName.equals(item.packageName)) {
10665                    iter.remove();
10666                }
10667            }
10668
10669            // Add the package's KeySets to the global KeySetManagerService
10670            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10671            ksms.addScannedPackageLPw(pkg);
10672
10673            int N = pkg.providers.size();
10674            StringBuilder r = null;
10675            int i;
10676            for (i=0; i<N; i++) {
10677                PackageParser.Provider p = pkg.providers.get(i);
10678                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10679                        p.info.processName);
10680                mProviders.addProvider(p);
10681                p.syncable = p.info.isSyncable;
10682                if (p.info.authority != null) {
10683                    String names[] = p.info.authority.split(";");
10684                    p.info.authority = null;
10685                    for (int j = 0; j < names.length; j++) {
10686                        if (j == 1 && p.syncable) {
10687                            // We only want the first authority for a provider to possibly be
10688                            // syncable, so if we already added this provider using a different
10689                            // authority clear the syncable flag. We copy the provider before
10690                            // changing it because the mProviders object contains a reference
10691                            // to a provider that we don't want to change.
10692                            // Only do this for the second authority since the resulting provider
10693                            // object can be the same for all future authorities for this provider.
10694                            p = new PackageParser.Provider(p);
10695                            p.syncable = false;
10696                        }
10697                        if (!mProvidersByAuthority.containsKey(names[j])) {
10698                            mProvidersByAuthority.put(names[j], p);
10699                            if (p.info.authority == null) {
10700                                p.info.authority = names[j];
10701                            } else {
10702                                p.info.authority = p.info.authority + ";" + names[j];
10703                            }
10704                            if (DEBUG_PACKAGE_SCANNING) {
10705                                if (chatty)
10706                                    Log.d(TAG, "Registered content provider: " + names[j]
10707                                            + ", className = " + p.info.name + ", isSyncable = "
10708                                            + p.info.isSyncable);
10709                            }
10710                        } else {
10711                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10712                            Slog.w(TAG, "Skipping provider name " + names[j] +
10713                                    " (in package " + pkg.applicationInfo.packageName +
10714                                    "): name already used by "
10715                                    + ((other != null && other.getComponentName() != null)
10716                                            ? other.getComponentName().getPackageName() : "?"));
10717                        }
10718                    }
10719                }
10720                if (chatty) {
10721                    if (r == null) {
10722                        r = new StringBuilder(256);
10723                    } else {
10724                        r.append(' ');
10725                    }
10726                    r.append(p.info.name);
10727                }
10728            }
10729            if (r != null) {
10730                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10731            }
10732
10733            N = pkg.services.size();
10734            r = null;
10735            for (i=0; i<N; i++) {
10736                PackageParser.Service s = pkg.services.get(i);
10737                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10738                        s.info.processName);
10739                mServices.addService(s);
10740                if (chatty) {
10741                    if (r == null) {
10742                        r = new StringBuilder(256);
10743                    } else {
10744                        r.append(' ');
10745                    }
10746                    r.append(s.info.name);
10747                }
10748            }
10749            if (r != null) {
10750                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10751            }
10752
10753            N = pkg.receivers.size();
10754            r = null;
10755            for (i=0; i<N; i++) {
10756                PackageParser.Activity a = pkg.receivers.get(i);
10757                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10758                        a.info.processName);
10759                mReceivers.addActivity(a, "receiver");
10760                if (chatty) {
10761                    if (r == null) {
10762                        r = new StringBuilder(256);
10763                    } else {
10764                        r.append(' ');
10765                    }
10766                    r.append(a.info.name);
10767                }
10768            }
10769            if (r != null) {
10770                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10771            }
10772
10773            N = pkg.activities.size();
10774            r = null;
10775            for (i=0; i<N; i++) {
10776                PackageParser.Activity a = pkg.activities.get(i);
10777                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10778                        a.info.processName);
10779                mActivities.addActivity(a, "activity");
10780                if (chatty) {
10781                    if (r == null) {
10782                        r = new StringBuilder(256);
10783                    } else {
10784                        r.append(' ');
10785                    }
10786                    r.append(a.info.name);
10787                }
10788            }
10789            if (r != null) {
10790                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10791            }
10792
10793            // Don't allow ephemeral applications to define new permissions groups.
10794            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10795                Slog.w(TAG, "Permission groups from package " + pkg.packageName
10796                        + " ignored: instant apps cannot define new permission groups.");
10797            } else {
10798                mPermissionManager.addAllPermissionGroups(pkg, chatty);
10799            }
10800
10801            // Don't allow ephemeral applications to define new permissions.
10802            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10803                Slog.w(TAG, "Permissions from package " + pkg.packageName
10804                        + " ignored: instant apps cannot define new permissions.");
10805            } else {
10806                mPermissionManager.addAllPermissions(pkg, chatty);
10807            }
10808
10809            N = pkg.instrumentation.size();
10810            r = null;
10811            for (i=0; i<N; i++) {
10812                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10813                a.info.packageName = pkg.applicationInfo.packageName;
10814                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10815                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10816                a.info.splitNames = pkg.splitNames;
10817                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10818                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10819                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10820                a.info.dataDir = pkg.applicationInfo.dataDir;
10821                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10822                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10823                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10824                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10825                mInstrumentation.put(a.getComponentName(), a);
10826                if (chatty) {
10827                    if (r == null) {
10828                        r = new StringBuilder(256);
10829                    } else {
10830                        r.append(' ');
10831                    }
10832                    r.append(a.info.name);
10833                }
10834            }
10835            if (r != null) {
10836                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10837            }
10838
10839            if (pkg.protectedBroadcasts != null) {
10840                N = pkg.protectedBroadcasts.size();
10841                synchronized (mProtectedBroadcasts) {
10842                    for (i = 0; i < N; i++) {
10843                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10844                    }
10845                }
10846            }
10847        }
10848
10849        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10850    }
10851
10852    /**
10853     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10854     * is derived purely on the basis of the contents of {@code scanFile} and
10855     * {@code cpuAbiOverride}.
10856     *
10857     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10858     */
10859    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
10860            boolean extractLibs, File appLib32InstallDir)
10861                    throws PackageManagerException {
10862        // Give ourselves some initial paths; we'll come back for another
10863        // pass once we've determined ABI below.
10864        setNativeLibraryPaths(pkg, appLib32InstallDir);
10865
10866        // We would never need to extract libs for forward-locked and external packages,
10867        // since the container service will do it for us. We shouldn't attempt to
10868        // extract libs from system app when it was not updated.
10869        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10870                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10871            extractLibs = false;
10872        }
10873
10874        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10875        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10876
10877        NativeLibraryHelper.Handle handle = null;
10878        try {
10879            handle = NativeLibraryHelper.Handle.create(pkg);
10880            // TODO(multiArch): This can be null for apps that didn't go through the
10881            // usual installation process. We can calculate it again, like we
10882            // do during install time.
10883            //
10884            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10885            // unnecessary.
10886            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10887
10888            // Null out the abis so that they can be recalculated.
10889            pkg.applicationInfo.primaryCpuAbi = null;
10890            pkg.applicationInfo.secondaryCpuAbi = null;
10891            if (isMultiArch(pkg.applicationInfo)) {
10892                // Warn if we've set an abiOverride for multi-lib packages..
10893                // By definition, we need to copy both 32 and 64 bit libraries for
10894                // such packages.
10895                if (pkg.cpuAbiOverride != null
10896                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10897                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10898                }
10899
10900                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10901                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10902                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10903                    if (extractLibs) {
10904                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10905                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10906                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10907                                useIsaSpecificSubdirs);
10908                    } else {
10909                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10910                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10911                    }
10912                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10913                }
10914
10915                // Shared library native code should be in the APK zip aligned
10916                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
10917                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10918                            "Shared library native lib extraction not supported");
10919                }
10920
10921                maybeThrowExceptionForMultiArchCopy(
10922                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10923
10924                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10925                    if (extractLibs) {
10926                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10927                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10928                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10929                                useIsaSpecificSubdirs);
10930                    } else {
10931                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10932                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10933                    }
10934                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10935                }
10936
10937                maybeThrowExceptionForMultiArchCopy(
10938                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10939
10940                if (abi64 >= 0) {
10941                    // Shared library native libs should be in the APK zip aligned
10942                    if (extractLibs && pkg.isLibrary()) {
10943                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10944                                "Shared library native lib extraction not supported");
10945                    }
10946                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10947                }
10948
10949                if (abi32 >= 0) {
10950                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10951                    if (abi64 >= 0) {
10952                        if (pkg.use32bitAbi) {
10953                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10954                            pkg.applicationInfo.primaryCpuAbi = abi;
10955                        } else {
10956                            pkg.applicationInfo.secondaryCpuAbi = abi;
10957                        }
10958                    } else {
10959                        pkg.applicationInfo.primaryCpuAbi = abi;
10960                    }
10961                }
10962            } else {
10963                String[] abiList = (cpuAbiOverride != null) ?
10964                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10965
10966                // Enable gross and lame hacks for apps that are built with old
10967                // SDK tools. We must scan their APKs for renderscript bitcode and
10968                // not launch them if it's present. Don't bother checking on devices
10969                // that don't have 64 bit support.
10970                boolean needsRenderScriptOverride = false;
10971                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10972                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10973                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10974                    needsRenderScriptOverride = true;
10975                }
10976
10977                final int copyRet;
10978                if (extractLibs) {
10979                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10980                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10981                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10982                } else {
10983                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10984                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10985                }
10986                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10987
10988                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10989                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10990                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10991                }
10992
10993                if (copyRet >= 0) {
10994                    // Shared libraries that have native libs must be multi-architecture
10995                    if (pkg.isLibrary()) {
10996                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10997                                "Shared library with native libs must be multiarch");
10998                    }
10999                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11000                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11001                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11002                } else if (needsRenderScriptOverride) {
11003                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11004                }
11005            }
11006        } catch (IOException ioe) {
11007            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11008        } finally {
11009            IoUtils.closeQuietly(handle);
11010        }
11011
11012        // Now that we've calculated the ABIs and determined if it's an internal app,
11013        // we will go ahead and populate the nativeLibraryPath.
11014        setNativeLibraryPaths(pkg, appLib32InstallDir);
11015    }
11016
11017    /**
11018     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11019     * i.e, so that all packages can be run inside a single process if required.
11020     *
11021     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11022     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11023     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11024     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11025     * updating a package that belongs to a shared user.
11026     *
11027     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11028     * adds unnecessary complexity.
11029     */
11030    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11031            PackageParser.Package scannedPackage) {
11032        String requiredInstructionSet = null;
11033        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11034            requiredInstructionSet = VMRuntime.getInstructionSet(
11035                     scannedPackage.applicationInfo.primaryCpuAbi);
11036        }
11037
11038        PackageSetting requirer = null;
11039        for (PackageSetting ps : packagesForUser) {
11040            // If packagesForUser contains scannedPackage, we skip it. This will happen
11041            // when scannedPackage is an update of an existing package. Without this check,
11042            // we will never be able to change the ABI of any package belonging to a shared
11043            // user, even if it's compatible with other packages.
11044            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11045                if (ps.primaryCpuAbiString == null) {
11046                    continue;
11047                }
11048
11049                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11050                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11051                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11052                    // this but there's not much we can do.
11053                    String errorMessage = "Instruction set mismatch, "
11054                            + ((requirer == null) ? "[caller]" : requirer)
11055                            + " requires " + requiredInstructionSet + " whereas " + ps
11056                            + " requires " + instructionSet;
11057                    Slog.w(TAG, errorMessage);
11058                }
11059
11060                if (requiredInstructionSet == null) {
11061                    requiredInstructionSet = instructionSet;
11062                    requirer = ps;
11063                }
11064            }
11065        }
11066
11067        if (requiredInstructionSet != null) {
11068            String adjustedAbi;
11069            if (requirer != null) {
11070                // requirer != null implies that either scannedPackage was null or that scannedPackage
11071                // did not require an ABI, in which case we have to adjust scannedPackage to match
11072                // the ABI of the set (which is the same as requirer's ABI)
11073                adjustedAbi = requirer.primaryCpuAbiString;
11074                if (scannedPackage != null) {
11075                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11076                }
11077            } else {
11078                // requirer == null implies that we're updating all ABIs in the set to
11079                // match scannedPackage.
11080                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11081            }
11082
11083            for (PackageSetting ps : packagesForUser) {
11084                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11085                    if (ps.primaryCpuAbiString != null) {
11086                        continue;
11087                    }
11088
11089                    ps.primaryCpuAbiString = adjustedAbi;
11090                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11091                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11092                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11093                        if (DEBUG_ABI_SELECTION) {
11094                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11095                                    + " (requirer="
11096                                    + (requirer != null ? requirer.pkg : "null")
11097                                    + ", scannedPackage="
11098                                    + (scannedPackage != null ? scannedPackage : "null")
11099                                    + ")");
11100                        }
11101                        try {
11102                            mInstaller.rmdex(ps.codePathString,
11103                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11104                        } catch (InstallerException ignored) {
11105                        }
11106                    }
11107                }
11108            }
11109        }
11110    }
11111
11112    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11113        synchronized (mPackages) {
11114            mResolverReplaced = true;
11115            // Set up information for custom user intent resolution activity.
11116            mResolveActivity.applicationInfo = pkg.applicationInfo;
11117            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11118            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11119            mResolveActivity.processName = pkg.applicationInfo.packageName;
11120            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11121            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11122                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11123            mResolveActivity.theme = 0;
11124            mResolveActivity.exported = true;
11125            mResolveActivity.enabled = true;
11126            mResolveInfo.activityInfo = mResolveActivity;
11127            mResolveInfo.priority = 0;
11128            mResolveInfo.preferredOrder = 0;
11129            mResolveInfo.match = 0;
11130            mResolveComponentName = mCustomResolverComponentName;
11131            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11132                    mResolveComponentName);
11133        }
11134    }
11135
11136    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11137        if (installerActivity == null) {
11138            if (DEBUG_EPHEMERAL) {
11139                Slog.d(TAG, "Clear ephemeral installer activity");
11140            }
11141            mInstantAppInstallerActivity = null;
11142            return;
11143        }
11144
11145        if (DEBUG_EPHEMERAL) {
11146            Slog.d(TAG, "Set ephemeral installer activity: "
11147                    + installerActivity.getComponentName());
11148        }
11149        // Set up information for ephemeral installer activity
11150        mInstantAppInstallerActivity = installerActivity;
11151        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11152                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11153        mInstantAppInstallerActivity.exported = true;
11154        mInstantAppInstallerActivity.enabled = true;
11155        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11156        mInstantAppInstallerInfo.priority = 0;
11157        mInstantAppInstallerInfo.preferredOrder = 1;
11158        mInstantAppInstallerInfo.isDefault = true;
11159        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11160                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11161    }
11162
11163    private static String calculateBundledApkRoot(final String codePathString) {
11164        final File codePath = new File(codePathString);
11165        final File codeRoot;
11166        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11167            codeRoot = Environment.getRootDirectory();
11168        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11169            codeRoot = Environment.getOemDirectory();
11170        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11171            codeRoot = Environment.getVendorDirectory();
11172        } else {
11173            // Unrecognized code path; take its top real segment as the apk root:
11174            // e.g. /something/app/blah.apk => /something
11175            try {
11176                File f = codePath.getCanonicalFile();
11177                File parent = f.getParentFile();    // non-null because codePath is a file
11178                File tmp;
11179                while ((tmp = parent.getParentFile()) != null) {
11180                    f = parent;
11181                    parent = tmp;
11182                }
11183                codeRoot = f;
11184                Slog.w(TAG, "Unrecognized code path "
11185                        + codePath + " - using " + codeRoot);
11186            } catch (IOException e) {
11187                // Can't canonicalize the code path -- shenanigans?
11188                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11189                return Environment.getRootDirectory().getPath();
11190            }
11191        }
11192        return codeRoot.getPath();
11193    }
11194
11195    /**
11196     * Derive and set the location of native libraries for the given package,
11197     * which varies depending on where and how the package was installed.
11198     */
11199    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11200        final ApplicationInfo info = pkg.applicationInfo;
11201        final String codePath = pkg.codePath;
11202        final File codeFile = new File(codePath);
11203        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11204        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11205
11206        info.nativeLibraryRootDir = null;
11207        info.nativeLibraryRootRequiresIsa = false;
11208        info.nativeLibraryDir = null;
11209        info.secondaryNativeLibraryDir = null;
11210
11211        if (isApkFile(codeFile)) {
11212            // Monolithic install
11213            if (bundledApp) {
11214                // If "/system/lib64/apkname" exists, assume that is the per-package
11215                // native library directory to use; otherwise use "/system/lib/apkname".
11216                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11217                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11218                        getPrimaryInstructionSet(info));
11219
11220                // This is a bundled system app so choose the path based on the ABI.
11221                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11222                // is just the default path.
11223                final String apkName = deriveCodePathName(codePath);
11224                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11225                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11226                        apkName).getAbsolutePath();
11227
11228                if (info.secondaryCpuAbi != null) {
11229                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11230                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11231                            secondaryLibDir, apkName).getAbsolutePath();
11232                }
11233            } else if (asecApp) {
11234                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11235                        .getAbsolutePath();
11236            } else {
11237                final String apkName = deriveCodePathName(codePath);
11238                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11239                        .getAbsolutePath();
11240            }
11241
11242            info.nativeLibraryRootRequiresIsa = false;
11243            info.nativeLibraryDir = info.nativeLibraryRootDir;
11244        } else {
11245            // Cluster install
11246            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11247            info.nativeLibraryRootRequiresIsa = true;
11248
11249            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11250                    getPrimaryInstructionSet(info)).getAbsolutePath();
11251
11252            if (info.secondaryCpuAbi != null) {
11253                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11254                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11255            }
11256        }
11257    }
11258
11259    /**
11260     * Calculate the abis and roots for a bundled app. These can uniquely
11261     * be determined from the contents of the system partition, i.e whether
11262     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11263     * of this information, and instead assume that the system was built
11264     * sensibly.
11265     */
11266    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11267                                           PackageSetting pkgSetting) {
11268        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11269
11270        // If "/system/lib64/apkname" exists, assume that is the per-package
11271        // native library directory to use; otherwise use "/system/lib/apkname".
11272        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11273        setBundledAppAbi(pkg, apkRoot, apkName);
11274        // pkgSetting might be null during rescan following uninstall of updates
11275        // to a bundled app, so accommodate that possibility.  The settings in
11276        // that case will be established later from the parsed package.
11277        //
11278        // If the settings aren't null, sync them up with what we've just derived.
11279        // note that apkRoot isn't stored in the package settings.
11280        if (pkgSetting != null) {
11281            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11282            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11283        }
11284    }
11285
11286    /**
11287     * Deduces the ABI of a bundled app and sets the relevant fields on the
11288     * parsed pkg object.
11289     *
11290     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11291     *        under which system libraries are installed.
11292     * @param apkName the name of the installed package.
11293     */
11294    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11295        final File codeFile = new File(pkg.codePath);
11296
11297        final boolean has64BitLibs;
11298        final boolean has32BitLibs;
11299        if (isApkFile(codeFile)) {
11300            // Monolithic install
11301            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11302            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11303        } else {
11304            // Cluster install
11305            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11306            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11307                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11308                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11309                has64BitLibs = (new File(rootDir, isa)).exists();
11310            } else {
11311                has64BitLibs = false;
11312            }
11313            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11314                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11315                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11316                has32BitLibs = (new File(rootDir, isa)).exists();
11317            } else {
11318                has32BitLibs = false;
11319            }
11320        }
11321
11322        if (has64BitLibs && !has32BitLibs) {
11323            // The package has 64 bit libs, but not 32 bit libs. Its primary
11324            // ABI should be 64 bit. We can safely assume here that the bundled
11325            // native libraries correspond to the most preferred ABI in the list.
11326
11327            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11328            pkg.applicationInfo.secondaryCpuAbi = null;
11329        } else if (has32BitLibs && !has64BitLibs) {
11330            // The package has 32 bit libs but not 64 bit libs. Its primary
11331            // ABI should be 32 bit.
11332
11333            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11334            pkg.applicationInfo.secondaryCpuAbi = null;
11335        } else if (has32BitLibs && has64BitLibs) {
11336            // The application has both 64 and 32 bit bundled libraries. We check
11337            // here that the app declares multiArch support, and warn if it doesn't.
11338            //
11339            // We will be lenient here and record both ABIs. The primary will be the
11340            // ABI that's higher on the list, i.e, a device that's configured to prefer
11341            // 64 bit apps will see a 64 bit primary ABI,
11342
11343            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11344                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11345            }
11346
11347            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11348                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11349                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11350            } else {
11351                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11352                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11353            }
11354        } else {
11355            pkg.applicationInfo.primaryCpuAbi = null;
11356            pkg.applicationInfo.secondaryCpuAbi = null;
11357        }
11358    }
11359
11360    private void killApplication(String pkgName, int appId, String reason) {
11361        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11362    }
11363
11364    private void killApplication(String pkgName, int appId, int userId, String reason) {
11365        // Request the ActivityManager to kill the process(only for existing packages)
11366        // so that we do not end up in a confused state while the user is still using the older
11367        // version of the application while the new one gets installed.
11368        final long token = Binder.clearCallingIdentity();
11369        try {
11370            IActivityManager am = ActivityManager.getService();
11371            if (am != null) {
11372                try {
11373                    am.killApplication(pkgName, appId, userId, reason);
11374                } catch (RemoteException e) {
11375                }
11376            }
11377        } finally {
11378            Binder.restoreCallingIdentity(token);
11379        }
11380    }
11381
11382    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11383        // Remove the parent package setting
11384        PackageSetting ps = (PackageSetting) pkg.mExtras;
11385        if (ps != null) {
11386            removePackageLI(ps, chatty);
11387        }
11388        // Remove the child package setting
11389        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11390        for (int i = 0; i < childCount; i++) {
11391            PackageParser.Package childPkg = pkg.childPackages.get(i);
11392            ps = (PackageSetting) childPkg.mExtras;
11393            if (ps != null) {
11394                removePackageLI(ps, chatty);
11395            }
11396        }
11397    }
11398
11399    void removePackageLI(PackageSetting ps, boolean chatty) {
11400        if (DEBUG_INSTALL) {
11401            if (chatty)
11402                Log.d(TAG, "Removing package " + ps.name);
11403        }
11404
11405        // writer
11406        synchronized (mPackages) {
11407            mPackages.remove(ps.name);
11408            final PackageParser.Package pkg = ps.pkg;
11409            if (pkg != null) {
11410                cleanPackageDataStructuresLILPw(pkg, chatty);
11411            }
11412        }
11413    }
11414
11415    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11416        if (DEBUG_INSTALL) {
11417            if (chatty)
11418                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11419        }
11420
11421        // writer
11422        synchronized (mPackages) {
11423            // Remove the parent package
11424            mPackages.remove(pkg.applicationInfo.packageName);
11425            cleanPackageDataStructuresLILPw(pkg, chatty);
11426
11427            // Remove the child packages
11428            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11429            for (int i = 0; i < childCount; i++) {
11430                PackageParser.Package childPkg = pkg.childPackages.get(i);
11431                mPackages.remove(childPkg.applicationInfo.packageName);
11432                cleanPackageDataStructuresLILPw(childPkg, chatty);
11433            }
11434        }
11435    }
11436
11437    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11438        int N = pkg.providers.size();
11439        StringBuilder r = null;
11440        int i;
11441        for (i=0; i<N; i++) {
11442            PackageParser.Provider p = pkg.providers.get(i);
11443            mProviders.removeProvider(p);
11444            if (p.info.authority == null) {
11445
11446                /* There was another ContentProvider with this authority when
11447                 * this app was installed so this authority is null,
11448                 * Ignore it as we don't have to unregister the provider.
11449                 */
11450                continue;
11451            }
11452            String names[] = p.info.authority.split(";");
11453            for (int j = 0; j < names.length; j++) {
11454                if (mProvidersByAuthority.get(names[j]) == p) {
11455                    mProvidersByAuthority.remove(names[j]);
11456                    if (DEBUG_REMOVE) {
11457                        if (chatty)
11458                            Log.d(TAG, "Unregistered content provider: " + names[j]
11459                                    + ", className = " + p.info.name + ", isSyncable = "
11460                                    + p.info.isSyncable);
11461                    }
11462                }
11463            }
11464            if (DEBUG_REMOVE && chatty) {
11465                if (r == null) {
11466                    r = new StringBuilder(256);
11467                } else {
11468                    r.append(' ');
11469                }
11470                r.append(p.info.name);
11471            }
11472        }
11473        if (r != null) {
11474            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11475        }
11476
11477        N = pkg.services.size();
11478        r = null;
11479        for (i=0; i<N; i++) {
11480            PackageParser.Service s = pkg.services.get(i);
11481            mServices.removeService(s);
11482            if (chatty) {
11483                if (r == null) {
11484                    r = new StringBuilder(256);
11485                } else {
11486                    r.append(' ');
11487                }
11488                r.append(s.info.name);
11489            }
11490        }
11491        if (r != null) {
11492            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11493        }
11494
11495        N = pkg.receivers.size();
11496        r = null;
11497        for (i=0; i<N; i++) {
11498            PackageParser.Activity a = pkg.receivers.get(i);
11499            mReceivers.removeActivity(a, "receiver");
11500            if (DEBUG_REMOVE && chatty) {
11501                if (r == null) {
11502                    r = new StringBuilder(256);
11503                } else {
11504                    r.append(' ');
11505                }
11506                r.append(a.info.name);
11507            }
11508        }
11509        if (r != null) {
11510            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11511        }
11512
11513        N = pkg.activities.size();
11514        r = null;
11515        for (i=0; i<N; i++) {
11516            PackageParser.Activity a = pkg.activities.get(i);
11517            mActivities.removeActivity(a, "activity");
11518            if (DEBUG_REMOVE && chatty) {
11519                if (r == null) {
11520                    r = new StringBuilder(256);
11521                } else {
11522                    r.append(' ');
11523                }
11524                r.append(a.info.name);
11525            }
11526        }
11527        if (r != null) {
11528            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11529        }
11530
11531        mPermissionManager.removeAllPermissions(pkg, chatty);
11532
11533        N = pkg.instrumentation.size();
11534        r = null;
11535        for (i=0; i<N; i++) {
11536            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11537            mInstrumentation.remove(a.getComponentName());
11538            if (DEBUG_REMOVE && chatty) {
11539                if (r == null) {
11540                    r = new StringBuilder(256);
11541                } else {
11542                    r.append(' ');
11543                }
11544                r.append(a.info.name);
11545            }
11546        }
11547        if (r != null) {
11548            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11549        }
11550
11551        r = null;
11552        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11553            // Only system apps can hold shared libraries.
11554            if (pkg.libraryNames != null) {
11555                for (i = 0; i < pkg.libraryNames.size(); i++) {
11556                    String name = pkg.libraryNames.get(i);
11557                    if (removeSharedLibraryLPw(name, 0)) {
11558                        if (DEBUG_REMOVE && chatty) {
11559                            if (r == null) {
11560                                r = new StringBuilder(256);
11561                            } else {
11562                                r.append(' ');
11563                            }
11564                            r.append(name);
11565                        }
11566                    }
11567                }
11568            }
11569        }
11570
11571        r = null;
11572
11573        // Any package can hold static shared libraries.
11574        if (pkg.staticSharedLibName != null) {
11575            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11576                if (DEBUG_REMOVE && chatty) {
11577                    if (r == null) {
11578                        r = new StringBuilder(256);
11579                    } else {
11580                        r.append(' ');
11581                    }
11582                    r.append(pkg.staticSharedLibName);
11583                }
11584            }
11585        }
11586
11587        if (r != null) {
11588            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11589        }
11590    }
11591
11592
11593    final class ActivityIntentResolver
11594            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11595        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11596                boolean defaultOnly, int userId) {
11597            if (!sUserManager.exists(userId)) return null;
11598            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11599            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11600        }
11601
11602        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11603                int userId) {
11604            if (!sUserManager.exists(userId)) return null;
11605            mFlags = flags;
11606            return super.queryIntent(intent, resolvedType,
11607                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11608                    userId);
11609        }
11610
11611        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11612                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11613            if (!sUserManager.exists(userId)) return null;
11614            if (packageActivities == null) {
11615                return null;
11616            }
11617            mFlags = flags;
11618            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11619            final int N = packageActivities.size();
11620            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11621                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11622
11623            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11624            for (int i = 0; i < N; ++i) {
11625                intentFilters = packageActivities.get(i).intents;
11626                if (intentFilters != null && intentFilters.size() > 0) {
11627                    PackageParser.ActivityIntentInfo[] array =
11628                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11629                    intentFilters.toArray(array);
11630                    listCut.add(array);
11631                }
11632            }
11633            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11634        }
11635
11636        /**
11637         * Finds a privileged activity that matches the specified activity names.
11638         */
11639        private PackageParser.Activity findMatchingActivity(
11640                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11641            for (PackageParser.Activity sysActivity : activityList) {
11642                if (sysActivity.info.name.equals(activityInfo.name)) {
11643                    return sysActivity;
11644                }
11645                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11646                    return sysActivity;
11647                }
11648                if (sysActivity.info.targetActivity != null) {
11649                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11650                        return sysActivity;
11651                    }
11652                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11653                        return sysActivity;
11654                    }
11655                }
11656            }
11657            return null;
11658        }
11659
11660        public class IterGenerator<E> {
11661            public Iterator<E> generate(ActivityIntentInfo info) {
11662                return null;
11663            }
11664        }
11665
11666        public class ActionIterGenerator extends IterGenerator<String> {
11667            @Override
11668            public Iterator<String> generate(ActivityIntentInfo info) {
11669                return info.actionsIterator();
11670            }
11671        }
11672
11673        public class CategoriesIterGenerator extends IterGenerator<String> {
11674            @Override
11675            public Iterator<String> generate(ActivityIntentInfo info) {
11676                return info.categoriesIterator();
11677            }
11678        }
11679
11680        public class SchemesIterGenerator extends IterGenerator<String> {
11681            @Override
11682            public Iterator<String> generate(ActivityIntentInfo info) {
11683                return info.schemesIterator();
11684            }
11685        }
11686
11687        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11688            @Override
11689            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11690                return info.authoritiesIterator();
11691            }
11692        }
11693
11694        /**
11695         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11696         * MODIFIED. Do not pass in a list that should not be changed.
11697         */
11698        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11699                IterGenerator<T> generator, Iterator<T> searchIterator) {
11700            // loop through the set of actions; every one must be found in the intent filter
11701            while (searchIterator.hasNext()) {
11702                // we must have at least one filter in the list to consider a match
11703                if (intentList.size() == 0) {
11704                    break;
11705                }
11706
11707                final T searchAction = searchIterator.next();
11708
11709                // loop through the set of intent filters
11710                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11711                while (intentIter.hasNext()) {
11712                    final ActivityIntentInfo intentInfo = intentIter.next();
11713                    boolean selectionFound = false;
11714
11715                    // loop through the intent filter's selection criteria; at least one
11716                    // of them must match the searched criteria
11717                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11718                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11719                        final T intentSelection = intentSelectionIter.next();
11720                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11721                            selectionFound = true;
11722                            break;
11723                        }
11724                    }
11725
11726                    // the selection criteria wasn't found in this filter's set; this filter
11727                    // is not a potential match
11728                    if (!selectionFound) {
11729                        intentIter.remove();
11730                    }
11731                }
11732            }
11733        }
11734
11735        private boolean isProtectedAction(ActivityIntentInfo filter) {
11736            final Iterator<String> actionsIter = filter.actionsIterator();
11737            while (actionsIter != null && actionsIter.hasNext()) {
11738                final String filterAction = actionsIter.next();
11739                if (PROTECTED_ACTIONS.contains(filterAction)) {
11740                    return true;
11741                }
11742            }
11743            return false;
11744        }
11745
11746        /**
11747         * Adjusts the priority of the given intent filter according to policy.
11748         * <p>
11749         * <ul>
11750         * <li>The priority for non privileged applications is capped to '0'</li>
11751         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11752         * <li>The priority for unbundled updates to privileged applications is capped to the
11753         *      priority defined on the system partition</li>
11754         * </ul>
11755         * <p>
11756         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11757         * allowed to obtain any priority on any action.
11758         */
11759        private void adjustPriority(
11760                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11761            // nothing to do; priority is fine as-is
11762            if (intent.getPriority() <= 0) {
11763                return;
11764            }
11765
11766            final ActivityInfo activityInfo = intent.activity.info;
11767            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11768
11769            final boolean privilegedApp =
11770                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11771            if (!privilegedApp) {
11772                // non-privileged applications can never define a priority >0
11773                if (DEBUG_FILTERS) {
11774                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
11775                            + " package: " + applicationInfo.packageName
11776                            + " activity: " + intent.activity.className
11777                            + " origPrio: " + intent.getPriority());
11778                }
11779                intent.setPriority(0);
11780                return;
11781            }
11782
11783            if (systemActivities == null) {
11784                // the system package is not disabled; we're parsing the system partition
11785                if (isProtectedAction(intent)) {
11786                    if (mDeferProtectedFilters) {
11787                        // We can't deal with these just yet. No component should ever obtain a
11788                        // >0 priority for a protected actions, with ONE exception -- the setup
11789                        // wizard. The setup wizard, however, cannot be known until we're able to
11790                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11791                        // until all intent filters have been processed. Chicken, meet egg.
11792                        // Let the filter temporarily have a high priority and rectify the
11793                        // priorities after all system packages have been scanned.
11794                        mProtectedFilters.add(intent);
11795                        if (DEBUG_FILTERS) {
11796                            Slog.i(TAG, "Protected action; save for later;"
11797                                    + " package: " + applicationInfo.packageName
11798                                    + " activity: " + intent.activity.className
11799                                    + " origPrio: " + intent.getPriority());
11800                        }
11801                        return;
11802                    } else {
11803                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11804                            Slog.i(TAG, "No setup wizard;"
11805                                + " All protected intents capped to priority 0");
11806                        }
11807                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11808                            if (DEBUG_FILTERS) {
11809                                Slog.i(TAG, "Found setup wizard;"
11810                                    + " allow priority " + intent.getPriority() + ";"
11811                                    + " package: " + intent.activity.info.packageName
11812                                    + " activity: " + intent.activity.className
11813                                    + " priority: " + intent.getPriority());
11814                            }
11815                            // setup wizard gets whatever it wants
11816                            return;
11817                        }
11818                        if (DEBUG_FILTERS) {
11819                            Slog.i(TAG, "Protected action; cap priority to 0;"
11820                                    + " package: " + intent.activity.info.packageName
11821                                    + " activity: " + intent.activity.className
11822                                    + " origPrio: " + intent.getPriority());
11823                        }
11824                        intent.setPriority(0);
11825                        return;
11826                    }
11827                }
11828                // privileged apps on the system image get whatever priority they request
11829                return;
11830            }
11831
11832            // privileged app unbundled update ... try to find the same activity
11833            final PackageParser.Activity foundActivity =
11834                    findMatchingActivity(systemActivities, activityInfo);
11835            if (foundActivity == null) {
11836                // this is a new activity; it cannot obtain >0 priority
11837                if (DEBUG_FILTERS) {
11838                    Slog.i(TAG, "New activity; cap priority to 0;"
11839                            + " package: " + applicationInfo.packageName
11840                            + " activity: " + intent.activity.className
11841                            + " origPrio: " + intent.getPriority());
11842                }
11843                intent.setPriority(0);
11844                return;
11845            }
11846
11847            // found activity, now check for filter equivalence
11848
11849            // a shallow copy is enough; we modify the list, not its contents
11850            final List<ActivityIntentInfo> intentListCopy =
11851                    new ArrayList<>(foundActivity.intents);
11852            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11853
11854            // find matching action subsets
11855            final Iterator<String> actionsIterator = intent.actionsIterator();
11856            if (actionsIterator != null) {
11857                getIntentListSubset(
11858                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11859                if (intentListCopy.size() == 0) {
11860                    // no more intents to match; we're not equivalent
11861                    if (DEBUG_FILTERS) {
11862                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11863                                + " package: " + applicationInfo.packageName
11864                                + " activity: " + intent.activity.className
11865                                + " origPrio: " + intent.getPriority());
11866                    }
11867                    intent.setPriority(0);
11868                    return;
11869                }
11870            }
11871
11872            // find matching category subsets
11873            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11874            if (categoriesIterator != null) {
11875                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11876                        categoriesIterator);
11877                if (intentListCopy.size() == 0) {
11878                    // no more intents to match; we're not equivalent
11879                    if (DEBUG_FILTERS) {
11880                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11881                                + " package: " + applicationInfo.packageName
11882                                + " activity: " + intent.activity.className
11883                                + " origPrio: " + intent.getPriority());
11884                    }
11885                    intent.setPriority(0);
11886                    return;
11887                }
11888            }
11889
11890            // find matching schemes subsets
11891            final Iterator<String> schemesIterator = intent.schemesIterator();
11892            if (schemesIterator != null) {
11893                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11894                        schemesIterator);
11895                if (intentListCopy.size() == 0) {
11896                    // no more intents to match; we're not equivalent
11897                    if (DEBUG_FILTERS) {
11898                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11899                                + " package: " + applicationInfo.packageName
11900                                + " activity: " + intent.activity.className
11901                                + " origPrio: " + intent.getPriority());
11902                    }
11903                    intent.setPriority(0);
11904                    return;
11905                }
11906            }
11907
11908            // find matching authorities subsets
11909            final Iterator<IntentFilter.AuthorityEntry>
11910                    authoritiesIterator = intent.authoritiesIterator();
11911            if (authoritiesIterator != null) {
11912                getIntentListSubset(intentListCopy,
11913                        new AuthoritiesIterGenerator(),
11914                        authoritiesIterator);
11915                if (intentListCopy.size() == 0) {
11916                    // no more intents to match; we're not equivalent
11917                    if (DEBUG_FILTERS) {
11918                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11919                                + " package: " + applicationInfo.packageName
11920                                + " activity: " + intent.activity.className
11921                                + " origPrio: " + intent.getPriority());
11922                    }
11923                    intent.setPriority(0);
11924                    return;
11925                }
11926            }
11927
11928            // we found matching filter(s); app gets the max priority of all intents
11929            int cappedPriority = 0;
11930            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11931                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11932            }
11933            if (intent.getPriority() > cappedPriority) {
11934                if (DEBUG_FILTERS) {
11935                    Slog.i(TAG, "Found matching filter(s);"
11936                            + " cap priority to " + cappedPriority + ";"
11937                            + " package: " + applicationInfo.packageName
11938                            + " activity: " + intent.activity.className
11939                            + " origPrio: " + intent.getPriority());
11940                }
11941                intent.setPriority(cappedPriority);
11942                return;
11943            }
11944            // all this for nothing; the requested priority was <= what was on the system
11945        }
11946
11947        public final void addActivity(PackageParser.Activity a, String type) {
11948            mActivities.put(a.getComponentName(), a);
11949            if (DEBUG_SHOW_INFO)
11950                Log.v(
11951                TAG, "  " + type + " " +
11952                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11953            if (DEBUG_SHOW_INFO)
11954                Log.v(TAG, "    Class=" + a.info.name);
11955            final int NI = a.intents.size();
11956            for (int j=0; j<NI; j++) {
11957                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11958                if ("activity".equals(type)) {
11959                    final PackageSetting ps =
11960                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11961                    final List<PackageParser.Activity> systemActivities =
11962                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11963                    adjustPriority(systemActivities, intent);
11964                }
11965                if (DEBUG_SHOW_INFO) {
11966                    Log.v(TAG, "    IntentFilter:");
11967                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11968                }
11969                if (!intent.debugCheck()) {
11970                    Log.w(TAG, "==> For Activity " + a.info.name);
11971                }
11972                addFilter(intent);
11973            }
11974        }
11975
11976        public final void removeActivity(PackageParser.Activity a, String type) {
11977            mActivities.remove(a.getComponentName());
11978            if (DEBUG_SHOW_INFO) {
11979                Log.v(TAG, "  " + type + " "
11980                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11981                                : a.info.name) + ":");
11982                Log.v(TAG, "    Class=" + a.info.name);
11983            }
11984            final int NI = a.intents.size();
11985            for (int j=0; j<NI; j++) {
11986                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11987                if (DEBUG_SHOW_INFO) {
11988                    Log.v(TAG, "    IntentFilter:");
11989                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11990                }
11991                removeFilter(intent);
11992            }
11993        }
11994
11995        @Override
11996        protected boolean allowFilterResult(
11997                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
11998            ActivityInfo filterAi = filter.activity.info;
11999            for (int i=dest.size()-1; i>=0; i--) {
12000                ActivityInfo destAi = dest.get(i).activityInfo;
12001                if (destAi.name == filterAi.name
12002                        && destAi.packageName == filterAi.packageName) {
12003                    return false;
12004                }
12005            }
12006            return true;
12007        }
12008
12009        @Override
12010        protected ActivityIntentInfo[] newArray(int size) {
12011            return new ActivityIntentInfo[size];
12012        }
12013
12014        @Override
12015        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12016            if (!sUserManager.exists(userId)) return true;
12017            PackageParser.Package p = filter.activity.owner;
12018            if (p != null) {
12019                PackageSetting ps = (PackageSetting)p.mExtras;
12020                if (ps != null) {
12021                    // System apps are never considered stopped for purposes of
12022                    // filtering, because there may be no way for the user to
12023                    // actually re-launch them.
12024                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12025                            && ps.getStopped(userId);
12026                }
12027            }
12028            return false;
12029        }
12030
12031        @Override
12032        protected boolean isPackageForFilter(String packageName,
12033                PackageParser.ActivityIntentInfo info) {
12034            return packageName.equals(info.activity.owner.packageName);
12035        }
12036
12037        @Override
12038        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12039                int match, int userId) {
12040            if (!sUserManager.exists(userId)) return null;
12041            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12042                return null;
12043            }
12044            final PackageParser.Activity activity = info.activity;
12045            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12046            if (ps == null) {
12047                return null;
12048            }
12049            final PackageUserState userState = ps.readUserState(userId);
12050            ActivityInfo ai =
12051                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12052            if (ai == null) {
12053                return null;
12054            }
12055            final boolean matchExplicitlyVisibleOnly =
12056                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12057            final boolean matchVisibleToInstantApp =
12058                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12059            final boolean componentVisible =
12060                    matchVisibleToInstantApp
12061                    && info.isVisibleToInstantApp()
12062                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12063            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12064            // throw out filters that aren't visible to ephemeral apps
12065            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12066                return null;
12067            }
12068            // throw out instant app filters if we're not explicitly requesting them
12069            if (!matchInstantApp && userState.instantApp) {
12070                return null;
12071            }
12072            // throw out instant app filters if updates are available; will trigger
12073            // instant app resolution
12074            if (userState.instantApp && ps.isUpdateAvailable()) {
12075                return null;
12076            }
12077            final ResolveInfo res = new ResolveInfo();
12078            res.activityInfo = ai;
12079            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12080                res.filter = info;
12081            }
12082            if (info != null) {
12083                res.handleAllWebDataURI = info.handleAllWebDataURI();
12084            }
12085            res.priority = info.getPriority();
12086            res.preferredOrder = activity.owner.mPreferredOrder;
12087            //System.out.println("Result: " + res.activityInfo.className +
12088            //                   " = " + res.priority);
12089            res.match = match;
12090            res.isDefault = info.hasDefault;
12091            res.labelRes = info.labelRes;
12092            res.nonLocalizedLabel = info.nonLocalizedLabel;
12093            if (userNeedsBadging(userId)) {
12094                res.noResourceId = true;
12095            } else {
12096                res.icon = info.icon;
12097            }
12098            res.iconResourceId = info.icon;
12099            res.system = res.activityInfo.applicationInfo.isSystemApp();
12100            res.isInstantAppAvailable = userState.instantApp;
12101            return res;
12102        }
12103
12104        @Override
12105        protected void sortResults(List<ResolveInfo> results) {
12106            Collections.sort(results, mResolvePrioritySorter);
12107        }
12108
12109        @Override
12110        protected void dumpFilter(PrintWriter out, String prefix,
12111                PackageParser.ActivityIntentInfo filter) {
12112            out.print(prefix); out.print(
12113                    Integer.toHexString(System.identityHashCode(filter.activity)));
12114                    out.print(' ');
12115                    filter.activity.printComponentShortName(out);
12116                    out.print(" filter ");
12117                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12118        }
12119
12120        @Override
12121        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12122            return filter.activity;
12123        }
12124
12125        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12126            PackageParser.Activity activity = (PackageParser.Activity)label;
12127            out.print(prefix); out.print(
12128                    Integer.toHexString(System.identityHashCode(activity)));
12129                    out.print(' ');
12130                    activity.printComponentShortName(out);
12131            if (count > 1) {
12132                out.print(" ("); out.print(count); out.print(" filters)");
12133            }
12134            out.println();
12135        }
12136
12137        // Keys are String (activity class name), values are Activity.
12138        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12139                = new ArrayMap<ComponentName, PackageParser.Activity>();
12140        private int mFlags;
12141    }
12142
12143    private final class ServiceIntentResolver
12144            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12145        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12146                boolean defaultOnly, int userId) {
12147            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12148            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12149        }
12150
12151        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12152                int userId) {
12153            if (!sUserManager.exists(userId)) return null;
12154            mFlags = flags;
12155            return super.queryIntent(intent, resolvedType,
12156                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12157                    userId);
12158        }
12159
12160        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12161                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12162            if (!sUserManager.exists(userId)) return null;
12163            if (packageServices == null) {
12164                return null;
12165            }
12166            mFlags = flags;
12167            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12168            final int N = packageServices.size();
12169            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12170                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12171
12172            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12173            for (int i = 0; i < N; ++i) {
12174                intentFilters = packageServices.get(i).intents;
12175                if (intentFilters != null && intentFilters.size() > 0) {
12176                    PackageParser.ServiceIntentInfo[] array =
12177                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12178                    intentFilters.toArray(array);
12179                    listCut.add(array);
12180                }
12181            }
12182            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12183        }
12184
12185        public final void addService(PackageParser.Service s) {
12186            mServices.put(s.getComponentName(), s);
12187            if (DEBUG_SHOW_INFO) {
12188                Log.v(TAG, "  "
12189                        + (s.info.nonLocalizedLabel != null
12190                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12191                Log.v(TAG, "    Class=" + s.info.name);
12192            }
12193            final int NI = s.intents.size();
12194            int j;
12195            for (j=0; j<NI; j++) {
12196                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12197                if (DEBUG_SHOW_INFO) {
12198                    Log.v(TAG, "    IntentFilter:");
12199                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12200                }
12201                if (!intent.debugCheck()) {
12202                    Log.w(TAG, "==> For Service " + s.info.name);
12203                }
12204                addFilter(intent);
12205            }
12206        }
12207
12208        public final void removeService(PackageParser.Service s) {
12209            mServices.remove(s.getComponentName());
12210            if (DEBUG_SHOW_INFO) {
12211                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12212                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12213                Log.v(TAG, "    Class=" + s.info.name);
12214            }
12215            final int NI = s.intents.size();
12216            int j;
12217            for (j=0; j<NI; j++) {
12218                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12219                if (DEBUG_SHOW_INFO) {
12220                    Log.v(TAG, "    IntentFilter:");
12221                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12222                }
12223                removeFilter(intent);
12224            }
12225        }
12226
12227        @Override
12228        protected boolean allowFilterResult(
12229                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12230            ServiceInfo filterSi = filter.service.info;
12231            for (int i=dest.size()-1; i>=0; i--) {
12232                ServiceInfo destAi = dest.get(i).serviceInfo;
12233                if (destAi.name == filterSi.name
12234                        && destAi.packageName == filterSi.packageName) {
12235                    return false;
12236                }
12237            }
12238            return true;
12239        }
12240
12241        @Override
12242        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12243            return new PackageParser.ServiceIntentInfo[size];
12244        }
12245
12246        @Override
12247        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12248            if (!sUserManager.exists(userId)) return true;
12249            PackageParser.Package p = filter.service.owner;
12250            if (p != null) {
12251                PackageSetting ps = (PackageSetting)p.mExtras;
12252                if (ps != null) {
12253                    // System apps are never considered stopped for purposes of
12254                    // filtering, because there may be no way for the user to
12255                    // actually re-launch them.
12256                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12257                            && ps.getStopped(userId);
12258                }
12259            }
12260            return false;
12261        }
12262
12263        @Override
12264        protected boolean isPackageForFilter(String packageName,
12265                PackageParser.ServiceIntentInfo info) {
12266            return packageName.equals(info.service.owner.packageName);
12267        }
12268
12269        @Override
12270        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12271                int match, int userId) {
12272            if (!sUserManager.exists(userId)) return null;
12273            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12274            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12275                return null;
12276            }
12277            final PackageParser.Service service = info.service;
12278            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12279            if (ps == null) {
12280                return null;
12281            }
12282            final PackageUserState userState = ps.readUserState(userId);
12283            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12284                    userState, userId);
12285            if (si == null) {
12286                return null;
12287            }
12288            final boolean matchVisibleToInstantApp =
12289                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12290            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12291            // throw out filters that aren't visible to ephemeral apps
12292            if (matchVisibleToInstantApp
12293                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12294                return null;
12295            }
12296            // throw out ephemeral filters if we're not explicitly requesting them
12297            if (!isInstantApp && userState.instantApp) {
12298                return null;
12299            }
12300            // throw out instant app filters if updates are available; will trigger
12301            // instant app resolution
12302            if (userState.instantApp && ps.isUpdateAvailable()) {
12303                return null;
12304            }
12305            final ResolveInfo res = new ResolveInfo();
12306            res.serviceInfo = si;
12307            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12308                res.filter = filter;
12309            }
12310            res.priority = info.getPriority();
12311            res.preferredOrder = service.owner.mPreferredOrder;
12312            res.match = match;
12313            res.isDefault = info.hasDefault;
12314            res.labelRes = info.labelRes;
12315            res.nonLocalizedLabel = info.nonLocalizedLabel;
12316            res.icon = info.icon;
12317            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12318            return res;
12319        }
12320
12321        @Override
12322        protected void sortResults(List<ResolveInfo> results) {
12323            Collections.sort(results, mResolvePrioritySorter);
12324        }
12325
12326        @Override
12327        protected void dumpFilter(PrintWriter out, String prefix,
12328                PackageParser.ServiceIntentInfo filter) {
12329            out.print(prefix); out.print(
12330                    Integer.toHexString(System.identityHashCode(filter.service)));
12331                    out.print(' ');
12332                    filter.service.printComponentShortName(out);
12333                    out.print(" filter ");
12334                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12335        }
12336
12337        @Override
12338        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12339            return filter.service;
12340        }
12341
12342        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12343            PackageParser.Service service = (PackageParser.Service)label;
12344            out.print(prefix); out.print(
12345                    Integer.toHexString(System.identityHashCode(service)));
12346                    out.print(' ');
12347                    service.printComponentShortName(out);
12348            if (count > 1) {
12349                out.print(" ("); out.print(count); out.print(" filters)");
12350            }
12351            out.println();
12352        }
12353
12354//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12355//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12356//            final List<ResolveInfo> retList = Lists.newArrayList();
12357//            while (i.hasNext()) {
12358//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12359//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12360//                    retList.add(resolveInfo);
12361//                }
12362//            }
12363//            return retList;
12364//        }
12365
12366        // Keys are String (activity class name), values are Activity.
12367        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12368                = new ArrayMap<ComponentName, PackageParser.Service>();
12369        private int mFlags;
12370    }
12371
12372    private final class ProviderIntentResolver
12373            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12374        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12375                boolean defaultOnly, int userId) {
12376            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12377            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12378        }
12379
12380        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12381                int userId) {
12382            if (!sUserManager.exists(userId))
12383                return null;
12384            mFlags = flags;
12385            return super.queryIntent(intent, resolvedType,
12386                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12387                    userId);
12388        }
12389
12390        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12391                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12392            if (!sUserManager.exists(userId))
12393                return null;
12394            if (packageProviders == null) {
12395                return null;
12396            }
12397            mFlags = flags;
12398            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12399            final int N = packageProviders.size();
12400            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12401                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12402
12403            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12404            for (int i = 0; i < N; ++i) {
12405                intentFilters = packageProviders.get(i).intents;
12406                if (intentFilters != null && intentFilters.size() > 0) {
12407                    PackageParser.ProviderIntentInfo[] array =
12408                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12409                    intentFilters.toArray(array);
12410                    listCut.add(array);
12411                }
12412            }
12413            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12414        }
12415
12416        public final void addProvider(PackageParser.Provider p) {
12417            if (mProviders.containsKey(p.getComponentName())) {
12418                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12419                return;
12420            }
12421
12422            mProviders.put(p.getComponentName(), p);
12423            if (DEBUG_SHOW_INFO) {
12424                Log.v(TAG, "  "
12425                        + (p.info.nonLocalizedLabel != null
12426                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12427                Log.v(TAG, "    Class=" + p.info.name);
12428            }
12429            final int NI = p.intents.size();
12430            int j;
12431            for (j = 0; j < NI; j++) {
12432                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12433                if (DEBUG_SHOW_INFO) {
12434                    Log.v(TAG, "    IntentFilter:");
12435                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12436                }
12437                if (!intent.debugCheck()) {
12438                    Log.w(TAG, "==> For Provider " + p.info.name);
12439                }
12440                addFilter(intent);
12441            }
12442        }
12443
12444        public final void removeProvider(PackageParser.Provider p) {
12445            mProviders.remove(p.getComponentName());
12446            if (DEBUG_SHOW_INFO) {
12447                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12448                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12449                Log.v(TAG, "    Class=" + p.info.name);
12450            }
12451            final int NI = p.intents.size();
12452            int j;
12453            for (j = 0; j < NI; j++) {
12454                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12455                if (DEBUG_SHOW_INFO) {
12456                    Log.v(TAG, "    IntentFilter:");
12457                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12458                }
12459                removeFilter(intent);
12460            }
12461        }
12462
12463        @Override
12464        protected boolean allowFilterResult(
12465                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12466            ProviderInfo filterPi = filter.provider.info;
12467            for (int i = dest.size() - 1; i >= 0; i--) {
12468                ProviderInfo destPi = dest.get(i).providerInfo;
12469                if (destPi.name == filterPi.name
12470                        && destPi.packageName == filterPi.packageName) {
12471                    return false;
12472                }
12473            }
12474            return true;
12475        }
12476
12477        @Override
12478        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12479            return new PackageParser.ProviderIntentInfo[size];
12480        }
12481
12482        @Override
12483        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12484            if (!sUserManager.exists(userId))
12485                return true;
12486            PackageParser.Package p = filter.provider.owner;
12487            if (p != null) {
12488                PackageSetting ps = (PackageSetting) p.mExtras;
12489                if (ps != null) {
12490                    // System apps are never considered stopped for purposes of
12491                    // filtering, because there may be no way for the user to
12492                    // actually re-launch them.
12493                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12494                            && ps.getStopped(userId);
12495                }
12496            }
12497            return false;
12498        }
12499
12500        @Override
12501        protected boolean isPackageForFilter(String packageName,
12502                PackageParser.ProviderIntentInfo info) {
12503            return packageName.equals(info.provider.owner.packageName);
12504        }
12505
12506        @Override
12507        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12508                int match, int userId) {
12509            if (!sUserManager.exists(userId))
12510                return null;
12511            final PackageParser.ProviderIntentInfo info = filter;
12512            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12513                return null;
12514            }
12515            final PackageParser.Provider provider = info.provider;
12516            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12517            if (ps == null) {
12518                return null;
12519            }
12520            final PackageUserState userState = ps.readUserState(userId);
12521            final boolean matchVisibleToInstantApp =
12522                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12523            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12524            // throw out filters that aren't visible to instant applications
12525            if (matchVisibleToInstantApp
12526                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12527                return null;
12528            }
12529            // throw out instant application filters if we're not explicitly requesting them
12530            if (!isInstantApp && userState.instantApp) {
12531                return null;
12532            }
12533            // throw out instant application filters if updates are available; will trigger
12534            // instant application resolution
12535            if (userState.instantApp && ps.isUpdateAvailable()) {
12536                return null;
12537            }
12538            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12539                    userState, userId);
12540            if (pi == null) {
12541                return null;
12542            }
12543            final ResolveInfo res = new ResolveInfo();
12544            res.providerInfo = pi;
12545            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12546                res.filter = filter;
12547            }
12548            res.priority = info.getPriority();
12549            res.preferredOrder = provider.owner.mPreferredOrder;
12550            res.match = match;
12551            res.isDefault = info.hasDefault;
12552            res.labelRes = info.labelRes;
12553            res.nonLocalizedLabel = info.nonLocalizedLabel;
12554            res.icon = info.icon;
12555            res.system = res.providerInfo.applicationInfo.isSystemApp();
12556            return res;
12557        }
12558
12559        @Override
12560        protected void sortResults(List<ResolveInfo> results) {
12561            Collections.sort(results, mResolvePrioritySorter);
12562        }
12563
12564        @Override
12565        protected void dumpFilter(PrintWriter out, String prefix,
12566                PackageParser.ProviderIntentInfo filter) {
12567            out.print(prefix);
12568            out.print(
12569                    Integer.toHexString(System.identityHashCode(filter.provider)));
12570            out.print(' ');
12571            filter.provider.printComponentShortName(out);
12572            out.print(" filter ");
12573            out.println(Integer.toHexString(System.identityHashCode(filter)));
12574        }
12575
12576        @Override
12577        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12578            return filter.provider;
12579        }
12580
12581        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12582            PackageParser.Provider provider = (PackageParser.Provider)label;
12583            out.print(prefix); out.print(
12584                    Integer.toHexString(System.identityHashCode(provider)));
12585                    out.print(' ');
12586                    provider.printComponentShortName(out);
12587            if (count > 1) {
12588                out.print(" ("); out.print(count); out.print(" filters)");
12589            }
12590            out.println();
12591        }
12592
12593        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12594                = new ArrayMap<ComponentName, PackageParser.Provider>();
12595        private int mFlags;
12596    }
12597
12598    static final class EphemeralIntentResolver
12599            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12600        /**
12601         * The result that has the highest defined order. Ordering applies on a
12602         * per-package basis. Mapping is from package name to Pair of order and
12603         * EphemeralResolveInfo.
12604         * <p>
12605         * NOTE: This is implemented as a field variable for convenience and efficiency.
12606         * By having a field variable, we're able to track filter ordering as soon as
12607         * a non-zero order is defined. Otherwise, multiple loops across the result set
12608         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12609         * this needs to be contained entirely within {@link #filterResults}.
12610         */
12611        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12612
12613        @Override
12614        protected AuxiliaryResolveInfo[] newArray(int size) {
12615            return new AuxiliaryResolveInfo[size];
12616        }
12617
12618        @Override
12619        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12620            return true;
12621        }
12622
12623        @Override
12624        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12625                int userId) {
12626            if (!sUserManager.exists(userId)) {
12627                return null;
12628            }
12629            final String packageName = responseObj.resolveInfo.getPackageName();
12630            final Integer order = responseObj.getOrder();
12631            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12632                    mOrderResult.get(packageName);
12633            // ordering is enabled and this item's order isn't high enough
12634            if (lastOrderResult != null && lastOrderResult.first >= order) {
12635                return null;
12636            }
12637            final InstantAppResolveInfo res = responseObj.resolveInfo;
12638            if (order > 0) {
12639                // non-zero order, enable ordering
12640                mOrderResult.put(packageName, new Pair<>(order, res));
12641            }
12642            return responseObj;
12643        }
12644
12645        @Override
12646        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12647            // only do work if ordering is enabled [most of the time it won't be]
12648            if (mOrderResult.size() == 0) {
12649                return;
12650            }
12651            int resultSize = results.size();
12652            for (int i = 0; i < resultSize; i++) {
12653                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12654                final String packageName = info.getPackageName();
12655                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12656                if (savedInfo == null) {
12657                    // package doesn't having ordering
12658                    continue;
12659                }
12660                if (savedInfo.second == info) {
12661                    // circled back to the highest ordered item; remove from order list
12662                    mOrderResult.remove(packageName);
12663                    if (mOrderResult.size() == 0) {
12664                        // no more ordered items
12665                        break;
12666                    }
12667                    continue;
12668                }
12669                // item has a worse order, remove it from the result list
12670                results.remove(i);
12671                resultSize--;
12672                i--;
12673            }
12674        }
12675    }
12676
12677    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12678            new Comparator<ResolveInfo>() {
12679        public int compare(ResolveInfo r1, ResolveInfo r2) {
12680            int v1 = r1.priority;
12681            int v2 = r2.priority;
12682            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12683            if (v1 != v2) {
12684                return (v1 > v2) ? -1 : 1;
12685            }
12686            v1 = r1.preferredOrder;
12687            v2 = r2.preferredOrder;
12688            if (v1 != v2) {
12689                return (v1 > v2) ? -1 : 1;
12690            }
12691            if (r1.isDefault != r2.isDefault) {
12692                return r1.isDefault ? -1 : 1;
12693            }
12694            v1 = r1.match;
12695            v2 = r2.match;
12696            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12697            if (v1 != v2) {
12698                return (v1 > v2) ? -1 : 1;
12699            }
12700            if (r1.system != r2.system) {
12701                return r1.system ? -1 : 1;
12702            }
12703            if (r1.activityInfo != null) {
12704                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12705            }
12706            if (r1.serviceInfo != null) {
12707                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12708            }
12709            if (r1.providerInfo != null) {
12710                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12711            }
12712            return 0;
12713        }
12714    };
12715
12716    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12717            new Comparator<ProviderInfo>() {
12718        public int compare(ProviderInfo p1, ProviderInfo p2) {
12719            final int v1 = p1.initOrder;
12720            final int v2 = p2.initOrder;
12721            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12722        }
12723    };
12724
12725    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12726            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12727            final int[] userIds) {
12728        mHandler.post(new Runnable() {
12729            @Override
12730            public void run() {
12731                try {
12732                    final IActivityManager am = ActivityManager.getService();
12733                    if (am == null) return;
12734                    final int[] resolvedUserIds;
12735                    if (userIds == null) {
12736                        resolvedUserIds = am.getRunningUserIds();
12737                    } else {
12738                        resolvedUserIds = userIds;
12739                    }
12740                    for (int id : resolvedUserIds) {
12741                        final Intent intent = new Intent(action,
12742                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12743                        if (extras != null) {
12744                            intent.putExtras(extras);
12745                        }
12746                        if (targetPkg != null) {
12747                            intent.setPackage(targetPkg);
12748                        }
12749                        // Modify the UID when posting to other users
12750                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12751                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12752                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12753                            intent.putExtra(Intent.EXTRA_UID, uid);
12754                        }
12755                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12756                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12757                        if (DEBUG_BROADCASTS) {
12758                            RuntimeException here = new RuntimeException("here");
12759                            here.fillInStackTrace();
12760                            Slog.d(TAG, "Sending to user " + id + ": "
12761                                    + intent.toShortString(false, true, false, false)
12762                                    + " " + intent.getExtras(), here);
12763                        }
12764                        am.broadcastIntent(null, intent, null, finishedReceiver,
12765                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12766                                null, finishedReceiver != null, false, id);
12767                    }
12768                } catch (RemoteException ex) {
12769                }
12770            }
12771        });
12772    }
12773
12774    /**
12775     * Check if the external storage media is available. This is true if there
12776     * is a mounted external storage medium or if the external storage is
12777     * emulated.
12778     */
12779    private boolean isExternalMediaAvailable() {
12780        return mMediaMounted || Environment.isExternalStorageEmulated();
12781    }
12782
12783    @Override
12784    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12785        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
12786            return null;
12787        }
12788        // writer
12789        synchronized (mPackages) {
12790            if (!isExternalMediaAvailable()) {
12791                // If the external storage is no longer mounted at this point,
12792                // the caller may not have been able to delete all of this
12793                // packages files and can not delete any more.  Bail.
12794                return null;
12795            }
12796            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12797            if (lastPackage != null) {
12798                pkgs.remove(lastPackage);
12799            }
12800            if (pkgs.size() > 0) {
12801                return pkgs.get(0);
12802            }
12803        }
12804        return null;
12805    }
12806
12807    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12808        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12809                userId, andCode ? 1 : 0, packageName);
12810        if (mSystemReady) {
12811            msg.sendToTarget();
12812        } else {
12813            if (mPostSystemReadyMessages == null) {
12814                mPostSystemReadyMessages = new ArrayList<>();
12815            }
12816            mPostSystemReadyMessages.add(msg);
12817        }
12818    }
12819
12820    void startCleaningPackages() {
12821        // reader
12822        if (!isExternalMediaAvailable()) {
12823            return;
12824        }
12825        synchronized (mPackages) {
12826            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12827                return;
12828            }
12829        }
12830        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12831        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12832        IActivityManager am = ActivityManager.getService();
12833        if (am != null) {
12834            int dcsUid = -1;
12835            synchronized (mPackages) {
12836                if (!mDefaultContainerWhitelisted) {
12837                    mDefaultContainerWhitelisted = true;
12838                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
12839                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
12840                }
12841            }
12842            try {
12843                if (dcsUid > 0) {
12844                    am.backgroundWhitelistUid(dcsUid);
12845                }
12846                am.startService(null, intent, null, false, mContext.getOpPackageName(),
12847                        UserHandle.USER_SYSTEM);
12848            } catch (RemoteException e) {
12849            }
12850        }
12851    }
12852
12853    @Override
12854    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12855            int installFlags, String installerPackageName, int userId) {
12856        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12857
12858        final int callingUid = Binder.getCallingUid();
12859        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
12860                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12861
12862        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12863            try {
12864                if (observer != null) {
12865                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12866                }
12867            } catch (RemoteException re) {
12868            }
12869            return;
12870        }
12871
12872        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12873            installFlags |= PackageManager.INSTALL_FROM_ADB;
12874
12875        } else {
12876            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12877            // about installerPackageName.
12878
12879            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12880            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12881        }
12882
12883        UserHandle user;
12884        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12885            user = UserHandle.ALL;
12886        } else {
12887            user = new UserHandle(userId);
12888        }
12889
12890        // Only system components can circumvent runtime permissions when installing.
12891        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12892                && mContext.checkCallingOrSelfPermission(Manifest.permission
12893                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12894            throw new SecurityException("You need the "
12895                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12896                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12897        }
12898
12899        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12900                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12901            throw new IllegalArgumentException(
12902                    "New installs into ASEC containers no longer supported");
12903        }
12904
12905        final File originFile = new File(originPath);
12906        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12907
12908        final Message msg = mHandler.obtainMessage(INIT_COPY);
12909        final VerificationInfo verificationInfo = new VerificationInfo(
12910                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12911        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12912                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12913                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12914                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12915        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12916        msg.obj = params;
12917
12918        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12919                System.identityHashCode(msg.obj));
12920        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12921                System.identityHashCode(msg.obj));
12922
12923        mHandler.sendMessage(msg);
12924    }
12925
12926
12927    /**
12928     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12929     * it is acting on behalf on an enterprise or the user).
12930     *
12931     * Note that the ordering of the conditionals in this method is important. The checks we perform
12932     * are as follows, in this order:
12933     *
12934     * 1) If the install is being performed by a system app, we can trust the app to have set the
12935     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12936     *    what it is.
12937     * 2) If the install is being performed by a device or profile owner app, the install reason
12938     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12939     *    set the install reason correctly. If the app targets an older SDK version where install
12940     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12941     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12942     * 3) In all other cases, the install is being performed by a regular app that is neither part
12943     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12944     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12945     *    set to enterprise policy and if so, change it to unknown instead.
12946     */
12947    private int fixUpInstallReason(String installerPackageName, int installerUid,
12948            int installReason) {
12949        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12950                == PERMISSION_GRANTED) {
12951            // If the install is being performed by a system app, we trust that app to have set the
12952            // install reason correctly.
12953            return installReason;
12954        }
12955
12956        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12957            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12958        if (dpm != null) {
12959            ComponentName owner = null;
12960            try {
12961                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12962                if (owner == null) {
12963                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12964                }
12965            } catch (RemoteException e) {
12966            }
12967            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12968                // If the install is being performed by a device or profile owner, the install
12969                // reason should be enterprise policy.
12970                return PackageManager.INSTALL_REASON_POLICY;
12971            }
12972        }
12973
12974        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12975            // If the install is being performed by a regular app (i.e. neither system app nor
12976            // device or profile owner), we have no reason to believe that the app is acting on
12977            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12978            // change it to unknown instead.
12979            return PackageManager.INSTALL_REASON_UNKNOWN;
12980        }
12981
12982        // If the install is being performed by a regular app and the install reason was set to any
12983        // value but enterprise policy, leave the install reason unchanged.
12984        return installReason;
12985    }
12986
12987    void installStage(String packageName, File stagedDir,
12988            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12989            String installerPackageName, int installerUid, UserHandle user,
12990            Certificate[][] certificates) {
12991        if (DEBUG_EPHEMERAL) {
12992            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
12993                Slog.d(TAG, "Ephemeral install of " + packageName);
12994            }
12995        }
12996        final VerificationInfo verificationInfo = new VerificationInfo(
12997                sessionParams.originatingUri, sessionParams.referrerUri,
12998                sessionParams.originatingUid, installerUid);
12999
13000        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13001
13002        final Message msg = mHandler.obtainMessage(INIT_COPY);
13003        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13004                sessionParams.installReason);
13005        final InstallParams params = new InstallParams(origin, null, observer,
13006                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13007                verificationInfo, user, sessionParams.abiOverride,
13008                sessionParams.grantedRuntimePermissions, certificates, installReason);
13009        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13010        msg.obj = params;
13011
13012        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13013                System.identityHashCode(msg.obj));
13014        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13015                System.identityHashCode(msg.obj));
13016
13017        mHandler.sendMessage(msg);
13018    }
13019
13020    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13021            int userId) {
13022        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13023        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13024                false /*startReceiver*/, pkgSetting.appId, userId);
13025
13026        // Send a session commit broadcast
13027        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13028        info.installReason = pkgSetting.getInstallReason(userId);
13029        info.appPackageName = packageName;
13030        sendSessionCommitBroadcast(info, userId);
13031    }
13032
13033    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13034            boolean includeStopped, int appId, int... userIds) {
13035        if (ArrayUtils.isEmpty(userIds)) {
13036            return;
13037        }
13038        Bundle extras = new Bundle(1);
13039        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13040        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13041
13042        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13043                packageName, extras, 0, null, null, userIds);
13044        if (sendBootCompleted) {
13045            mHandler.post(() -> {
13046                        for (int userId : userIds) {
13047                            sendBootCompletedBroadcastToSystemApp(
13048                                    packageName, includeStopped, userId);
13049                        }
13050                    }
13051            );
13052        }
13053    }
13054
13055    /**
13056     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13057     * automatically without needing an explicit launch.
13058     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13059     */
13060    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13061            int userId) {
13062        // If user is not running, the app didn't miss any broadcast
13063        if (!mUserManagerInternal.isUserRunning(userId)) {
13064            return;
13065        }
13066        final IActivityManager am = ActivityManager.getService();
13067        try {
13068            // Deliver LOCKED_BOOT_COMPLETED first
13069            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13070                    .setPackage(packageName);
13071            if (includeStopped) {
13072                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13073            }
13074            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13075            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13076                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13077
13078            // Deliver BOOT_COMPLETED only if user is unlocked
13079            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13080                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13081                if (includeStopped) {
13082                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13083                }
13084                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13085                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13086            }
13087        } catch (RemoteException e) {
13088            throw e.rethrowFromSystemServer();
13089        }
13090    }
13091
13092    @Override
13093    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13094            int userId) {
13095        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13096        PackageSetting pkgSetting;
13097        final int callingUid = Binder.getCallingUid();
13098        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13099                true /* requireFullPermission */, true /* checkShell */,
13100                "setApplicationHiddenSetting for user " + userId);
13101
13102        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13103            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13104            return false;
13105        }
13106
13107        long callingId = Binder.clearCallingIdentity();
13108        try {
13109            boolean sendAdded = false;
13110            boolean sendRemoved = false;
13111            // writer
13112            synchronized (mPackages) {
13113                pkgSetting = mSettings.mPackages.get(packageName);
13114                if (pkgSetting == null) {
13115                    return false;
13116                }
13117                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13118                    return false;
13119                }
13120                // Do not allow "android" is being disabled
13121                if ("android".equals(packageName)) {
13122                    Slog.w(TAG, "Cannot hide package: android");
13123                    return false;
13124                }
13125                // Cannot hide static shared libs as they are considered
13126                // a part of the using app (emulating static linking). Also
13127                // static libs are installed always on internal storage.
13128                PackageParser.Package pkg = mPackages.get(packageName);
13129                if (pkg != null && pkg.staticSharedLibName != null) {
13130                    Slog.w(TAG, "Cannot hide package: " + packageName
13131                            + " providing static shared library: "
13132                            + pkg.staticSharedLibName);
13133                    return false;
13134                }
13135                // Only allow protected packages to hide themselves.
13136                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13137                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13138                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13139                    return false;
13140                }
13141
13142                if (pkgSetting.getHidden(userId) != hidden) {
13143                    pkgSetting.setHidden(hidden, userId);
13144                    mSettings.writePackageRestrictionsLPr(userId);
13145                    if (hidden) {
13146                        sendRemoved = true;
13147                    } else {
13148                        sendAdded = true;
13149                    }
13150                }
13151            }
13152            if (sendAdded) {
13153                sendPackageAddedForUser(packageName, pkgSetting, userId);
13154                return true;
13155            }
13156            if (sendRemoved) {
13157                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13158                        "hiding pkg");
13159                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13160                return true;
13161            }
13162        } finally {
13163            Binder.restoreCallingIdentity(callingId);
13164        }
13165        return false;
13166    }
13167
13168    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13169            int userId) {
13170        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13171        info.removedPackage = packageName;
13172        info.installerPackageName = pkgSetting.installerPackageName;
13173        info.removedUsers = new int[] {userId};
13174        info.broadcastUsers = new int[] {userId};
13175        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13176        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13177    }
13178
13179    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13180        if (pkgList.length > 0) {
13181            Bundle extras = new Bundle(1);
13182            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13183
13184            sendPackageBroadcast(
13185                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13186                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13187                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13188                    new int[] {userId});
13189        }
13190    }
13191
13192    /**
13193     * Returns true if application is not found or there was an error. Otherwise it returns
13194     * the hidden state of the package for the given user.
13195     */
13196    @Override
13197    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13198        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13199        final int callingUid = Binder.getCallingUid();
13200        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13201                true /* requireFullPermission */, false /* checkShell */,
13202                "getApplicationHidden for user " + userId);
13203        PackageSetting ps;
13204        long callingId = Binder.clearCallingIdentity();
13205        try {
13206            // writer
13207            synchronized (mPackages) {
13208                ps = mSettings.mPackages.get(packageName);
13209                if (ps == null) {
13210                    return true;
13211                }
13212                if (filterAppAccessLPr(ps, callingUid, userId)) {
13213                    return true;
13214                }
13215                return ps.getHidden(userId);
13216            }
13217        } finally {
13218            Binder.restoreCallingIdentity(callingId);
13219        }
13220    }
13221
13222    /**
13223     * @hide
13224     */
13225    @Override
13226    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13227            int installReason) {
13228        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13229                null);
13230        PackageSetting pkgSetting;
13231        final int callingUid = Binder.getCallingUid();
13232        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13233                true /* requireFullPermission */, true /* checkShell */,
13234                "installExistingPackage for user " + userId);
13235        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13236            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13237        }
13238
13239        long callingId = Binder.clearCallingIdentity();
13240        try {
13241            boolean installed = false;
13242            final boolean instantApp =
13243                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13244            final boolean fullApp =
13245                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13246
13247            // writer
13248            synchronized (mPackages) {
13249                pkgSetting = mSettings.mPackages.get(packageName);
13250                if (pkgSetting == null) {
13251                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13252                }
13253                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13254                    // only allow the existing package to be used if it's installed as a full
13255                    // application for at least one user
13256                    boolean installAllowed = false;
13257                    for (int checkUserId : sUserManager.getUserIds()) {
13258                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13259                        if (installAllowed) {
13260                            break;
13261                        }
13262                    }
13263                    if (!installAllowed) {
13264                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13265                    }
13266                }
13267                if (!pkgSetting.getInstalled(userId)) {
13268                    pkgSetting.setInstalled(true, userId);
13269                    pkgSetting.setHidden(false, userId);
13270                    pkgSetting.setInstallReason(installReason, userId);
13271                    mSettings.writePackageRestrictionsLPr(userId);
13272                    mSettings.writeKernelMappingLPr(pkgSetting);
13273                    installed = true;
13274                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13275                    // upgrade app from instant to full; we don't allow app downgrade
13276                    installed = true;
13277                }
13278                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13279            }
13280
13281            if (installed) {
13282                if (pkgSetting.pkg != null) {
13283                    synchronized (mInstallLock) {
13284                        // We don't need to freeze for a brand new install
13285                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13286                    }
13287                }
13288                sendPackageAddedForUser(packageName, pkgSetting, userId);
13289                synchronized (mPackages) {
13290                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13291                }
13292            }
13293        } finally {
13294            Binder.restoreCallingIdentity(callingId);
13295        }
13296
13297        return PackageManager.INSTALL_SUCCEEDED;
13298    }
13299
13300    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13301            boolean instantApp, boolean fullApp) {
13302        // no state specified; do nothing
13303        if (!instantApp && !fullApp) {
13304            return;
13305        }
13306        if (userId != UserHandle.USER_ALL) {
13307            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13308                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13309            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13310                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13311            }
13312        } else {
13313            for (int currentUserId : sUserManager.getUserIds()) {
13314                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13315                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13316                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13317                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13318                }
13319            }
13320        }
13321    }
13322
13323    boolean isUserRestricted(int userId, String restrictionKey) {
13324        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13325        if (restrictions.getBoolean(restrictionKey, false)) {
13326            Log.w(TAG, "User is restricted: " + restrictionKey);
13327            return true;
13328        }
13329        return false;
13330    }
13331
13332    @Override
13333    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13334            int userId) {
13335        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13336        final int callingUid = Binder.getCallingUid();
13337        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13338                true /* requireFullPermission */, true /* checkShell */,
13339                "setPackagesSuspended for user " + userId);
13340
13341        if (ArrayUtils.isEmpty(packageNames)) {
13342            return packageNames;
13343        }
13344
13345        // List of package names for whom the suspended state has changed.
13346        List<String> changedPackages = new ArrayList<>(packageNames.length);
13347        // List of package names for whom the suspended state is not set as requested in this
13348        // method.
13349        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13350        long callingId = Binder.clearCallingIdentity();
13351        try {
13352            for (int i = 0; i < packageNames.length; i++) {
13353                String packageName = packageNames[i];
13354                boolean changed = false;
13355                final int appId;
13356                synchronized (mPackages) {
13357                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13358                    if (pkgSetting == null
13359                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13360                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13361                                + "\". Skipping suspending/un-suspending.");
13362                        unactionedPackages.add(packageName);
13363                        continue;
13364                    }
13365                    appId = pkgSetting.appId;
13366                    if (pkgSetting.getSuspended(userId) != suspended) {
13367                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13368                            unactionedPackages.add(packageName);
13369                            continue;
13370                        }
13371                        pkgSetting.setSuspended(suspended, userId);
13372                        mSettings.writePackageRestrictionsLPr(userId);
13373                        changed = true;
13374                        changedPackages.add(packageName);
13375                    }
13376                }
13377
13378                if (changed && suspended) {
13379                    killApplication(packageName, UserHandle.getUid(userId, appId),
13380                            "suspending package");
13381                }
13382            }
13383        } finally {
13384            Binder.restoreCallingIdentity(callingId);
13385        }
13386
13387        if (!changedPackages.isEmpty()) {
13388            sendPackagesSuspendedForUser(changedPackages.toArray(
13389                    new String[changedPackages.size()]), userId, suspended);
13390        }
13391
13392        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13393    }
13394
13395    @Override
13396    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13397        final int callingUid = Binder.getCallingUid();
13398        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13399                true /* requireFullPermission */, false /* checkShell */,
13400                "isPackageSuspendedForUser for user " + userId);
13401        synchronized (mPackages) {
13402            final PackageSetting ps = mSettings.mPackages.get(packageName);
13403            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13404                throw new IllegalArgumentException("Unknown target package: " + packageName);
13405            }
13406            return ps.getSuspended(userId);
13407        }
13408    }
13409
13410    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13411        if (isPackageDeviceAdmin(packageName, userId)) {
13412            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13413                    + "\": has an active device admin");
13414            return false;
13415        }
13416
13417        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13418        if (packageName.equals(activeLauncherPackageName)) {
13419            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13420                    + "\": contains the active launcher");
13421            return false;
13422        }
13423
13424        if (packageName.equals(mRequiredInstallerPackage)) {
13425            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13426                    + "\": required for package installation");
13427            return false;
13428        }
13429
13430        if (packageName.equals(mRequiredUninstallerPackage)) {
13431            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13432                    + "\": required for package uninstallation");
13433            return false;
13434        }
13435
13436        if (packageName.equals(mRequiredVerifierPackage)) {
13437            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13438                    + "\": required for package verification");
13439            return false;
13440        }
13441
13442        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13443            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13444                    + "\": is the default dialer");
13445            return false;
13446        }
13447
13448        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13449            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13450                    + "\": protected package");
13451            return false;
13452        }
13453
13454        // Cannot suspend static shared libs as they are considered
13455        // a part of the using app (emulating static linking). Also
13456        // static libs are installed always on internal storage.
13457        PackageParser.Package pkg = mPackages.get(packageName);
13458        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13459            Slog.w(TAG, "Cannot suspend package: " + packageName
13460                    + " providing static shared library: "
13461                    + pkg.staticSharedLibName);
13462            return false;
13463        }
13464
13465        return true;
13466    }
13467
13468    private String getActiveLauncherPackageName(int userId) {
13469        Intent intent = new Intent(Intent.ACTION_MAIN);
13470        intent.addCategory(Intent.CATEGORY_HOME);
13471        ResolveInfo resolveInfo = resolveIntent(
13472                intent,
13473                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13474                PackageManager.MATCH_DEFAULT_ONLY,
13475                userId);
13476
13477        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13478    }
13479
13480    private String getDefaultDialerPackageName(int userId) {
13481        synchronized (mPackages) {
13482            return mSettings.getDefaultDialerPackageNameLPw(userId);
13483        }
13484    }
13485
13486    @Override
13487    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13488        mContext.enforceCallingOrSelfPermission(
13489                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13490                "Only package verification agents can verify applications");
13491
13492        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13493        final PackageVerificationResponse response = new PackageVerificationResponse(
13494                verificationCode, Binder.getCallingUid());
13495        msg.arg1 = id;
13496        msg.obj = response;
13497        mHandler.sendMessage(msg);
13498    }
13499
13500    @Override
13501    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13502            long millisecondsToDelay) {
13503        mContext.enforceCallingOrSelfPermission(
13504                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13505                "Only package verification agents can extend verification timeouts");
13506
13507        final PackageVerificationState state = mPendingVerification.get(id);
13508        final PackageVerificationResponse response = new PackageVerificationResponse(
13509                verificationCodeAtTimeout, Binder.getCallingUid());
13510
13511        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13512            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13513        }
13514        if (millisecondsToDelay < 0) {
13515            millisecondsToDelay = 0;
13516        }
13517        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13518                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13519            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13520        }
13521
13522        if ((state != null) && !state.timeoutExtended()) {
13523            state.extendTimeout();
13524
13525            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13526            msg.arg1 = id;
13527            msg.obj = response;
13528            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13529        }
13530    }
13531
13532    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13533            int verificationCode, UserHandle user) {
13534        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13535        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13536        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13537        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13538        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13539
13540        mContext.sendBroadcastAsUser(intent, user,
13541                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13542    }
13543
13544    private ComponentName matchComponentForVerifier(String packageName,
13545            List<ResolveInfo> receivers) {
13546        ActivityInfo targetReceiver = null;
13547
13548        final int NR = receivers.size();
13549        for (int i = 0; i < NR; i++) {
13550            final ResolveInfo info = receivers.get(i);
13551            if (info.activityInfo == null) {
13552                continue;
13553            }
13554
13555            if (packageName.equals(info.activityInfo.packageName)) {
13556                targetReceiver = info.activityInfo;
13557                break;
13558            }
13559        }
13560
13561        if (targetReceiver == null) {
13562            return null;
13563        }
13564
13565        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13566    }
13567
13568    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13569            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13570        if (pkgInfo.verifiers.length == 0) {
13571            return null;
13572        }
13573
13574        final int N = pkgInfo.verifiers.length;
13575        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13576        for (int i = 0; i < N; i++) {
13577            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13578
13579            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13580                    receivers);
13581            if (comp == null) {
13582                continue;
13583            }
13584
13585            final int verifierUid = getUidForVerifier(verifierInfo);
13586            if (verifierUid == -1) {
13587                continue;
13588            }
13589
13590            if (DEBUG_VERIFY) {
13591                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13592                        + " with the correct signature");
13593            }
13594            sufficientVerifiers.add(comp);
13595            verificationState.addSufficientVerifier(verifierUid);
13596        }
13597
13598        return sufficientVerifiers;
13599    }
13600
13601    private int getUidForVerifier(VerifierInfo verifierInfo) {
13602        synchronized (mPackages) {
13603            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13604            if (pkg == null) {
13605                return -1;
13606            } else if (pkg.mSignatures.length != 1) {
13607                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13608                        + " has more than one signature; ignoring");
13609                return -1;
13610            }
13611
13612            /*
13613             * If the public key of the package's signature does not match
13614             * our expected public key, then this is a different package and
13615             * we should skip.
13616             */
13617
13618            final byte[] expectedPublicKey;
13619            try {
13620                final Signature verifierSig = pkg.mSignatures[0];
13621                final PublicKey publicKey = verifierSig.getPublicKey();
13622                expectedPublicKey = publicKey.getEncoded();
13623            } catch (CertificateException e) {
13624                return -1;
13625            }
13626
13627            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13628
13629            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13630                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13631                        + " does not have the expected public key; ignoring");
13632                return -1;
13633            }
13634
13635            return pkg.applicationInfo.uid;
13636        }
13637    }
13638
13639    @Override
13640    public void finishPackageInstall(int token, boolean didLaunch) {
13641        enforceSystemOrRoot("Only the system is allowed to finish installs");
13642
13643        if (DEBUG_INSTALL) {
13644            Slog.v(TAG, "BM finishing package install for " + token);
13645        }
13646        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13647
13648        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13649        mHandler.sendMessage(msg);
13650    }
13651
13652    /**
13653     * Get the verification agent timeout.  Used for both the APK verifier and the
13654     * intent filter verifier.
13655     *
13656     * @return verification timeout in milliseconds
13657     */
13658    private long getVerificationTimeout() {
13659        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13660                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13661                DEFAULT_VERIFICATION_TIMEOUT);
13662    }
13663
13664    /**
13665     * Get the default verification agent response code.
13666     *
13667     * @return default verification response code
13668     */
13669    private int getDefaultVerificationResponse(UserHandle user) {
13670        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13671            return PackageManager.VERIFICATION_REJECT;
13672        }
13673        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13674                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13675                DEFAULT_VERIFICATION_RESPONSE);
13676    }
13677
13678    /**
13679     * Check whether or not package verification has been enabled.
13680     *
13681     * @return true if verification should be performed
13682     */
13683    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13684        if (!DEFAULT_VERIFY_ENABLE) {
13685            return false;
13686        }
13687
13688        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13689
13690        // Check if installing from ADB
13691        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13692            // Do not run verification in a test harness environment
13693            if (ActivityManager.isRunningInTestHarness()) {
13694                return false;
13695            }
13696            if (ensureVerifyAppsEnabled) {
13697                return true;
13698            }
13699            // Check if the developer does not want package verification for ADB installs
13700            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13701                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13702                return false;
13703            }
13704        } else {
13705            // only when not installed from ADB, skip verification for instant apps when
13706            // the installer and verifier are the same.
13707            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13708                if (mInstantAppInstallerActivity != null
13709                        && mInstantAppInstallerActivity.packageName.equals(
13710                                mRequiredVerifierPackage)) {
13711                    try {
13712                        mContext.getSystemService(AppOpsManager.class)
13713                                .checkPackage(installerUid, mRequiredVerifierPackage);
13714                        if (DEBUG_VERIFY) {
13715                            Slog.i(TAG, "disable verification for instant app");
13716                        }
13717                        return false;
13718                    } catch (SecurityException ignore) { }
13719                }
13720            }
13721        }
13722
13723        if (ensureVerifyAppsEnabled) {
13724            return true;
13725        }
13726
13727        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13728                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13729    }
13730
13731    @Override
13732    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13733            throws RemoteException {
13734        mContext.enforceCallingOrSelfPermission(
13735                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13736                "Only intentfilter verification agents can verify applications");
13737
13738        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13739        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13740                Binder.getCallingUid(), verificationCode, failedDomains);
13741        msg.arg1 = id;
13742        msg.obj = response;
13743        mHandler.sendMessage(msg);
13744    }
13745
13746    @Override
13747    public int getIntentVerificationStatus(String packageName, int userId) {
13748        final int callingUid = Binder.getCallingUid();
13749        if (UserHandle.getUserId(callingUid) != userId) {
13750            mContext.enforceCallingOrSelfPermission(
13751                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13752                    "getIntentVerificationStatus" + userId);
13753        }
13754        if (getInstantAppPackageName(callingUid) != null) {
13755            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13756        }
13757        synchronized (mPackages) {
13758            final PackageSetting ps = mSettings.mPackages.get(packageName);
13759            if (ps == null
13760                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13761                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13762            }
13763            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13764        }
13765    }
13766
13767    @Override
13768    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13769        mContext.enforceCallingOrSelfPermission(
13770                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13771
13772        boolean result = false;
13773        synchronized (mPackages) {
13774            final PackageSetting ps = mSettings.mPackages.get(packageName);
13775            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13776                return false;
13777            }
13778            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13779        }
13780        if (result) {
13781            scheduleWritePackageRestrictionsLocked(userId);
13782        }
13783        return result;
13784    }
13785
13786    @Override
13787    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13788            String packageName) {
13789        final int callingUid = Binder.getCallingUid();
13790        if (getInstantAppPackageName(callingUid) != null) {
13791            return ParceledListSlice.emptyList();
13792        }
13793        synchronized (mPackages) {
13794            final PackageSetting ps = mSettings.mPackages.get(packageName);
13795            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13796                return ParceledListSlice.emptyList();
13797            }
13798            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13799        }
13800    }
13801
13802    @Override
13803    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13804        if (TextUtils.isEmpty(packageName)) {
13805            return ParceledListSlice.emptyList();
13806        }
13807        final int callingUid = Binder.getCallingUid();
13808        final int callingUserId = UserHandle.getUserId(callingUid);
13809        synchronized (mPackages) {
13810            PackageParser.Package pkg = mPackages.get(packageName);
13811            if (pkg == null || pkg.activities == null) {
13812                return ParceledListSlice.emptyList();
13813            }
13814            if (pkg.mExtras == null) {
13815                return ParceledListSlice.emptyList();
13816            }
13817            final PackageSetting ps = (PackageSetting) pkg.mExtras;
13818            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
13819                return ParceledListSlice.emptyList();
13820            }
13821            final int count = pkg.activities.size();
13822            ArrayList<IntentFilter> result = new ArrayList<>();
13823            for (int n=0; n<count; n++) {
13824                PackageParser.Activity activity = pkg.activities.get(n);
13825                if (activity.intents != null && activity.intents.size() > 0) {
13826                    result.addAll(activity.intents);
13827                }
13828            }
13829            return new ParceledListSlice<>(result);
13830        }
13831    }
13832
13833    @Override
13834    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13835        mContext.enforceCallingOrSelfPermission(
13836                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13837        if (UserHandle.getCallingUserId() != userId) {
13838            mContext.enforceCallingOrSelfPermission(
13839                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13840        }
13841
13842        synchronized (mPackages) {
13843            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13844            if (packageName != null) {
13845                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
13846                        packageName, userId);
13847            }
13848            return result;
13849        }
13850    }
13851
13852    @Override
13853    public String getDefaultBrowserPackageName(int userId) {
13854        if (UserHandle.getCallingUserId() != userId) {
13855            mContext.enforceCallingOrSelfPermission(
13856                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13857        }
13858        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13859            return null;
13860        }
13861        synchronized (mPackages) {
13862            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13863        }
13864    }
13865
13866    /**
13867     * Get the "allow unknown sources" setting.
13868     *
13869     * @return the current "allow unknown sources" setting
13870     */
13871    private int getUnknownSourcesSettings() {
13872        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13873                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13874                -1);
13875    }
13876
13877    @Override
13878    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13879        final int callingUid = Binder.getCallingUid();
13880        if (getInstantAppPackageName(callingUid) != null) {
13881            return;
13882        }
13883        // writer
13884        synchronized (mPackages) {
13885            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13886            if (targetPackageSetting == null
13887                    || filterAppAccessLPr(
13888                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
13889                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13890            }
13891
13892            PackageSetting installerPackageSetting;
13893            if (installerPackageName != null) {
13894                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13895                if (installerPackageSetting == null) {
13896                    throw new IllegalArgumentException("Unknown installer package: "
13897                            + installerPackageName);
13898                }
13899            } else {
13900                installerPackageSetting = null;
13901            }
13902
13903            Signature[] callerSignature;
13904            Object obj = mSettings.getUserIdLPr(callingUid);
13905            if (obj != null) {
13906                if (obj instanceof SharedUserSetting) {
13907                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13908                } else if (obj instanceof PackageSetting) {
13909                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13910                } else {
13911                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
13912                }
13913            } else {
13914                throw new SecurityException("Unknown calling UID: " + callingUid);
13915            }
13916
13917            // Verify: can't set installerPackageName to a package that is
13918            // not signed with the same cert as the caller.
13919            if (installerPackageSetting != null) {
13920                if (compareSignatures(callerSignature,
13921                        installerPackageSetting.signatures.mSignatures)
13922                        != PackageManager.SIGNATURE_MATCH) {
13923                    throw new SecurityException(
13924                            "Caller does not have same cert as new installer package "
13925                            + installerPackageName);
13926                }
13927            }
13928
13929            // Verify: if target already has an installer package, it must
13930            // be signed with the same cert as the caller.
13931            if (targetPackageSetting.installerPackageName != null) {
13932                PackageSetting setting = mSettings.mPackages.get(
13933                        targetPackageSetting.installerPackageName);
13934                // If the currently set package isn't valid, then it's always
13935                // okay to change it.
13936                if (setting != null) {
13937                    if (compareSignatures(callerSignature,
13938                            setting.signatures.mSignatures)
13939                            != PackageManager.SIGNATURE_MATCH) {
13940                        throw new SecurityException(
13941                                "Caller does not have same cert as old installer package "
13942                                + targetPackageSetting.installerPackageName);
13943                    }
13944                }
13945            }
13946
13947            // Okay!
13948            targetPackageSetting.installerPackageName = installerPackageName;
13949            if (installerPackageName != null) {
13950                mSettings.mInstallerPackages.add(installerPackageName);
13951            }
13952            scheduleWriteSettingsLocked();
13953        }
13954    }
13955
13956    @Override
13957    public void setApplicationCategoryHint(String packageName, int categoryHint,
13958            String callerPackageName) {
13959        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13960            throw new SecurityException("Instant applications don't have access to this method");
13961        }
13962        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13963                callerPackageName);
13964        synchronized (mPackages) {
13965            PackageSetting ps = mSettings.mPackages.get(packageName);
13966            if (ps == null) {
13967                throw new IllegalArgumentException("Unknown target package " + packageName);
13968            }
13969            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13970                throw new IllegalArgumentException("Unknown target package " + packageName);
13971            }
13972            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13973                throw new IllegalArgumentException("Calling package " + callerPackageName
13974                        + " is not installer for " + packageName);
13975            }
13976
13977            if (ps.categoryHint != categoryHint) {
13978                ps.categoryHint = categoryHint;
13979                scheduleWriteSettingsLocked();
13980            }
13981        }
13982    }
13983
13984    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13985        // Queue up an async operation since the package installation may take a little while.
13986        mHandler.post(new Runnable() {
13987            public void run() {
13988                mHandler.removeCallbacks(this);
13989                 // Result object to be returned
13990                PackageInstalledInfo res = new PackageInstalledInfo();
13991                res.setReturnCode(currentStatus);
13992                res.uid = -1;
13993                res.pkg = null;
13994                res.removedInfo = null;
13995                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13996                    args.doPreInstall(res.returnCode);
13997                    synchronized (mInstallLock) {
13998                        installPackageTracedLI(args, res);
13999                    }
14000                    args.doPostInstall(res.returnCode, res.uid);
14001                }
14002
14003                // A restore should be performed at this point if (a) the install
14004                // succeeded, (b) the operation is not an update, and (c) the new
14005                // package has not opted out of backup participation.
14006                final boolean update = res.removedInfo != null
14007                        && res.removedInfo.removedPackage != null;
14008                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14009                boolean doRestore = !update
14010                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14011
14012                // Set up the post-install work request bookkeeping.  This will be used
14013                // and cleaned up by the post-install event handling regardless of whether
14014                // there's a restore pass performed.  Token values are >= 1.
14015                int token;
14016                if (mNextInstallToken < 0) mNextInstallToken = 1;
14017                token = mNextInstallToken++;
14018
14019                PostInstallData data = new PostInstallData(args, res);
14020                mRunningInstalls.put(token, data);
14021                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14022
14023                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14024                    // Pass responsibility to the Backup Manager.  It will perform a
14025                    // restore if appropriate, then pass responsibility back to the
14026                    // Package Manager to run the post-install observer callbacks
14027                    // and broadcasts.
14028                    IBackupManager bm = IBackupManager.Stub.asInterface(
14029                            ServiceManager.getService(Context.BACKUP_SERVICE));
14030                    if (bm != null) {
14031                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14032                                + " to BM for possible restore");
14033                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14034                        try {
14035                            // TODO: http://b/22388012
14036                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14037                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14038                            } else {
14039                                doRestore = false;
14040                            }
14041                        } catch (RemoteException e) {
14042                            // can't happen; the backup manager is local
14043                        } catch (Exception e) {
14044                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14045                            doRestore = false;
14046                        }
14047                    } else {
14048                        Slog.e(TAG, "Backup Manager not found!");
14049                        doRestore = false;
14050                    }
14051                }
14052
14053                if (!doRestore) {
14054                    // No restore possible, or the Backup Manager was mysteriously not
14055                    // available -- just fire the post-install work request directly.
14056                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14057
14058                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14059
14060                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14061                    mHandler.sendMessage(msg);
14062                }
14063            }
14064        });
14065    }
14066
14067    /**
14068     * Callback from PackageSettings whenever an app is first transitioned out of the
14069     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14070     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14071     * here whether the app is the target of an ongoing install, and only send the
14072     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14073     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14074     * handling.
14075     */
14076    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14077        // Serialize this with the rest of the install-process message chain.  In the
14078        // restore-at-install case, this Runnable will necessarily run before the
14079        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14080        // are coherent.  In the non-restore case, the app has already completed install
14081        // and been launched through some other means, so it is not in a problematic
14082        // state for observers to see the FIRST_LAUNCH signal.
14083        mHandler.post(new Runnable() {
14084            @Override
14085            public void run() {
14086                for (int i = 0; i < mRunningInstalls.size(); i++) {
14087                    final PostInstallData data = mRunningInstalls.valueAt(i);
14088                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14089                        continue;
14090                    }
14091                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14092                        // right package; but is it for the right user?
14093                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14094                            if (userId == data.res.newUsers[uIndex]) {
14095                                if (DEBUG_BACKUP) {
14096                                    Slog.i(TAG, "Package " + pkgName
14097                                            + " being restored so deferring FIRST_LAUNCH");
14098                                }
14099                                return;
14100                            }
14101                        }
14102                    }
14103                }
14104                // didn't find it, so not being restored
14105                if (DEBUG_BACKUP) {
14106                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14107                }
14108                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14109            }
14110        });
14111    }
14112
14113    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14114        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14115                installerPkg, null, userIds);
14116    }
14117
14118    private abstract class HandlerParams {
14119        private static final int MAX_RETRIES = 4;
14120
14121        /**
14122         * Number of times startCopy() has been attempted and had a non-fatal
14123         * error.
14124         */
14125        private int mRetries = 0;
14126
14127        /** User handle for the user requesting the information or installation. */
14128        private final UserHandle mUser;
14129        String traceMethod;
14130        int traceCookie;
14131
14132        HandlerParams(UserHandle user) {
14133            mUser = user;
14134        }
14135
14136        UserHandle getUser() {
14137            return mUser;
14138        }
14139
14140        HandlerParams setTraceMethod(String traceMethod) {
14141            this.traceMethod = traceMethod;
14142            return this;
14143        }
14144
14145        HandlerParams setTraceCookie(int traceCookie) {
14146            this.traceCookie = traceCookie;
14147            return this;
14148        }
14149
14150        final boolean startCopy() {
14151            boolean res;
14152            try {
14153                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14154
14155                if (++mRetries > MAX_RETRIES) {
14156                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14157                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14158                    handleServiceError();
14159                    return false;
14160                } else {
14161                    handleStartCopy();
14162                    res = true;
14163                }
14164            } catch (RemoteException e) {
14165                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14166                mHandler.sendEmptyMessage(MCS_RECONNECT);
14167                res = false;
14168            }
14169            handleReturnCode();
14170            return res;
14171        }
14172
14173        final void serviceError() {
14174            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14175            handleServiceError();
14176            handleReturnCode();
14177        }
14178
14179        abstract void handleStartCopy() throws RemoteException;
14180        abstract void handleServiceError();
14181        abstract void handleReturnCode();
14182    }
14183
14184    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14185        for (File path : paths) {
14186            try {
14187                mcs.clearDirectory(path.getAbsolutePath());
14188            } catch (RemoteException e) {
14189            }
14190        }
14191    }
14192
14193    static class OriginInfo {
14194        /**
14195         * Location where install is coming from, before it has been
14196         * copied/renamed into place. This could be a single monolithic APK
14197         * file, or a cluster directory. This location may be untrusted.
14198         */
14199        final File file;
14200
14201        /**
14202         * Flag indicating that {@link #file} or {@link #cid} has already been
14203         * staged, meaning downstream users don't need to defensively copy the
14204         * contents.
14205         */
14206        final boolean staged;
14207
14208        /**
14209         * Flag indicating that {@link #file} or {@link #cid} is an already
14210         * installed app that is being moved.
14211         */
14212        final boolean existing;
14213
14214        final String resolvedPath;
14215        final File resolvedFile;
14216
14217        static OriginInfo fromNothing() {
14218            return new OriginInfo(null, false, false);
14219        }
14220
14221        static OriginInfo fromUntrustedFile(File file) {
14222            return new OriginInfo(file, false, false);
14223        }
14224
14225        static OriginInfo fromExistingFile(File file) {
14226            return new OriginInfo(file, false, true);
14227        }
14228
14229        static OriginInfo fromStagedFile(File file) {
14230            return new OriginInfo(file, true, false);
14231        }
14232
14233        private OriginInfo(File file, boolean staged, boolean existing) {
14234            this.file = file;
14235            this.staged = staged;
14236            this.existing = existing;
14237
14238            if (file != null) {
14239                resolvedPath = file.getAbsolutePath();
14240                resolvedFile = file;
14241            } else {
14242                resolvedPath = null;
14243                resolvedFile = null;
14244            }
14245        }
14246    }
14247
14248    static class MoveInfo {
14249        final int moveId;
14250        final String fromUuid;
14251        final String toUuid;
14252        final String packageName;
14253        final String dataAppName;
14254        final int appId;
14255        final String seinfo;
14256        final int targetSdkVersion;
14257
14258        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14259                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14260            this.moveId = moveId;
14261            this.fromUuid = fromUuid;
14262            this.toUuid = toUuid;
14263            this.packageName = packageName;
14264            this.dataAppName = dataAppName;
14265            this.appId = appId;
14266            this.seinfo = seinfo;
14267            this.targetSdkVersion = targetSdkVersion;
14268        }
14269    }
14270
14271    static class VerificationInfo {
14272        /** A constant used to indicate that a uid value is not present. */
14273        public static final int NO_UID = -1;
14274
14275        /** URI referencing where the package was downloaded from. */
14276        final Uri originatingUri;
14277
14278        /** HTTP referrer URI associated with the originatingURI. */
14279        final Uri referrer;
14280
14281        /** UID of the application that the install request originated from. */
14282        final int originatingUid;
14283
14284        /** UID of application requesting the install */
14285        final int installerUid;
14286
14287        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14288            this.originatingUri = originatingUri;
14289            this.referrer = referrer;
14290            this.originatingUid = originatingUid;
14291            this.installerUid = installerUid;
14292        }
14293    }
14294
14295    class InstallParams extends HandlerParams {
14296        final OriginInfo origin;
14297        final MoveInfo move;
14298        final IPackageInstallObserver2 observer;
14299        int installFlags;
14300        final String installerPackageName;
14301        final String volumeUuid;
14302        private InstallArgs mArgs;
14303        private int mRet;
14304        final String packageAbiOverride;
14305        final String[] grantedRuntimePermissions;
14306        final VerificationInfo verificationInfo;
14307        final Certificate[][] certificates;
14308        final int installReason;
14309
14310        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14311                int installFlags, String installerPackageName, String volumeUuid,
14312                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14313                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14314            super(user);
14315            this.origin = origin;
14316            this.move = move;
14317            this.observer = observer;
14318            this.installFlags = installFlags;
14319            this.installerPackageName = installerPackageName;
14320            this.volumeUuid = volumeUuid;
14321            this.verificationInfo = verificationInfo;
14322            this.packageAbiOverride = packageAbiOverride;
14323            this.grantedRuntimePermissions = grantedPermissions;
14324            this.certificates = certificates;
14325            this.installReason = installReason;
14326        }
14327
14328        @Override
14329        public String toString() {
14330            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14331                    + " file=" + origin.file + "}";
14332        }
14333
14334        private int installLocationPolicy(PackageInfoLite pkgLite) {
14335            String packageName = pkgLite.packageName;
14336            int installLocation = pkgLite.installLocation;
14337            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14338            // reader
14339            synchronized (mPackages) {
14340                // Currently installed package which the new package is attempting to replace or
14341                // null if no such package is installed.
14342                PackageParser.Package installedPkg = mPackages.get(packageName);
14343                // Package which currently owns the data which the new package will own if installed.
14344                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14345                // will be null whereas dataOwnerPkg will contain information about the package
14346                // which was uninstalled while keeping its data.
14347                PackageParser.Package dataOwnerPkg = installedPkg;
14348                if (dataOwnerPkg  == null) {
14349                    PackageSetting ps = mSettings.mPackages.get(packageName);
14350                    if (ps != null) {
14351                        dataOwnerPkg = ps.pkg;
14352                    }
14353                }
14354
14355                if (dataOwnerPkg != null) {
14356                    // If installed, the package will get access to data left on the device by its
14357                    // predecessor. As a security measure, this is permited only if this is not a
14358                    // version downgrade or if the predecessor package is marked as debuggable and
14359                    // a downgrade is explicitly requested.
14360                    //
14361                    // On debuggable platform builds, downgrades are permitted even for
14362                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14363                    // not offer security guarantees and thus it's OK to disable some security
14364                    // mechanisms to make debugging/testing easier on those builds. However, even on
14365                    // debuggable builds downgrades of packages are permitted only if requested via
14366                    // installFlags. This is because we aim to keep the behavior of debuggable
14367                    // platform builds as close as possible to the behavior of non-debuggable
14368                    // platform builds.
14369                    final boolean downgradeRequested =
14370                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14371                    final boolean packageDebuggable =
14372                                (dataOwnerPkg.applicationInfo.flags
14373                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14374                    final boolean downgradePermitted =
14375                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14376                    if (!downgradePermitted) {
14377                        try {
14378                            checkDowngrade(dataOwnerPkg, pkgLite);
14379                        } catch (PackageManagerException e) {
14380                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14381                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14382                        }
14383                    }
14384                }
14385
14386                if (installedPkg != null) {
14387                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14388                        // Check for updated system application.
14389                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14390                            if (onSd) {
14391                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14392                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14393                            }
14394                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14395                        } else {
14396                            if (onSd) {
14397                                // Install flag overrides everything.
14398                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14399                            }
14400                            // If current upgrade specifies particular preference
14401                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14402                                // Application explicitly specified internal.
14403                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14404                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14405                                // App explictly prefers external. Let policy decide
14406                            } else {
14407                                // Prefer previous location
14408                                if (isExternal(installedPkg)) {
14409                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14410                                }
14411                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14412                            }
14413                        }
14414                    } else {
14415                        // Invalid install. Return error code
14416                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14417                    }
14418                }
14419            }
14420            // All the special cases have been taken care of.
14421            // Return result based on recommended install location.
14422            if (onSd) {
14423                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14424            }
14425            return pkgLite.recommendedInstallLocation;
14426        }
14427
14428        /*
14429         * Invoke remote method to get package information and install
14430         * location values. Override install location based on default
14431         * policy if needed and then create install arguments based
14432         * on the install location.
14433         */
14434        public void handleStartCopy() throws RemoteException {
14435            int ret = PackageManager.INSTALL_SUCCEEDED;
14436
14437            // If we're already staged, we've firmly committed to an install location
14438            if (origin.staged) {
14439                if (origin.file != null) {
14440                    installFlags |= PackageManager.INSTALL_INTERNAL;
14441                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14442                } else {
14443                    throw new IllegalStateException("Invalid stage location");
14444                }
14445            }
14446
14447            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14448            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14449            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14450            PackageInfoLite pkgLite = null;
14451
14452            if (onInt && onSd) {
14453                // Check if both bits are set.
14454                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14455                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14456            } else if (onSd && ephemeral) {
14457                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14458                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14459            } else {
14460                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14461                        packageAbiOverride);
14462
14463                if (DEBUG_EPHEMERAL && ephemeral) {
14464                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14465                }
14466
14467                /*
14468                 * If we have too little free space, try to free cache
14469                 * before giving up.
14470                 */
14471                if (!origin.staged && pkgLite.recommendedInstallLocation
14472                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14473                    // TODO: focus freeing disk space on the target device
14474                    final StorageManager storage = StorageManager.from(mContext);
14475                    final long lowThreshold = storage.getStorageLowBytes(
14476                            Environment.getDataDirectory());
14477
14478                    final long sizeBytes = mContainerService.calculateInstalledSize(
14479                            origin.resolvedPath, packageAbiOverride);
14480
14481                    try {
14482                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14483                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14484                                installFlags, packageAbiOverride);
14485                    } catch (InstallerException e) {
14486                        Slog.w(TAG, "Failed to free cache", e);
14487                    }
14488
14489                    /*
14490                     * The cache free must have deleted the file we
14491                     * downloaded to install.
14492                     *
14493                     * TODO: fix the "freeCache" call to not delete
14494                     *       the file we care about.
14495                     */
14496                    if (pkgLite.recommendedInstallLocation
14497                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14498                        pkgLite.recommendedInstallLocation
14499                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14500                    }
14501                }
14502            }
14503
14504            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14505                int loc = pkgLite.recommendedInstallLocation;
14506                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14507                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14508                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14509                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14510                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14511                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14512                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14513                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14514                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14515                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14516                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14517                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14518                } else {
14519                    // Override with defaults if needed.
14520                    loc = installLocationPolicy(pkgLite);
14521                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14522                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14523                    } else if (!onSd && !onInt) {
14524                        // Override install location with flags
14525                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14526                            // Set the flag to install on external media.
14527                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14528                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14529                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14530                            if (DEBUG_EPHEMERAL) {
14531                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14532                            }
14533                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14534                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14535                                    |PackageManager.INSTALL_INTERNAL);
14536                        } else {
14537                            // Make sure the flag for installing on external
14538                            // media is unset
14539                            installFlags |= PackageManager.INSTALL_INTERNAL;
14540                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14541                        }
14542                    }
14543                }
14544            }
14545
14546            final InstallArgs args = createInstallArgs(this);
14547            mArgs = args;
14548
14549            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14550                // TODO: http://b/22976637
14551                // Apps installed for "all" users use the device owner to verify the app
14552                UserHandle verifierUser = getUser();
14553                if (verifierUser == UserHandle.ALL) {
14554                    verifierUser = UserHandle.SYSTEM;
14555                }
14556
14557                /*
14558                 * Determine if we have any installed package verifiers. If we
14559                 * do, then we'll defer to them to verify the packages.
14560                 */
14561                final int requiredUid = mRequiredVerifierPackage == null ? -1
14562                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14563                                verifierUser.getIdentifier());
14564                final int installerUid =
14565                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14566                if (!origin.existing && requiredUid != -1
14567                        && isVerificationEnabled(
14568                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14569                    final Intent verification = new Intent(
14570                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14571                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14572                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14573                            PACKAGE_MIME_TYPE);
14574                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14575
14576                    // Query all live verifiers based on current user state
14577                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14578                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14579                            false /*allowDynamicSplits*/);
14580
14581                    if (DEBUG_VERIFY) {
14582                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14583                                + verification.toString() + " with " + pkgLite.verifiers.length
14584                                + " optional verifiers");
14585                    }
14586
14587                    final int verificationId = mPendingVerificationToken++;
14588
14589                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14590
14591                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14592                            installerPackageName);
14593
14594                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14595                            installFlags);
14596
14597                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14598                            pkgLite.packageName);
14599
14600                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14601                            pkgLite.versionCode);
14602
14603                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
14604                            pkgLite.getLongVersionCode());
14605
14606                    if (verificationInfo != null) {
14607                        if (verificationInfo.originatingUri != null) {
14608                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14609                                    verificationInfo.originatingUri);
14610                        }
14611                        if (verificationInfo.referrer != null) {
14612                            verification.putExtra(Intent.EXTRA_REFERRER,
14613                                    verificationInfo.referrer);
14614                        }
14615                        if (verificationInfo.originatingUid >= 0) {
14616                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14617                                    verificationInfo.originatingUid);
14618                        }
14619                        if (verificationInfo.installerUid >= 0) {
14620                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14621                                    verificationInfo.installerUid);
14622                        }
14623                    }
14624
14625                    final PackageVerificationState verificationState = new PackageVerificationState(
14626                            requiredUid, args);
14627
14628                    mPendingVerification.append(verificationId, verificationState);
14629
14630                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14631                            receivers, verificationState);
14632
14633                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14634                    final long idleDuration = getVerificationTimeout();
14635
14636                    /*
14637                     * If any sufficient verifiers were listed in the package
14638                     * manifest, attempt to ask them.
14639                     */
14640                    if (sufficientVerifiers != null) {
14641                        final int N = sufficientVerifiers.size();
14642                        if (N == 0) {
14643                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14644                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14645                        } else {
14646                            for (int i = 0; i < N; i++) {
14647                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14648                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14649                                        verifierComponent.getPackageName(), idleDuration,
14650                                        verifierUser.getIdentifier(), false, "package verifier");
14651
14652                                final Intent sufficientIntent = new Intent(verification);
14653                                sufficientIntent.setComponent(verifierComponent);
14654                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14655                            }
14656                        }
14657                    }
14658
14659                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14660                            mRequiredVerifierPackage, receivers);
14661                    if (ret == PackageManager.INSTALL_SUCCEEDED
14662                            && mRequiredVerifierPackage != null) {
14663                        Trace.asyncTraceBegin(
14664                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14665                        /*
14666                         * Send the intent to the required verification agent,
14667                         * but only start the verification timeout after the
14668                         * target BroadcastReceivers have run.
14669                         */
14670                        verification.setComponent(requiredVerifierComponent);
14671                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14672                                mRequiredVerifierPackage, idleDuration,
14673                                verifierUser.getIdentifier(), false, "package verifier");
14674                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14675                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14676                                new BroadcastReceiver() {
14677                                    @Override
14678                                    public void onReceive(Context context, Intent intent) {
14679                                        final Message msg = mHandler
14680                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14681                                        msg.arg1 = verificationId;
14682                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14683                                    }
14684                                }, null, 0, null, null);
14685
14686                        /*
14687                         * We don't want the copy to proceed until verification
14688                         * succeeds, so null out this field.
14689                         */
14690                        mArgs = null;
14691                    }
14692                } else {
14693                    /*
14694                     * No package verification is enabled, so immediately start
14695                     * the remote call to initiate copy using temporary file.
14696                     */
14697                    ret = args.copyApk(mContainerService, true);
14698                }
14699            }
14700
14701            mRet = ret;
14702        }
14703
14704        @Override
14705        void handleReturnCode() {
14706            // If mArgs is null, then MCS couldn't be reached. When it
14707            // reconnects, it will try again to install. At that point, this
14708            // will succeed.
14709            if (mArgs != null) {
14710                processPendingInstall(mArgs, mRet);
14711            }
14712        }
14713
14714        @Override
14715        void handleServiceError() {
14716            mArgs = createInstallArgs(this);
14717            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14718        }
14719    }
14720
14721    private InstallArgs createInstallArgs(InstallParams params) {
14722        if (params.move != null) {
14723            return new MoveInstallArgs(params);
14724        } else {
14725            return new FileInstallArgs(params);
14726        }
14727    }
14728
14729    /**
14730     * Create args that describe an existing installed package. Typically used
14731     * when cleaning up old installs, or used as a move source.
14732     */
14733    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14734            String resourcePath, String[] instructionSets) {
14735        return new FileInstallArgs(codePath, resourcePath, instructionSets);
14736    }
14737
14738    static abstract class InstallArgs {
14739        /** @see InstallParams#origin */
14740        final OriginInfo origin;
14741        /** @see InstallParams#move */
14742        final MoveInfo move;
14743
14744        final IPackageInstallObserver2 observer;
14745        // Always refers to PackageManager flags only
14746        final int installFlags;
14747        final String installerPackageName;
14748        final String volumeUuid;
14749        final UserHandle user;
14750        final String abiOverride;
14751        final String[] installGrantPermissions;
14752        /** If non-null, drop an async trace when the install completes */
14753        final String traceMethod;
14754        final int traceCookie;
14755        final Certificate[][] certificates;
14756        final int installReason;
14757
14758        // The list of instruction sets supported by this app. This is currently
14759        // only used during the rmdex() phase to clean up resources. We can get rid of this
14760        // if we move dex files under the common app path.
14761        /* nullable */ String[] instructionSets;
14762
14763        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14764                int installFlags, String installerPackageName, String volumeUuid,
14765                UserHandle user, String[] instructionSets,
14766                String abiOverride, String[] installGrantPermissions,
14767                String traceMethod, int traceCookie, Certificate[][] certificates,
14768                int installReason) {
14769            this.origin = origin;
14770            this.move = move;
14771            this.installFlags = installFlags;
14772            this.observer = observer;
14773            this.installerPackageName = installerPackageName;
14774            this.volumeUuid = volumeUuid;
14775            this.user = user;
14776            this.instructionSets = instructionSets;
14777            this.abiOverride = abiOverride;
14778            this.installGrantPermissions = installGrantPermissions;
14779            this.traceMethod = traceMethod;
14780            this.traceCookie = traceCookie;
14781            this.certificates = certificates;
14782            this.installReason = installReason;
14783        }
14784
14785        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14786        abstract int doPreInstall(int status);
14787
14788        /**
14789         * Rename package into final resting place. All paths on the given
14790         * scanned package should be updated to reflect the rename.
14791         */
14792        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14793        abstract int doPostInstall(int status, int uid);
14794
14795        /** @see PackageSettingBase#codePathString */
14796        abstract String getCodePath();
14797        /** @see PackageSettingBase#resourcePathString */
14798        abstract String getResourcePath();
14799
14800        // Need installer lock especially for dex file removal.
14801        abstract void cleanUpResourcesLI();
14802        abstract boolean doPostDeleteLI(boolean delete);
14803
14804        /**
14805         * Called before the source arguments are copied. This is used mostly
14806         * for MoveParams when it needs to read the source file to put it in the
14807         * destination.
14808         */
14809        int doPreCopy() {
14810            return PackageManager.INSTALL_SUCCEEDED;
14811        }
14812
14813        /**
14814         * Called after the source arguments are copied. This is used mostly for
14815         * MoveParams when it needs to read the source file to put it in the
14816         * destination.
14817         */
14818        int doPostCopy(int uid) {
14819            return PackageManager.INSTALL_SUCCEEDED;
14820        }
14821
14822        protected boolean isFwdLocked() {
14823            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14824        }
14825
14826        protected boolean isExternalAsec() {
14827            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14828        }
14829
14830        protected boolean isEphemeral() {
14831            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14832        }
14833
14834        UserHandle getUser() {
14835            return user;
14836        }
14837    }
14838
14839    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14840        if (!allCodePaths.isEmpty()) {
14841            if (instructionSets == null) {
14842                throw new IllegalStateException("instructionSet == null");
14843            }
14844            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14845            for (String codePath : allCodePaths) {
14846                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14847                    try {
14848                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14849                    } catch (InstallerException ignored) {
14850                    }
14851                }
14852            }
14853        }
14854    }
14855
14856    /**
14857     * Logic to handle installation of non-ASEC applications, including copying
14858     * and renaming logic.
14859     */
14860    class FileInstallArgs extends InstallArgs {
14861        private File codeFile;
14862        private File resourceFile;
14863
14864        // Example topology:
14865        // /data/app/com.example/base.apk
14866        // /data/app/com.example/split_foo.apk
14867        // /data/app/com.example/lib/arm/libfoo.so
14868        // /data/app/com.example/lib/arm64/libfoo.so
14869        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14870
14871        /** New install */
14872        FileInstallArgs(InstallParams params) {
14873            super(params.origin, params.move, params.observer, params.installFlags,
14874                    params.installerPackageName, params.volumeUuid,
14875                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14876                    params.grantedRuntimePermissions,
14877                    params.traceMethod, params.traceCookie, params.certificates,
14878                    params.installReason);
14879            if (isFwdLocked()) {
14880                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14881            }
14882        }
14883
14884        /** Existing install */
14885        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14886            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14887                    null, null, null, 0, null /*certificates*/,
14888                    PackageManager.INSTALL_REASON_UNKNOWN);
14889            this.codeFile = (codePath != null) ? new File(codePath) : null;
14890            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14891        }
14892
14893        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14894            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14895            try {
14896                return doCopyApk(imcs, temp);
14897            } finally {
14898                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14899            }
14900        }
14901
14902        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14903            if (origin.staged) {
14904                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14905                codeFile = origin.file;
14906                resourceFile = origin.file;
14907                return PackageManager.INSTALL_SUCCEEDED;
14908            }
14909
14910            try {
14911                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14912                final File tempDir =
14913                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14914                codeFile = tempDir;
14915                resourceFile = tempDir;
14916            } catch (IOException e) {
14917                Slog.w(TAG, "Failed to create copy file: " + e);
14918                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14919            }
14920
14921            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14922                @Override
14923                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14924                    if (!FileUtils.isValidExtFilename(name)) {
14925                        throw new IllegalArgumentException("Invalid filename: " + name);
14926                    }
14927                    try {
14928                        final File file = new File(codeFile, name);
14929                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14930                                O_RDWR | O_CREAT, 0644);
14931                        Os.chmod(file.getAbsolutePath(), 0644);
14932                        return new ParcelFileDescriptor(fd);
14933                    } catch (ErrnoException e) {
14934                        throw new RemoteException("Failed to open: " + e.getMessage());
14935                    }
14936                }
14937            };
14938
14939            int ret = PackageManager.INSTALL_SUCCEEDED;
14940            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14941            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14942                Slog.e(TAG, "Failed to copy package");
14943                return ret;
14944            }
14945
14946            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14947            NativeLibraryHelper.Handle handle = null;
14948            try {
14949                handle = NativeLibraryHelper.Handle.create(codeFile);
14950                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14951                        abiOverride);
14952            } catch (IOException e) {
14953                Slog.e(TAG, "Copying native libraries failed", e);
14954                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14955            } finally {
14956                IoUtils.closeQuietly(handle);
14957            }
14958
14959            return ret;
14960        }
14961
14962        int doPreInstall(int status) {
14963            if (status != PackageManager.INSTALL_SUCCEEDED) {
14964                cleanUp();
14965            }
14966            return status;
14967        }
14968
14969        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14970            if (status != PackageManager.INSTALL_SUCCEEDED) {
14971                cleanUp();
14972                return false;
14973            }
14974
14975            final File targetDir = codeFile.getParentFile();
14976            final File beforeCodeFile = codeFile;
14977            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14978
14979            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14980            try {
14981                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14982            } catch (ErrnoException e) {
14983                Slog.w(TAG, "Failed to rename", e);
14984                return false;
14985            }
14986
14987            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14988                Slog.w(TAG, "Failed to restorecon");
14989                return false;
14990            }
14991
14992            // Reflect the rename internally
14993            codeFile = afterCodeFile;
14994            resourceFile = afterCodeFile;
14995
14996            // Reflect the rename in scanned details
14997            try {
14998                pkg.setCodePath(afterCodeFile.getCanonicalPath());
14999            } catch (IOException e) {
15000                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15001                return false;
15002            }
15003            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15004                    afterCodeFile, pkg.baseCodePath));
15005            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15006                    afterCodeFile, pkg.splitCodePaths));
15007
15008            // Reflect the rename in app info
15009            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15010            pkg.setApplicationInfoCodePath(pkg.codePath);
15011            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15012            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15013            pkg.setApplicationInfoResourcePath(pkg.codePath);
15014            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15015            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15016
15017            return true;
15018        }
15019
15020        int doPostInstall(int status, int uid) {
15021            if (status != PackageManager.INSTALL_SUCCEEDED) {
15022                cleanUp();
15023            }
15024            return status;
15025        }
15026
15027        @Override
15028        String getCodePath() {
15029            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15030        }
15031
15032        @Override
15033        String getResourcePath() {
15034            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15035        }
15036
15037        private boolean cleanUp() {
15038            if (codeFile == null || !codeFile.exists()) {
15039                return false;
15040            }
15041
15042            removeCodePathLI(codeFile);
15043
15044            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15045                resourceFile.delete();
15046            }
15047
15048            return true;
15049        }
15050
15051        void cleanUpResourcesLI() {
15052            // Try enumerating all code paths before deleting
15053            List<String> allCodePaths = Collections.EMPTY_LIST;
15054            if (codeFile != null && codeFile.exists()) {
15055                try {
15056                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15057                    allCodePaths = pkg.getAllCodePaths();
15058                } catch (PackageParserException e) {
15059                    // Ignored; we tried our best
15060                }
15061            }
15062
15063            cleanUp();
15064            removeDexFiles(allCodePaths, instructionSets);
15065        }
15066
15067        boolean doPostDeleteLI(boolean delete) {
15068            // XXX err, shouldn't we respect the delete flag?
15069            cleanUpResourcesLI();
15070            return true;
15071        }
15072    }
15073
15074    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15075            PackageManagerException {
15076        if (copyRet < 0) {
15077            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15078                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15079                throw new PackageManagerException(copyRet, message);
15080            }
15081        }
15082    }
15083
15084    /**
15085     * Extract the StorageManagerService "container ID" from the full code path of an
15086     * .apk.
15087     */
15088    static String cidFromCodePath(String fullCodePath) {
15089        int eidx = fullCodePath.lastIndexOf("/");
15090        String subStr1 = fullCodePath.substring(0, eidx);
15091        int sidx = subStr1.lastIndexOf("/");
15092        return subStr1.substring(sidx+1, eidx);
15093    }
15094
15095    /**
15096     * Logic to handle movement of existing installed applications.
15097     */
15098    class MoveInstallArgs extends InstallArgs {
15099        private File codeFile;
15100        private File resourceFile;
15101
15102        /** New install */
15103        MoveInstallArgs(InstallParams params) {
15104            super(params.origin, params.move, params.observer, params.installFlags,
15105                    params.installerPackageName, params.volumeUuid,
15106                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15107                    params.grantedRuntimePermissions,
15108                    params.traceMethod, params.traceCookie, params.certificates,
15109                    params.installReason);
15110        }
15111
15112        int copyApk(IMediaContainerService imcs, boolean temp) {
15113            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15114                    + move.fromUuid + " to " + move.toUuid);
15115            synchronized (mInstaller) {
15116                try {
15117                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15118                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15119                } catch (InstallerException e) {
15120                    Slog.w(TAG, "Failed to move app", e);
15121                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15122                }
15123            }
15124
15125            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15126            resourceFile = codeFile;
15127            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15128
15129            return PackageManager.INSTALL_SUCCEEDED;
15130        }
15131
15132        int doPreInstall(int status) {
15133            if (status != PackageManager.INSTALL_SUCCEEDED) {
15134                cleanUp(move.toUuid);
15135            }
15136            return status;
15137        }
15138
15139        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15140            if (status != PackageManager.INSTALL_SUCCEEDED) {
15141                cleanUp(move.toUuid);
15142                return false;
15143            }
15144
15145            // Reflect the move in app info
15146            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15147            pkg.setApplicationInfoCodePath(pkg.codePath);
15148            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15149            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15150            pkg.setApplicationInfoResourcePath(pkg.codePath);
15151            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15152            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15153
15154            return true;
15155        }
15156
15157        int doPostInstall(int status, int uid) {
15158            if (status == PackageManager.INSTALL_SUCCEEDED) {
15159                cleanUp(move.fromUuid);
15160            } else {
15161                cleanUp(move.toUuid);
15162            }
15163            return status;
15164        }
15165
15166        @Override
15167        String getCodePath() {
15168            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15169        }
15170
15171        @Override
15172        String getResourcePath() {
15173            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15174        }
15175
15176        private boolean cleanUp(String volumeUuid) {
15177            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15178                    move.dataAppName);
15179            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15180            final int[] userIds = sUserManager.getUserIds();
15181            synchronized (mInstallLock) {
15182                // Clean up both app data and code
15183                // All package moves are frozen until finished
15184                for (int userId : userIds) {
15185                    try {
15186                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15187                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15188                    } catch (InstallerException e) {
15189                        Slog.w(TAG, String.valueOf(e));
15190                    }
15191                }
15192                removeCodePathLI(codeFile);
15193            }
15194            return true;
15195        }
15196
15197        void cleanUpResourcesLI() {
15198            throw new UnsupportedOperationException();
15199        }
15200
15201        boolean doPostDeleteLI(boolean delete) {
15202            throw new UnsupportedOperationException();
15203        }
15204    }
15205
15206    static String getAsecPackageName(String packageCid) {
15207        int idx = packageCid.lastIndexOf("-");
15208        if (idx == -1) {
15209            return packageCid;
15210        }
15211        return packageCid.substring(0, idx);
15212    }
15213
15214    // Utility method used to create code paths based on package name and available index.
15215    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15216        String idxStr = "";
15217        int idx = 1;
15218        // Fall back to default value of idx=1 if prefix is not
15219        // part of oldCodePath
15220        if (oldCodePath != null) {
15221            String subStr = oldCodePath;
15222            // Drop the suffix right away
15223            if (suffix != null && subStr.endsWith(suffix)) {
15224                subStr = subStr.substring(0, subStr.length() - suffix.length());
15225            }
15226            // If oldCodePath already contains prefix find out the
15227            // ending index to either increment or decrement.
15228            int sidx = subStr.lastIndexOf(prefix);
15229            if (sidx != -1) {
15230                subStr = subStr.substring(sidx + prefix.length());
15231                if (subStr != null) {
15232                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15233                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15234                    }
15235                    try {
15236                        idx = Integer.parseInt(subStr);
15237                        if (idx <= 1) {
15238                            idx++;
15239                        } else {
15240                            idx--;
15241                        }
15242                    } catch(NumberFormatException e) {
15243                    }
15244                }
15245            }
15246        }
15247        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15248        return prefix + idxStr;
15249    }
15250
15251    private File getNextCodePath(File targetDir, String packageName) {
15252        File result;
15253        SecureRandom random = new SecureRandom();
15254        byte[] bytes = new byte[16];
15255        do {
15256            random.nextBytes(bytes);
15257            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15258            result = new File(targetDir, packageName + "-" + suffix);
15259        } while (result.exists());
15260        return result;
15261    }
15262
15263    // Utility method that returns the relative package path with respect
15264    // to the installation directory. Like say for /data/data/com.test-1.apk
15265    // string com.test-1 is returned.
15266    static String deriveCodePathName(String codePath) {
15267        if (codePath == null) {
15268            return null;
15269        }
15270        final File codeFile = new File(codePath);
15271        final String name = codeFile.getName();
15272        if (codeFile.isDirectory()) {
15273            return name;
15274        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15275            final int lastDot = name.lastIndexOf('.');
15276            return name.substring(0, lastDot);
15277        } else {
15278            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15279            return null;
15280        }
15281    }
15282
15283    static class PackageInstalledInfo {
15284        String name;
15285        int uid;
15286        // The set of users that originally had this package installed.
15287        int[] origUsers;
15288        // The set of users that now have this package installed.
15289        int[] newUsers;
15290        PackageParser.Package pkg;
15291        int returnCode;
15292        String returnMsg;
15293        String installerPackageName;
15294        PackageRemovedInfo removedInfo;
15295        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15296
15297        public void setError(int code, String msg) {
15298            setReturnCode(code);
15299            setReturnMessage(msg);
15300            Slog.w(TAG, msg);
15301        }
15302
15303        public void setError(String msg, PackageParserException e) {
15304            setReturnCode(e.error);
15305            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15306            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15307            for (int i = 0; i < childCount; i++) {
15308                addedChildPackages.valueAt(i).setError(msg, e);
15309            }
15310            Slog.w(TAG, msg, e);
15311        }
15312
15313        public void setError(String msg, PackageManagerException e) {
15314            returnCode = e.error;
15315            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15316            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15317            for (int i = 0; i < childCount; i++) {
15318                addedChildPackages.valueAt(i).setError(msg, e);
15319            }
15320            Slog.w(TAG, msg, e);
15321        }
15322
15323        public void setReturnCode(int returnCode) {
15324            this.returnCode = returnCode;
15325            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15326            for (int i = 0; i < childCount; i++) {
15327                addedChildPackages.valueAt(i).returnCode = returnCode;
15328            }
15329        }
15330
15331        private void setReturnMessage(String returnMsg) {
15332            this.returnMsg = returnMsg;
15333            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15334            for (int i = 0; i < childCount; i++) {
15335                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15336            }
15337        }
15338
15339        // In some error cases we want to convey more info back to the observer
15340        String origPackage;
15341        String origPermission;
15342    }
15343
15344    /*
15345     * Install a non-existing package.
15346     */
15347    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15348            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15349            String volumeUuid, PackageInstalledInfo res, int installReason) {
15350        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15351
15352        // Remember this for later, in case we need to rollback this install
15353        String pkgName = pkg.packageName;
15354
15355        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15356
15357        synchronized(mPackages) {
15358            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15359            if (renamedPackage != null) {
15360                // A package with the same name is already installed, though
15361                // it has been renamed to an older name.  The package we
15362                // are trying to install should be installed as an update to
15363                // the existing one, but that has not been requested, so bail.
15364                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15365                        + " without first uninstalling package running as "
15366                        + renamedPackage);
15367                return;
15368            }
15369            if (mPackages.containsKey(pkgName)) {
15370                // Don't allow installation over an existing package with the same name.
15371                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15372                        + " without first uninstalling.");
15373                return;
15374            }
15375        }
15376
15377        try {
15378            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15379                    System.currentTimeMillis(), user);
15380
15381            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15382
15383            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15384                prepareAppDataAfterInstallLIF(newPackage);
15385
15386            } else {
15387                // Remove package from internal structures, but keep around any
15388                // data that might have already existed
15389                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15390                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15391            }
15392        } catch (PackageManagerException e) {
15393            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15394        }
15395
15396        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15397    }
15398
15399    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15400        try (DigestInputStream digestStream =
15401                new DigestInputStream(new FileInputStream(file), digest)) {
15402            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15403        }
15404    }
15405
15406    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15407            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15408            PackageInstalledInfo res, int installReason) {
15409        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15410
15411        final PackageParser.Package oldPackage;
15412        final PackageSetting ps;
15413        final String pkgName = pkg.packageName;
15414        final int[] allUsers;
15415        final int[] installedUsers;
15416
15417        synchronized(mPackages) {
15418            oldPackage = mPackages.get(pkgName);
15419            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15420
15421            // don't allow upgrade to target a release SDK from a pre-release SDK
15422            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15423                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15424            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15425                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15426            if (oldTargetsPreRelease
15427                    && !newTargetsPreRelease
15428                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15429                Slog.w(TAG, "Can't install package targeting released sdk");
15430                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15431                return;
15432            }
15433
15434            ps = mSettings.mPackages.get(pkgName);
15435
15436            // verify signatures are valid
15437            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15438            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15439                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15440                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15441                            "New package not signed by keys specified by upgrade-keysets: "
15442                                    + pkgName);
15443                    return;
15444                }
15445            } else {
15446                // default to original signature matching
15447                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15448                        != PackageManager.SIGNATURE_MATCH) {
15449                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15450                            "New package has a different signature: " + pkgName);
15451                    return;
15452                }
15453            }
15454
15455            // don't allow a system upgrade unless the upgrade hash matches
15456            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15457                byte[] digestBytes = null;
15458                try {
15459                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15460                    updateDigest(digest, new File(pkg.baseCodePath));
15461                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15462                        for (String path : pkg.splitCodePaths) {
15463                            updateDigest(digest, new File(path));
15464                        }
15465                    }
15466                    digestBytes = digest.digest();
15467                } catch (NoSuchAlgorithmException | IOException e) {
15468                    res.setError(INSTALL_FAILED_INVALID_APK,
15469                            "Could not compute hash: " + pkgName);
15470                    return;
15471                }
15472                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15473                    res.setError(INSTALL_FAILED_INVALID_APK,
15474                            "New package fails restrict-update check: " + pkgName);
15475                    return;
15476                }
15477                // retain upgrade restriction
15478                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15479            }
15480
15481            // Check for shared user id changes
15482            String invalidPackageName =
15483                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15484            if (invalidPackageName != null) {
15485                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15486                        "Package " + invalidPackageName + " tried to change user "
15487                                + oldPackage.mSharedUserId);
15488                return;
15489            }
15490
15491            // In case of rollback, remember per-user/profile install state
15492            allUsers = sUserManager.getUserIds();
15493            installedUsers = ps.queryInstalledUsers(allUsers, true);
15494
15495            // don't allow an upgrade from full to ephemeral
15496            if (isInstantApp) {
15497                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15498                    for (int currentUser : allUsers) {
15499                        if (!ps.getInstantApp(currentUser)) {
15500                            // can't downgrade from full to instant
15501                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15502                                    + " for user: " + currentUser);
15503                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15504                            return;
15505                        }
15506                    }
15507                } else if (!ps.getInstantApp(user.getIdentifier())) {
15508                    // can't downgrade from full to instant
15509                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15510                            + " for user: " + user.getIdentifier());
15511                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15512                    return;
15513                }
15514            }
15515        }
15516
15517        // Update what is removed
15518        res.removedInfo = new PackageRemovedInfo(this);
15519        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15520        res.removedInfo.removedPackage = oldPackage.packageName;
15521        res.removedInfo.installerPackageName = ps.installerPackageName;
15522        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15523        res.removedInfo.isUpdate = true;
15524        res.removedInfo.origUsers = installedUsers;
15525        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15526        for (int i = 0; i < installedUsers.length; i++) {
15527            final int userId = installedUsers[i];
15528            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15529        }
15530
15531        final int childCount = (oldPackage.childPackages != null)
15532                ? oldPackage.childPackages.size() : 0;
15533        for (int i = 0; i < childCount; i++) {
15534            boolean childPackageUpdated = false;
15535            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15536            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15537            if (res.addedChildPackages != null) {
15538                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15539                if (childRes != null) {
15540                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15541                    childRes.removedInfo.removedPackage = childPkg.packageName;
15542                    if (childPs != null) {
15543                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15544                    }
15545                    childRes.removedInfo.isUpdate = true;
15546                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15547                    childPackageUpdated = true;
15548                }
15549            }
15550            if (!childPackageUpdated) {
15551                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15552                childRemovedRes.removedPackage = childPkg.packageName;
15553                if (childPs != null) {
15554                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15555                }
15556                childRemovedRes.isUpdate = false;
15557                childRemovedRes.dataRemoved = true;
15558                synchronized (mPackages) {
15559                    if (childPs != null) {
15560                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15561                    }
15562                }
15563                if (res.removedInfo.removedChildPackages == null) {
15564                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15565                }
15566                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15567            }
15568        }
15569
15570        boolean sysPkg = (isSystemApp(oldPackage));
15571        if (sysPkg) {
15572            // Set the system/privileged/oem flags as needed
15573            final boolean privileged =
15574                    (oldPackage.applicationInfo.privateFlags
15575                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15576            final boolean oem =
15577                    (oldPackage.applicationInfo.privateFlags
15578                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15579            final @ParseFlags int systemParseFlags = parseFlags;
15580            final @ScanFlags int systemScanFlags = scanFlags
15581                    | SCAN_AS_SYSTEM
15582                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
15583                    | (oem ? SCAN_AS_OEM : 0);
15584
15585            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
15586                    user, allUsers, installerPackageName, res, installReason);
15587        } else {
15588            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
15589                    user, allUsers, installerPackageName, res, installReason);
15590        }
15591    }
15592
15593    @Override
15594    public List<String> getPreviousCodePaths(String packageName) {
15595        final int callingUid = Binder.getCallingUid();
15596        final List<String> result = new ArrayList<>();
15597        if (getInstantAppPackageName(callingUid) != null) {
15598            return result;
15599        }
15600        final PackageSetting ps = mSettings.mPackages.get(packageName);
15601        if (ps != null
15602                && ps.oldCodePaths != null
15603                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15604            result.addAll(ps.oldCodePaths);
15605        }
15606        return result;
15607    }
15608
15609    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15610            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15611            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
15612            String installerPackageName, PackageInstalledInfo res, int installReason) {
15613        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15614                + deletedPackage);
15615
15616        String pkgName = deletedPackage.packageName;
15617        boolean deletedPkg = true;
15618        boolean addedPkg = false;
15619        boolean updatedSettings = false;
15620        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15621        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15622                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15623
15624        final long origUpdateTime = (pkg.mExtras != null)
15625                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15626
15627        // First delete the existing package while retaining the data directory
15628        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15629                res.removedInfo, true, pkg)) {
15630            // If the existing package wasn't successfully deleted
15631            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15632            deletedPkg = false;
15633        } else {
15634            // Successfully deleted the old package; proceed with replace.
15635
15636            // If deleted package lived in a container, give users a chance to
15637            // relinquish resources before killing.
15638            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15639                if (DEBUG_INSTALL) {
15640                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15641                }
15642                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15643                final ArrayList<String> pkgList = new ArrayList<String>(1);
15644                pkgList.add(deletedPackage.applicationInfo.packageName);
15645                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15646            }
15647
15648            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15649                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15650            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15651
15652            try {
15653                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
15654                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15655                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15656                        installReason);
15657
15658                // Update the in-memory copy of the previous code paths.
15659                PackageSetting ps = mSettings.mPackages.get(pkgName);
15660                if (!killApp) {
15661                    if (ps.oldCodePaths == null) {
15662                        ps.oldCodePaths = new ArraySet<>();
15663                    }
15664                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15665                    if (deletedPackage.splitCodePaths != null) {
15666                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15667                    }
15668                } else {
15669                    ps.oldCodePaths = null;
15670                }
15671                if (ps.childPackageNames != null) {
15672                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15673                        final String childPkgName = ps.childPackageNames.get(i);
15674                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15675                        childPs.oldCodePaths = ps.oldCodePaths;
15676                    }
15677                }
15678                // set instant app status, but, only if it's explicitly specified
15679                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15680                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15681                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15682                prepareAppDataAfterInstallLIF(newPackage);
15683                addedPkg = true;
15684                mDexManager.notifyPackageUpdated(newPackage.packageName,
15685                        newPackage.baseCodePath, newPackage.splitCodePaths);
15686            } catch (PackageManagerException e) {
15687                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15688            }
15689        }
15690
15691        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15692            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15693
15694            // Revert all internal state mutations and added folders for the failed install
15695            if (addedPkg) {
15696                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15697                        res.removedInfo, true, null);
15698            }
15699
15700            // Restore the old package
15701            if (deletedPkg) {
15702                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15703                File restoreFile = new File(deletedPackage.codePath);
15704                // Parse old package
15705                boolean oldExternal = isExternal(deletedPackage);
15706                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15707                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15708                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15709                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15710                try {
15711                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15712                            null);
15713                } catch (PackageManagerException e) {
15714                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15715                            + e.getMessage());
15716                    return;
15717                }
15718
15719                synchronized (mPackages) {
15720                    // Ensure the installer package name up to date
15721                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15722
15723                    // Update permissions for restored package
15724                    mPermissionManager.updatePermissions(
15725                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15726                            mPermissionCallback);
15727
15728                    mSettings.writeLPr();
15729                }
15730
15731                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15732            }
15733        } else {
15734            synchronized (mPackages) {
15735                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15736                if (ps != null) {
15737                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15738                    if (res.removedInfo.removedChildPackages != null) {
15739                        final int childCount = res.removedInfo.removedChildPackages.size();
15740                        // Iterate in reverse as we may modify the collection
15741                        for (int i = childCount - 1; i >= 0; i--) {
15742                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15743                            if (res.addedChildPackages.containsKey(childPackageName)) {
15744                                res.removedInfo.removedChildPackages.removeAt(i);
15745                            } else {
15746                                PackageRemovedInfo childInfo = res.removedInfo
15747                                        .removedChildPackages.valueAt(i);
15748                                childInfo.removedForAllUsers = mPackages.get(
15749                                        childInfo.removedPackage) == null;
15750                            }
15751                        }
15752                    }
15753                }
15754            }
15755        }
15756    }
15757
15758    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15759            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15760            final @ScanFlags int scanFlags, UserHandle user,
15761            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15762            int installReason) {
15763        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15764                + ", old=" + deletedPackage);
15765
15766        final boolean disabledSystem;
15767
15768        // Remove existing system package
15769        removePackageLI(deletedPackage, true);
15770
15771        synchronized (mPackages) {
15772            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15773        }
15774        if (!disabledSystem) {
15775            // We didn't need to disable the .apk as a current system package,
15776            // which means we are replacing another update that is already
15777            // installed.  We need to make sure to delete the older one's .apk.
15778            res.removedInfo.args = createInstallArgsForExisting(0,
15779                    deletedPackage.applicationInfo.getCodePath(),
15780                    deletedPackage.applicationInfo.getResourcePath(),
15781                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15782        } else {
15783            res.removedInfo.args = null;
15784        }
15785
15786        // Successfully disabled the old package. Now proceed with re-installation
15787        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15788                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15789        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15790
15791        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15792        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15793                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15794
15795        PackageParser.Package newPackage = null;
15796        try {
15797            // Add the package to the internal data structures
15798            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
15799
15800            // Set the update and install times
15801            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15802            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15803                    System.currentTimeMillis());
15804
15805            // Update the package dynamic state if succeeded
15806            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15807                // Now that the install succeeded make sure we remove data
15808                // directories for any child package the update removed.
15809                final int deletedChildCount = (deletedPackage.childPackages != null)
15810                        ? deletedPackage.childPackages.size() : 0;
15811                final int newChildCount = (newPackage.childPackages != null)
15812                        ? newPackage.childPackages.size() : 0;
15813                for (int i = 0; i < deletedChildCount; i++) {
15814                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15815                    boolean childPackageDeleted = true;
15816                    for (int j = 0; j < newChildCount; j++) {
15817                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15818                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15819                            childPackageDeleted = false;
15820                            break;
15821                        }
15822                    }
15823                    if (childPackageDeleted) {
15824                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15825                                deletedChildPkg.packageName);
15826                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15827                            PackageRemovedInfo removedChildRes = res.removedInfo
15828                                    .removedChildPackages.get(deletedChildPkg.packageName);
15829                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15830                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15831                        }
15832                    }
15833                }
15834
15835                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15836                        installReason);
15837                prepareAppDataAfterInstallLIF(newPackage);
15838
15839                mDexManager.notifyPackageUpdated(newPackage.packageName,
15840                            newPackage.baseCodePath, newPackage.splitCodePaths);
15841            }
15842        } catch (PackageManagerException e) {
15843            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15844            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15845        }
15846
15847        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15848            // Re installation failed. Restore old information
15849            // Remove new pkg information
15850            if (newPackage != null) {
15851                removeInstalledPackageLI(newPackage, true);
15852            }
15853            // Add back the old system package
15854            try {
15855                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15856            } catch (PackageManagerException e) {
15857                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15858            }
15859
15860            synchronized (mPackages) {
15861                if (disabledSystem) {
15862                    enableSystemPackageLPw(deletedPackage);
15863                }
15864
15865                // Ensure the installer package name up to date
15866                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15867
15868                // Update permissions for restored package
15869                mPermissionManager.updatePermissions(
15870                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15871                        mPermissionCallback);
15872
15873                mSettings.writeLPr();
15874            }
15875
15876            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15877                    + " after failed upgrade");
15878        }
15879    }
15880
15881    /**
15882     * Checks whether the parent or any of the child packages have a change shared
15883     * user. For a package to be a valid update the shred users of the parent and
15884     * the children should match. We may later support changing child shared users.
15885     * @param oldPkg The updated package.
15886     * @param newPkg The update package.
15887     * @return The shared user that change between the versions.
15888     */
15889    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15890            PackageParser.Package newPkg) {
15891        // Check parent shared user
15892        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15893            return newPkg.packageName;
15894        }
15895        // Check child shared users
15896        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15897        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15898        for (int i = 0; i < newChildCount; i++) {
15899            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15900            // If this child was present, did it have the same shared user?
15901            for (int j = 0; j < oldChildCount; j++) {
15902                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15903                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15904                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15905                    return newChildPkg.packageName;
15906                }
15907            }
15908        }
15909        return null;
15910    }
15911
15912    private void removeNativeBinariesLI(PackageSetting ps) {
15913        // Remove the lib path for the parent package
15914        if (ps != null) {
15915            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15916            // Remove the lib path for the child packages
15917            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15918            for (int i = 0; i < childCount; i++) {
15919                PackageSetting childPs = null;
15920                synchronized (mPackages) {
15921                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15922                }
15923                if (childPs != null) {
15924                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15925                            .legacyNativeLibraryPathString);
15926                }
15927            }
15928        }
15929    }
15930
15931    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15932        // Enable the parent package
15933        mSettings.enableSystemPackageLPw(pkg.packageName);
15934        // Enable the child packages
15935        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15936        for (int i = 0; i < childCount; i++) {
15937            PackageParser.Package childPkg = pkg.childPackages.get(i);
15938            mSettings.enableSystemPackageLPw(childPkg.packageName);
15939        }
15940    }
15941
15942    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15943            PackageParser.Package newPkg) {
15944        // Disable the parent package (parent always replaced)
15945        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15946        // Disable the child packages
15947        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15948        for (int i = 0; i < childCount; i++) {
15949            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15950            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15951            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15952        }
15953        return disabled;
15954    }
15955
15956    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15957            String installerPackageName) {
15958        // Enable the parent package
15959        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15960        // Enable the child packages
15961        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15962        for (int i = 0; i < childCount; i++) {
15963            PackageParser.Package childPkg = pkg.childPackages.get(i);
15964            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15965        }
15966    }
15967
15968    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15969            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15970        // Update the parent package setting
15971        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15972                res, user, installReason);
15973        // Update the child packages setting
15974        final int childCount = (newPackage.childPackages != null)
15975                ? newPackage.childPackages.size() : 0;
15976        for (int i = 0; i < childCount; i++) {
15977            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15978            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15979            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15980                    childRes.origUsers, childRes, user, installReason);
15981        }
15982    }
15983
15984    private void updateSettingsInternalLI(PackageParser.Package pkg,
15985            String installerPackageName, int[] allUsers, int[] installedForUsers,
15986            PackageInstalledInfo res, UserHandle user, int installReason) {
15987        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15988
15989        String pkgName = pkg.packageName;
15990        synchronized (mPackages) {
15991            //write settings. the installStatus will be incomplete at this stage.
15992            //note that the new package setting would have already been
15993            //added to mPackages. It hasn't been persisted yet.
15994            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15995            // TODO: Remove this write? It's also written at the end of this method
15996            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15997            mSettings.writeLPr();
15998            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15999        }
16000
16001        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16002        synchronized (mPackages) {
16003// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16004            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16005                    mPermissionCallback);
16006            // For system-bundled packages, we assume that installing an upgraded version
16007            // of the package implies that the user actually wants to run that new code,
16008            // so we enable the package.
16009            PackageSetting ps = mSettings.mPackages.get(pkgName);
16010            final int userId = user.getIdentifier();
16011            if (ps != null) {
16012                if (isSystemApp(pkg)) {
16013                    if (DEBUG_INSTALL) {
16014                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16015                    }
16016                    // Enable system package for requested users
16017                    if (res.origUsers != null) {
16018                        for (int origUserId : res.origUsers) {
16019                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16020                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16021                                        origUserId, installerPackageName);
16022                            }
16023                        }
16024                    }
16025                    // Also convey the prior install/uninstall state
16026                    if (allUsers != null && installedForUsers != null) {
16027                        for (int currentUserId : allUsers) {
16028                            final boolean installed = ArrayUtils.contains(
16029                                    installedForUsers, currentUserId);
16030                            if (DEBUG_INSTALL) {
16031                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16032                            }
16033                            ps.setInstalled(installed, currentUserId);
16034                        }
16035                        // these install state changes will be persisted in the
16036                        // upcoming call to mSettings.writeLPr().
16037                    }
16038                }
16039                // It's implied that when a user requests installation, they want the app to be
16040                // installed and enabled.
16041                if (userId != UserHandle.USER_ALL) {
16042                    ps.setInstalled(true, userId);
16043                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16044                }
16045
16046                // When replacing an existing package, preserve the original install reason for all
16047                // users that had the package installed before.
16048                final Set<Integer> previousUserIds = new ArraySet<>();
16049                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16050                    final int installReasonCount = res.removedInfo.installReasons.size();
16051                    for (int i = 0; i < installReasonCount; i++) {
16052                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16053                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16054                        ps.setInstallReason(previousInstallReason, previousUserId);
16055                        previousUserIds.add(previousUserId);
16056                    }
16057                }
16058
16059                // Set install reason for users that are having the package newly installed.
16060                if (userId == UserHandle.USER_ALL) {
16061                    for (int currentUserId : sUserManager.getUserIds()) {
16062                        if (!previousUserIds.contains(currentUserId)) {
16063                            ps.setInstallReason(installReason, currentUserId);
16064                        }
16065                    }
16066                } else if (!previousUserIds.contains(userId)) {
16067                    ps.setInstallReason(installReason, userId);
16068                }
16069                mSettings.writeKernelMappingLPr(ps);
16070            }
16071            res.name = pkgName;
16072            res.uid = pkg.applicationInfo.uid;
16073            res.pkg = pkg;
16074            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16075            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16076            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16077            //to update install status
16078            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16079            mSettings.writeLPr();
16080            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16081        }
16082
16083        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16084    }
16085
16086    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16087        try {
16088            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16089            installPackageLI(args, res);
16090        } finally {
16091            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16092        }
16093    }
16094
16095    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16096        final int installFlags = args.installFlags;
16097        final String installerPackageName = args.installerPackageName;
16098        final String volumeUuid = args.volumeUuid;
16099        final File tmpPackageFile = new File(args.getCodePath());
16100        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16101        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16102                || (args.volumeUuid != null));
16103        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16104        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16105        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16106        final boolean virtualPreload =
16107                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16108        boolean replace = false;
16109        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16110        if (args.move != null) {
16111            // moving a complete application; perform an initial scan on the new install location
16112            scanFlags |= SCAN_INITIAL;
16113        }
16114        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16115            scanFlags |= SCAN_DONT_KILL_APP;
16116        }
16117        if (instantApp) {
16118            scanFlags |= SCAN_AS_INSTANT_APP;
16119        }
16120        if (fullApp) {
16121            scanFlags |= SCAN_AS_FULL_APP;
16122        }
16123        if (virtualPreload) {
16124            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16125        }
16126
16127        // Result object to be returned
16128        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16129        res.installerPackageName = installerPackageName;
16130
16131        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16132
16133        // Sanity check
16134        if (instantApp && (forwardLocked || onExternal)) {
16135            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16136                    + " external=" + onExternal);
16137            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16138            return;
16139        }
16140
16141        // Retrieve PackageSettings and parse package
16142        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16143                | PackageParser.PARSE_ENFORCE_CODE
16144                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16145                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16146                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16147                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16148        PackageParser pp = new PackageParser();
16149        pp.setSeparateProcesses(mSeparateProcesses);
16150        pp.setDisplayMetrics(mMetrics);
16151        pp.setCallback(mPackageParserCallback);
16152
16153        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16154        final PackageParser.Package pkg;
16155        try {
16156            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16157        } catch (PackageParserException e) {
16158            res.setError("Failed parse during installPackageLI", e);
16159            return;
16160        } finally {
16161            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16162        }
16163
16164        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16165        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16166            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
16167            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16168                    "Instant app package must target O");
16169            return;
16170        }
16171        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16172            Slog.w(TAG, "Instant app package " + pkg.packageName
16173                    + " does not target targetSandboxVersion 2");
16174            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16175                    "Instant app package must use targetSanboxVersion 2");
16176            return;
16177        }
16178
16179        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16180            // Static shared libraries have synthetic package names
16181            renameStaticSharedLibraryPackage(pkg);
16182
16183            // No static shared libs on external storage
16184            if (onExternal) {
16185                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16186                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16187                        "Packages declaring static-shared libs cannot be updated");
16188                return;
16189            }
16190        }
16191
16192        // If we are installing a clustered package add results for the children
16193        if (pkg.childPackages != null) {
16194            synchronized (mPackages) {
16195                final int childCount = pkg.childPackages.size();
16196                for (int i = 0; i < childCount; i++) {
16197                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16198                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16199                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16200                    childRes.pkg = childPkg;
16201                    childRes.name = childPkg.packageName;
16202                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16203                    if (childPs != null) {
16204                        childRes.origUsers = childPs.queryInstalledUsers(
16205                                sUserManager.getUserIds(), true);
16206                    }
16207                    if ((mPackages.containsKey(childPkg.packageName))) {
16208                        childRes.removedInfo = new PackageRemovedInfo(this);
16209                        childRes.removedInfo.removedPackage = childPkg.packageName;
16210                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16211                    }
16212                    if (res.addedChildPackages == null) {
16213                        res.addedChildPackages = new ArrayMap<>();
16214                    }
16215                    res.addedChildPackages.put(childPkg.packageName, childRes);
16216                }
16217            }
16218        }
16219
16220        // If package doesn't declare API override, mark that we have an install
16221        // time CPU ABI override.
16222        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16223            pkg.cpuAbiOverride = args.abiOverride;
16224        }
16225
16226        String pkgName = res.name = pkg.packageName;
16227        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16228            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16229                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16230                return;
16231            }
16232        }
16233
16234        try {
16235            // either use what we've been given or parse directly from the APK
16236            if (args.certificates != null) {
16237                try {
16238                    PackageParser.populateCertificates(pkg, args.certificates);
16239                } catch (PackageParserException e) {
16240                    // there was something wrong with the certificates we were given;
16241                    // try to pull them from the APK
16242                    PackageParser.collectCertificates(pkg, parseFlags);
16243                }
16244            } else {
16245                PackageParser.collectCertificates(pkg, parseFlags);
16246            }
16247        } catch (PackageParserException e) {
16248            res.setError("Failed collect during installPackageLI", e);
16249            return;
16250        }
16251
16252        // Get rid of all references to package scan path via parser.
16253        pp = null;
16254        String oldCodePath = null;
16255        boolean systemApp = false;
16256        synchronized (mPackages) {
16257            // Check if installing already existing package
16258            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16259                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16260                if (pkg.mOriginalPackages != null
16261                        && pkg.mOriginalPackages.contains(oldName)
16262                        && mPackages.containsKey(oldName)) {
16263                    // This package is derived from an original package,
16264                    // and this device has been updating from that original
16265                    // name.  We must continue using the original name, so
16266                    // rename the new package here.
16267                    pkg.setPackageName(oldName);
16268                    pkgName = pkg.packageName;
16269                    replace = true;
16270                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16271                            + oldName + " pkgName=" + pkgName);
16272                } else if (mPackages.containsKey(pkgName)) {
16273                    // This package, under its official name, already exists
16274                    // on the device; we should replace it.
16275                    replace = true;
16276                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16277                }
16278
16279                // Child packages are installed through the parent package
16280                if (pkg.parentPackage != null) {
16281                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16282                            "Package " + pkg.packageName + " is child of package "
16283                                    + pkg.parentPackage.parentPackage + ". Child packages "
16284                                    + "can be updated only through the parent package.");
16285                    return;
16286                }
16287
16288                if (replace) {
16289                    // Prevent apps opting out from runtime permissions
16290                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16291                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16292                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16293                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16294                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16295                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16296                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16297                                        + " doesn't support runtime permissions but the old"
16298                                        + " target SDK " + oldTargetSdk + " does.");
16299                        return;
16300                    }
16301                    // Prevent apps from downgrading their targetSandbox.
16302                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16303                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16304                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16305                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16306                                "Package " + pkg.packageName + " new target sandbox "
16307                                + newTargetSandbox + " is incompatible with the previous value of"
16308                                + oldTargetSandbox + ".");
16309                        return;
16310                    }
16311
16312                    // Prevent installing of child packages
16313                    if (oldPackage.parentPackage != null) {
16314                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16315                                "Package " + pkg.packageName + " is child of package "
16316                                        + oldPackage.parentPackage + ". Child packages "
16317                                        + "can be updated only through the parent package.");
16318                        return;
16319                    }
16320                }
16321            }
16322
16323            PackageSetting ps = mSettings.mPackages.get(pkgName);
16324            if (ps != null) {
16325                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16326
16327                // Static shared libs have same package with different versions where
16328                // we internally use a synthetic package name to allow multiple versions
16329                // of the same package, therefore we need to compare signatures against
16330                // the package setting for the latest library version.
16331                PackageSetting signatureCheckPs = ps;
16332                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16333                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16334                    if (libraryEntry != null) {
16335                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16336                    }
16337                }
16338
16339                // Quick sanity check that we're signed correctly if updating;
16340                // we'll check this again later when scanning, but we want to
16341                // bail early here before tripping over redefined permissions.
16342                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16343                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16344                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16345                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16346                                + pkg.packageName + " upgrade keys do not match the "
16347                                + "previously installed version");
16348                        return;
16349                    }
16350                } else {
16351                    try {
16352                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16353                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16354                        final boolean compatMatch = verifySignatures(
16355                                signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover);
16356                        // The new KeySets will be re-added later in the scanning process.
16357                        if (compatMatch) {
16358                            synchronized (mPackages) {
16359                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16360                            }
16361                        }
16362                    } catch (PackageManagerException e) {
16363                        res.setError(e.error, e.getMessage());
16364                        return;
16365                    }
16366                }
16367
16368                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16369                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16370                    systemApp = (ps.pkg.applicationInfo.flags &
16371                            ApplicationInfo.FLAG_SYSTEM) != 0;
16372                }
16373                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16374            }
16375
16376            int N = pkg.permissions.size();
16377            for (int i = N-1; i >= 0; i--) {
16378                final PackageParser.Permission perm = pkg.permissions.get(i);
16379                final BasePermission bp =
16380                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16381
16382                // Don't allow anyone but the system to define ephemeral permissions.
16383                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16384                        && !systemApp) {
16385                    Slog.w(TAG, "Non-System package " + pkg.packageName
16386                            + " attempting to delcare ephemeral permission "
16387                            + perm.info.name + "; Removing ephemeral.");
16388                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16389                }
16390
16391                // Check whether the newly-scanned package wants to define an already-defined perm
16392                if (bp != null) {
16393                    // If the defining package is signed with our cert, it's okay.  This
16394                    // also includes the "updating the same package" case, of course.
16395                    // "updating same package" could also involve key-rotation.
16396                    final boolean sigsOk;
16397                    final String sourcePackageName = bp.getSourcePackageName();
16398                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16399                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16400                    if (sourcePackageName.equals(pkg.packageName)
16401                            && (ksms.shouldCheckUpgradeKeySetLocked(
16402                                    sourcePackageSetting, scanFlags))) {
16403                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16404                    } else {
16405                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16406                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16407                    }
16408                    if (!sigsOk) {
16409                        // If the owning package is the system itself, we log but allow
16410                        // install to proceed; we fail the install on all other permission
16411                        // redefinitions.
16412                        if (!sourcePackageName.equals("android")) {
16413                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16414                                    + pkg.packageName + " attempting to redeclare permission "
16415                                    + perm.info.name + " already owned by " + sourcePackageName);
16416                            res.origPermission = perm.info.name;
16417                            res.origPackage = sourcePackageName;
16418                            return;
16419                        } else {
16420                            Slog.w(TAG, "Package " + pkg.packageName
16421                                    + " attempting to redeclare system permission "
16422                                    + perm.info.name + "; ignoring new declaration");
16423                            pkg.permissions.remove(i);
16424                        }
16425                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16426                        // Prevent apps to change protection level to dangerous from any other
16427                        // type as this would allow a privilege escalation where an app adds a
16428                        // normal/signature permission in other app's group and later redefines
16429                        // it as dangerous leading to the group auto-grant.
16430                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16431                                == PermissionInfo.PROTECTION_DANGEROUS) {
16432                            if (bp != null && !bp.isRuntime()) {
16433                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16434                                        + "non-runtime permission " + perm.info.name
16435                                        + " to runtime; keeping old protection level");
16436                                perm.info.protectionLevel = bp.getProtectionLevel();
16437                            }
16438                        }
16439                    }
16440                }
16441            }
16442        }
16443
16444        if (systemApp) {
16445            if (onExternal) {
16446                // Abort update; system app can't be replaced with app on sdcard
16447                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16448                        "Cannot install updates to system apps on sdcard");
16449                return;
16450            } else if (instantApp) {
16451                // Abort update; system app can't be replaced with an instant app
16452                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16453                        "Cannot update a system app with an instant app");
16454                return;
16455            }
16456        }
16457
16458        if (args.move != null) {
16459            // We did an in-place move, so dex is ready to roll
16460            scanFlags |= SCAN_NO_DEX;
16461            scanFlags |= SCAN_MOVE;
16462
16463            synchronized (mPackages) {
16464                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16465                if (ps == null) {
16466                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16467                            "Missing settings for moved package " + pkgName);
16468                }
16469
16470                // We moved the entire application as-is, so bring over the
16471                // previously derived ABI information.
16472                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16473                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16474            }
16475
16476        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16477            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16478            scanFlags |= SCAN_NO_DEX;
16479
16480            try {
16481                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16482                    args.abiOverride : pkg.cpuAbiOverride);
16483                final boolean extractNativeLibs = !pkg.isLibrary();
16484                derivePackageAbi(pkg, abiOverride, extractNativeLibs, mAppLib32InstallDir);
16485            } catch (PackageManagerException pme) {
16486                Slog.e(TAG, "Error deriving application ABI", pme);
16487                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16488                return;
16489            }
16490
16491            // Shared libraries for the package need to be updated.
16492            synchronized (mPackages) {
16493                try {
16494                    updateSharedLibrariesLPr(pkg, null);
16495                } catch (PackageManagerException e) {
16496                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16497                }
16498            }
16499        }
16500
16501        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16502            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16503            return;
16504        }
16505
16506        if (!instantApp) {
16507            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16508        } else {
16509            if (DEBUG_DOMAIN_VERIFICATION) {
16510                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16511            }
16512        }
16513
16514        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16515                "installPackageLI")) {
16516            if (replace) {
16517                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16518                    // Static libs have a synthetic package name containing the version
16519                    // and cannot be updated as an update would get a new package name,
16520                    // unless this is the exact same version code which is useful for
16521                    // development.
16522                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16523                    if (existingPkg != null &&
16524                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
16525                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16526                                + "static-shared libs cannot be updated");
16527                        return;
16528                    }
16529                }
16530                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
16531                        installerPackageName, res, args.installReason);
16532            } else {
16533                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16534                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16535            }
16536        }
16537
16538        // Check whether we need to dexopt the app.
16539        //
16540        // NOTE: it is IMPORTANT to call dexopt:
16541        //   - after doRename which will sync the package data from PackageParser.Package and its
16542        //     corresponding ApplicationInfo.
16543        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
16544        //     uid of the application (pkg.applicationInfo.uid).
16545        //     This update happens in place!
16546        //
16547        // We only need to dexopt if the package meets ALL of the following conditions:
16548        //   1) it is not forward locked.
16549        //   2) it is not on on an external ASEC container.
16550        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16551        //
16552        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16553        // complete, so we skip this step during installation. Instead, we'll take extra time
16554        // the first time the instant app starts. It's preferred to do it this way to provide
16555        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16556        // middle of running an instant app. The default behaviour can be overridden
16557        // via gservices.
16558        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
16559                && !forwardLocked
16560                && !pkg.applicationInfo.isExternalAsec()
16561                && (!instantApp || Global.getInt(mContext.getContentResolver(),
16562                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16563
16564        if (performDexopt) {
16565            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16566            // Do not run PackageDexOptimizer through the local performDexOpt
16567            // method because `pkg` may not be in `mPackages` yet.
16568            //
16569            // Also, don't fail application installs if the dexopt step fails.
16570            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16571                    REASON_INSTALL,
16572                    DexoptOptions.DEXOPT_BOOT_COMPLETE);
16573            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16574                    null /* instructionSets */,
16575                    getOrCreateCompilerPackageStats(pkg),
16576                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16577                    dexoptOptions);
16578            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16579        }
16580
16581        // Notify BackgroundDexOptService that the package has been changed.
16582        // If this is an update of a package which used to fail to compile,
16583        // BackgroundDexOptService will remove it from its blacklist.
16584        // TODO: Layering violation
16585        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16586
16587        synchronized (mPackages) {
16588            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16589            if (ps != null) {
16590                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16591                ps.setUpdateAvailable(false /*updateAvailable*/);
16592            }
16593
16594            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16595            for (int i = 0; i < childCount; i++) {
16596                PackageParser.Package childPkg = pkg.childPackages.get(i);
16597                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16598                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16599                if (childPs != null) {
16600                    childRes.newUsers = childPs.queryInstalledUsers(
16601                            sUserManager.getUserIds(), true);
16602                }
16603            }
16604
16605            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16606                updateSequenceNumberLP(ps, res.newUsers);
16607                updateInstantAppInstallerLocked(pkgName);
16608            }
16609        }
16610    }
16611
16612    private void startIntentFilterVerifications(int userId, boolean replacing,
16613            PackageParser.Package pkg) {
16614        if (mIntentFilterVerifierComponent == null) {
16615            Slog.w(TAG, "No IntentFilter verification will not be done as "
16616                    + "there is no IntentFilterVerifier available!");
16617            return;
16618        }
16619
16620        final int verifierUid = getPackageUid(
16621                mIntentFilterVerifierComponent.getPackageName(),
16622                MATCH_DEBUG_TRIAGED_MISSING,
16623                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16624
16625        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16626        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16627        mHandler.sendMessage(msg);
16628
16629        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16630        for (int i = 0; i < childCount; i++) {
16631            PackageParser.Package childPkg = pkg.childPackages.get(i);
16632            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16633            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16634            mHandler.sendMessage(msg);
16635        }
16636    }
16637
16638    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16639            PackageParser.Package pkg) {
16640        int size = pkg.activities.size();
16641        if (size == 0) {
16642            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16643                    "No activity, so no need to verify any IntentFilter!");
16644            return;
16645        }
16646
16647        final boolean hasDomainURLs = hasDomainURLs(pkg);
16648        if (!hasDomainURLs) {
16649            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16650                    "No domain URLs, so no need to verify any IntentFilter!");
16651            return;
16652        }
16653
16654        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16655                + " if any IntentFilter from the " + size
16656                + " Activities needs verification ...");
16657
16658        int count = 0;
16659        final String packageName = pkg.packageName;
16660
16661        synchronized (mPackages) {
16662            // If this is a new install and we see that we've already run verification for this
16663            // package, we have nothing to do: it means the state was restored from backup.
16664            if (!replacing) {
16665                IntentFilterVerificationInfo ivi =
16666                        mSettings.getIntentFilterVerificationLPr(packageName);
16667                if (ivi != null) {
16668                    if (DEBUG_DOMAIN_VERIFICATION) {
16669                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16670                                + ivi.getStatusString());
16671                    }
16672                    return;
16673                }
16674            }
16675
16676            // If any filters need to be verified, then all need to be.
16677            boolean needToVerify = false;
16678            for (PackageParser.Activity a : pkg.activities) {
16679                for (ActivityIntentInfo filter : a.intents) {
16680                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16681                        if (DEBUG_DOMAIN_VERIFICATION) {
16682                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16683                        }
16684                        needToVerify = true;
16685                        break;
16686                    }
16687                }
16688            }
16689
16690            if (needToVerify) {
16691                final int verificationId = mIntentFilterVerificationToken++;
16692                for (PackageParser.Activity a : pkg.activities) {
16693                    for (ActivityIntentInfo filter : a.intents) {
16694                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16695                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16696                                    "Verification needed for IntentFilter:" + filter.toString());
16697                            mIntentFilterVerifier.addOneIntentFilterVerification(
16698                                    verifierUid, userId, verificationId, filter, packageName);
16699                            count++;
16700                        }
16701                    }
16702                }
16703            }
16704        }
16705
16706        if (count > 0) {
16707            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16708                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16709                    +  " for userId:" + userId);
16710            mIntentFilterVerifier.startVerifications(userId);
16711        } else {
16712            if (DEBUG_DOMAIN_VERIFICATION) {
16713                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16714            }
16715        }
16716    }
16717
16718    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16719        final ComponentName cn  = filter.activity.getComponentName();
16720        final String packageName = cn.getPackageName();
16721
16722        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16723                packageName);
16724        if (ivi == null) {
16725            return true;
16726        }
16727        int status = ivi.getStatus();
16728        switch (status) {
16729            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16730            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16731                return true;
16732
16733            default:
16734                // Nothing to do
16735                return false;
16736        }
16737    }
16738
16739    private static boolean isMultiArch(ApplicationInfo info) {
16740        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16741    }
16742
16743    private static boolean isExternal(PackageParser.Package pkg) {
16744        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16745    }
16746
16747    private static boolean isExternal(PackageSetting ps) {
16748        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16749    }
16750
16751    private static boolean isSystemApp(PackageParser.Package pkg) {
16752        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16753    }
16754
16755    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16756        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16757    }
16758
16759    private static boolean isOemApp(PackageParser.Package pkg) {
16760        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16761    }
16762
16763    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16764        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16765    }
16766
16767    private static boolean isSystemApp(PackageSetting ps) {
16768        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16769    }
16770
16771    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16772        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16773    }
16774
16775    private int packageFlagsToInstallFlags(PackageSetting ps) {
16776        int installFlags = 0;
16777        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16778            // This existing package was an external ASEC install when we have
16779            // the external flag without a UUID
16780            installFlags |= PackageManager.INSTALL_EXTERNAL;
16781        }
16782        if (ps.isForwardLocked()) {
16783            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16784        }
16785        return installFlags;
16786    }
16787
16788    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16789        if (isExternal(pkg)) {
16790            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16791                return mSettings.getExternalVersion();
16792            } else {
16793                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16794            }
16795        } else {
16796            return mSettings.getInternalVersion();
16797        }
16798    }
16799
16800    private void deleteTempPackageFiles() {
16801        final FilenameFilter filter = new FilenameFilter() {
16802            public boolean accept(File dir, String name) {
16803                return name.startsWith("vmdl") && name.endsWith(".tmp");
16804            }
16805        };
16806        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16807            file.delete();
16808        }
16809    }
16810
16811    @Override
16812    public void deletePackageAsUser(String packageName, int versionCode,
16813            IPackageDeleteObserver observer, int userId, int flags) {
16814        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
16815                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
16816    }
16817
16818    @Override
16819    public void deletePackageVersioned(VersionedPackage versionedPackage,
16820            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16821        final int callingUid = Binder.getCallingUid();
16822        mContext.enforceCallingOrSelfPermission(
16823                android.Manifest.permission.DELETE_PACKAGES, null);
16824        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
16825        Preconditions.checkNotNull(versionedPackage);
16826        Preconditions.checkNotNull(observer);
16827        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
16828                PackageManager.VERSION_CODE_HIGHEST,
16829                Long.MAX_VALUE, "versionCode must be >= -1");
16830
16831        final String packageName = versionedPackage.getPackageName();
16832        final long versionCode = versionedPackage.getLongVersionCode();
16833        final String internalPackageName;
16834        synchronized (mPackages) {
16835            // Normalize package name to handle renamed packages and static libs
16836            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
16837        }
16838
16839        final int uid = Binder.getCallingUid();
16840        if (!isOrphaned(internalPackageName)
16841                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
16842            try {
16843                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16844                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16845                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16846                observer.onUserActionRequired(intent);
16847            } catch (RemoteException re) {
16848            }
16849            return;
16850        }
16851        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16852        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16853        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16854            mContext.enforceCallingOrSelfPermission(
16855                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16856                    "deletePackage for user " + userId);
16857        }
16858
16859        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16860            try {
16861                observer.onPackageDeleted(packageName,
16862                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16863            } catch (RemoteException re) {
16864            }
16865            return;
16866        }
16867
16868        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
16869            try {
16870                observer.onPackageDeleted(packageName,
16871                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16872            } catch (RemoteException re) {
16873            }
16874            return;
16875        }
16876
16877        if (DEBUG_REMOVE) {
16878            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
16879                    + " deleteAllUsers: " + deleteAllUsers + " version="
16880                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
16881                    ? "VERSION_CODE_HIGHEST" : versionCode));
16882        }
16883        // Queue up an async operation since the package deletion may take a little while.
16884        mHandler.post(new Runnable() {
16885            public void run() {
16886                mHandler.removeCallbacks(this);
16887                int returnCode;
16888                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
16889                boolean doDeletePackage = true;
16890                if (ps != null) {
16891                    final boolean targetIsInstantApp =
16892                            ps.getInstantApp(UserHandle.getUserId(callingUid));
16893                    doDeletePackage = !targetIsInstantApp
16894                            || canViewInstantApps;
16895                }
16896                if (doDeletePackage) {
16897                    if (!deleteAllUsers) {
16898                        returnCode = deletePackageX(internalPackageName, versionCode,
16899                                userId, deleteFlags);
16900                    } else {
16901                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
16902                                internalPackageName, users);
16903                        // If nobody is blocking uninstall, proceed with delete for all users
16904                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16905                            returnCode = deletePackageX(internalPackageName, versionCode,
16906                                    userId, deleteFlags);
16907                        } else {
16908                            // Otherwise uninstall individually for users with blockUninstalls=false
16909                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16910                            for (int userId : users) {
16911                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16912                                    returnCode = deletePackageX(internalPackageName, versionCode,
16913                                            userId, userFlags);
16914                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16915                                        Slog.w(TAG, "Package delete failed for user " + userId
16916                                                + ", returnCode " + returnCode);
16917                                    }
16918                                }
16919                            }
16920                            // The app has only been marked uninstalled for certain users.
16921                            // We still need to report that delete was blocked
16922                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16923                        }
16924                    }
16925                } else {
16926                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16927                }
16928                try {
16929                    observer.onPackageDeleted(packageName, returnCode, null);
16930                } catch (RemoteException e) {
16931                    Log.i(TAG, "Observer no longer exists.");
16932                } //end catch
16933            } //end run
16934        });
16935    }
16936
16937    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
16938        if (pkg.staticSharedLibName != null) {
16939            return pkg.manifestPackageName;
16940        }
16941        return pkg.packageName;
16942    }
16943
16944    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
16945        // Handle renamed packages
16946        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
16947        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
16948
16949        // Is this a static library?
16950        LongSparseArray<SharedLibraryEntry> versionedLib =
16951                mStaticLibsByDeclaringPackage.get(packageName);
16952        if (versionedLib == null || versionedLib.size() <= 0) {
16953            return packageName;
16954        }
16955
16956        // Figure out which lib versions the caller can see
16957        LongSparseLongArray versionsCallerCanSee = null;
16958        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
16959        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
16960                && callingAppId != Process.ROOT_UID) {
16961            versionsCallerCanSee = new LongSparseLongArray();
16962            String libName = versionedLib.valueAt(0).info.getName();
16963            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
16964            if (uidPackages != null) {
16965                for (String uidPackage : uidPackages) {
16966                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
16967                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
16968                    if (libIdx >= 0) {
16969                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
16970                        versionsCallerCanSee.append(libVersion, libVersion);
16971                    }
16972                }
16973            }
16974        }
16975
16976        // Caller can see nothing - done
16977        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
16978            return packageName;
16979        }
16980
16981        // Find the version the caller can see and the app version code
16982        SharedLibraryEntry highestVersion = null;
16983        final int versionCount = versionedLib.size();
16984        for (int i = 0; i < versionCount; i++) {
16985            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
16986            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
16987                    libEntry.info.getLongVersion()) < 0) {
16988                continue;
16989            }
16990            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
16991            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
16992                if (libVersionCode == versionCode) {
16993                    return libEntry.apk;
16994                }
16995            } else if (highestVersion == null) {
16996                highestVersion = libEntry;
16997            } else if (libVersionCode  > highestVersion.info
16998                    .getDeclaringPackage().getLongVersionCode()) {
16999                highestVersion = libEntry;
17000            }
17001        }
17002
17003        if (highestVersion != null) {
17004            return highestVersion.apk;
17005        }
17006
17007        return packageName;
17008    }
17009
17010    boolean isCallerVerifier(int callingUid) {
17011        final int callingUserId = UserHandle.getUserId(callingUid);
17012        return mRequiredVerifierPackage != null &&
17013                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17014    }
17015
17016    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17017        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17018              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17019            return true;
17020        }
17021        final int callingUserId = UserHandle.getUserId(callingUid);
17022        // If the caller installed the pkgName, then allow it to silently uninstall.
17023        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17024            return true;
17025        }
17026
17027        // Allow package verifier to silently uninstall.
17028        if (mRequiredVerifierPackage != null &&
17029                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17030            return true;
17031        }
17032
17033        // Allow package uninstaller to silently uninstall.
17034        if (mRequiredUninstallerPackage != null &&
17035                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17036            return true;
17037        }
17038
17039        // Allow storage manager to silently uninstall.
17040        if (mStorageManagerPackage != null &&
17041                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17042            return true;
17043        }
17044
17045        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17046        // uninstall for device owner provisioning.
17047        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17048                == PERMISSION_GRANTED) {
17049            return true;
17050        }
17051
17052        return false;
17053    }
17054
17055    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17056        int[] result = EMPTY_INT_ARRAY;
17057        for (int userId : userIds) {
17058            if (getBlockUninstallForUser(packageName, userId)) {
17059                result = ArrayUtils.appendInt(result, userId);
17060            }
17061        }
17062        return result;
17063    }
17064
17065    @Override
17066    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17067        final int callingUid = Binder.getCallingUid();
17068        if (getInstantAppPackageName(callingUid) != null
17069                && !isCallerSameApp(packageName, callingUid)) {
17070            return false;
17071        }
17072        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17073    }
17074
17075    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17076        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17077                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17078        try {
17079            if (dpm != null) {
17080                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17081                        /* callingUserOnly =*/ false);
17082                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17083                        : deviceOwnerComponentName.getPackageName();
17084                // Does the package contains the device owner?
17085                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17086                // this check is probably not needed, since DO should be registered as a device
17087                // admin on some user too. (Original bug for this: b/17657954)
17088                if (packageName.equals(deviceOwnerPackageName)) {
17089                    return true;
17090                }
17091                // Does it contain a device admin for any user?
17092                int[] users;
17093                if (userId == UserHandle.USER_ALL) {
17094                    users = sUserManager.getUserIds();
17095                } else {
17096                    users = new int[]{userId};
17097                }
17098                for (int i = 0; i < users.length; ++i) {
17099                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17100                        return true;
17101                    }
17102                }
17103            }
17104        } catch (RemoteException e) {
17105        }
17106        return false;
17107    }
17108
17109    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17110        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17111    }
17112
17113    /**
17114     *  This method is an internal method that could be get invoked either
17115     *  to delete an installed package or to clean up a failed installation.
17116     *  After deleting an installed package, a broadcast is sent to notify any
17117     *  listeners that the package has been removed. For cleaning up a failed
17118     *  installation, the broadcast is not necessary since the package's
17119     *  installation wouldn't have sent the initial broadcast either
17120     *  The key steps in deleting a package are
17121     *  deleting the package information in internal structures like mPackages,
17122     *  deleting the packages base directories through installd
17123     *  updating mSettings to reflect current status
17124     *  persisting settings for later use
17125     *  sending a broadcast if necessary
17126     */
17127    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17128        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17129        final boolean res;
17130
17131        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17132                ? UserHandle.USER_ALL : userId;
17133
17134        if (isPackageDeviceAdmin(packageName, removeUser)) {
17135            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17136            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17137        }
17138
17139        PackageSetting uninstalledPs = null;
17140        PackageParser.Package pkg = null;
17141
17142        // for the uninstall-updates case and restricted profiles, remember the per-
17143        // user handle installed state
17144        int[] allUsers;
17145        synchronized (mPackages) {
17146            uninstalledPs = mSettings.mPackages.get(packageName);
17147            if (uninstalledPs == null) {
17148                Slog.w(TAG, "Not removing non-existent package " + packageName);
17149                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17150            }
17151
17152            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17153                    && uninstalledPs.versionCode != versionCode) {
17154                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17155                        + uninstalledPs.versionCode + " != " + versionCode);
17156                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17157            }
17158
17159            // Static shared libs can be declared by any package, so let us not
17160            // allow removing a package if it provides a lib others depend on.
17161            pkg = mPackages.get(packageName);
17162
17163            allUsers = sUserManager.getUserIds();
17164
17165            if (pkg != null && pkg.staticSharedLibName != null) {
17166                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17167                        pkg.staticSharedLibVersion);
17168                if (libEntry != null) {
17169                    for (int currUserId : allUsers) {
17170                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17171                            continue;
17172                        }
17173                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17174                                libEntry.info, 0, currUserId);
17175                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17176                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17177                                    + " hosting lib " + libEntry.info.getName() + " version "
17178                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17179                                    + " for user " + currUserId);
17180                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17181                        }
17182                    }
17183                }
17184            }
17185
17186            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17187        }
17188
17189        final int freezeUser;
17190        if (isUpdatedSystemApp(uninstalledPs)
17191                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17192            // We're downgrading a system app, which will apply to all users, so
17193            // freeze them all during the downgrade
17194            freezeUser = UserHandle.USER_ALL;
17195        } else {
17196            freezeUser = removeUser;
17197        }
17198
17199        synchronized (mInstallLock) {
17200            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17201            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17202                    deleteFlags, "deletePackageX")) {
17203                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17204                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17205            }
17206            synchronized (mPackages) {
17207                if (res) {
17208                    if (pkg != null) {
17209                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17210                    }
17211                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17212                    updateInstantAppInstallerLocked(packageName);
17213                }
17214            }
17215        }
17216
17217        if (res) {
17218            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17219            info.sendPackageRemovedBroadcasts(killApp);
17220            info.sendSystemPackageUpdatedBroadcasts();
17221            info.sendSystemPackageAppearedBroadcasts();
17222        }
17223        // Force a gc here.
17224        Runtime.getRuntime().gc();
17225        // Delete the resources here after sending the broadcast to let
17226        // other processes clean up before deleting resources.
17227        if (info.args != null) {
17228            synchronized (mInstallLock) {
17229                info.args.doPostDeleteLI(true);
17230            }
17231        }
17232
17233        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17234    }
17235
17236    static class PackageRemovedInfo {
17237        final PackageSender packageSender;
17238        String removedPackage;
17239        String installerPackageName;
17240        int uid = -1;
17241        int removedAppId = -1;
17242        int[] origUsers;
17243        int[] removedUsers = null;
17244        int[] broadcastUsers = null;
17245        SparseArray<Integer> installReasons;
17246        boolean isRemovedPackageSystemUpdate = false;
17247        boolean isUpdate;
17248        boolean dataRemoved;
17249        boolean removedForAllUsers;
17250        boolean isStaticSharedLib;
17251        // Clean up resources deleted packages.
17252        InstallArgs args = null;
17253        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17254        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17255
17256        PackageRemovedInfo(PackageSender packageSender) {
17257            this.packageSender = packageSender;
17258        }
17259
17260        void sendPackageRemovedBroadcasts(boolean killApp) {
17261            sendPackageRemovedBroadcastInternal(killApp);
17262            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17263            for (int i = 0; i < childCount; i++) {
17264                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17265                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17266            }
17267        }
17268
17269        void sendSystemPackageUpdatedBroadcasts() {
17270            if (isRemovedPackageSystemUpdate) {
17271                sendSystemPackageUpdatedBroadcastsInternal();
17272                final int childCount = (removedChildPackages != null)
17273                        ? removedChildPackages.size() : 0;
17274                for (int i = 0; i < childCount; i++) {
17275                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17276                    if (childInfo.isRemovedPackageSystemUpdate) {
17277                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17278                    }
17279                }
17280            }
17281        }
17282
17283        void sendSystemPackageAppearedBroadcasts() {
17284            final int packageCount = (appearedChildPackages != null)
17285                    ? appearedChildPackages.size() : 0;
17286            for (int i = 0; i < packageCount; i++) {
17287                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17288                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17289                    true /*sendBootCompleted*/, false /*startReceiver*/,
17290                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17291            }
17292        }
17293
17294        private void sendSystemPackageUpdatedBroadcastsInternal() {
17295            Bundle extras = new Bundle(2);
17296            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17297            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17298            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17299                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17300            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17301                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17302            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17303                null, null, 0, removedPackage, null, null);
17304            if (installerPackageName != null) {
17305                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17306                        removedPackage, extras, 0 /*flags*/,
17307                        installerPackageName, null, null);
17308                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17309                        removedPackage, extras, 0 /*flags*/,
17310                        installerPackageName, null, null);
17311            }
17312        }
17313
17314        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17315            // Don't send static shared library removal broadcasts as these
17316            // libs are visible only the the apps that depend on them an one
17317            // cannot remove the library if it has a dependency.
17318            if (isStaticSharedLib) {
17319                return;
17320            }
17321            Bundle extras = new Bundle(2);
17322            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17323            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17324            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17325            if (isUpdate || isRemovedPackageSystemUpdate) {
17326                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17327            }
17328            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17329            if (removedPackage != null) {
17330                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17331                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
17332                if (installerPackageName != null) {
17333                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17334                            removedPackage, extras, 0 /*flags*/,
17335                            installerPackageName, null, broadcastUsers);
17336                }
17337                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17338                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17339                        removedPackage, extras,
17340                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17341                        null, null, broadcastUsers);
17342                }
17343            }
17344            if (removedAppId >= 0) {
17345                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17346                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17347                    null, null, broadcastUsers);
17348            }
17349        }
17350
17351        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17352            removedUsers = userIds;
17353            if (removedUsers == null) {
17354                broadcastUsers = null;
17355                return;
17356            }
17357
17358            broadcastUsers = EMPTY_INT_ARRAY;
17359            for (int i = userIds.length - 1; i >= 0; --i) {
17360                final int userId = userIds[i];
17361                if (deletedPackageSetting.getInstantApp(userId)) {
17362                    continue;
17363                }
17364                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17365            }
17366        }
17367    }
17368
17369    /*
17370     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17371     * flag is not set, the data directory is removed as well.
17372     * make sure this flag is set for partially installed apps. If not its meaningless to
17373     * delete a partially installed application.
17374     */
17375    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17376            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17377        String packageName = ps.name;
17378        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17379        // Retrieve object to delete permissions for shared user later on
17380        final PackageParser.Package deletedPkg;
17381        final PackageSetting deletedPs;
17382        // reader
17383        synchronized (mPackages) {
17384            deletedPkg = mPackages.get(packageName);
17385            deletedPs = mSettings.mPackages.get(packageName);
17386            if (outInfo != null) {
17387                outInfo.removedPackage = packageName;
17388                outInfo.installerPackageName = ps.installerPackageName;
17389                outInfo.isStaticSharedLib = deletedPkg != null
17390                        && deletedPkg.staticSharedLibName != null;
17391                outInfo.populateUsers(deletedPs == null ? null
17392                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17393            }
17394        }
17395
17396        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
17397
17398        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17399            final PackageParser.Package resolvedPkg;
17400            if (deletedPkg != null) {
17401                resolvedPkg = deletedPkg;
17402            } else {
17403                // We don't have a parsed package when it lives on an ejected
17404                // adopted storage device, so fake something together
17405                resolvedPkg = new PackageParser.Package(ps.name);
17406                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17407            }
17408            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17409                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17410            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17411            if (outInfo != null) {
17412                outInfo.dataRemoved = true;
17413            }
17414            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17415        }
17416
17417        int removedAppId = -1;
17418
17419        // writer
17420        synchronized (mPackages) {
17421            boolean installedStateChanged = false;
17422            if (deletedPs != null) {
17423                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17424                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17425                    clearDefaultBrowserIfNeeded(packageName);
17426                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17427                    removedAppId = mSettings.removePackageLPw(packageName);
17428                    if (outInfo != null) {
17429                        outInfo.removedAppId = removedAppId;
17430                    }
17431                    mPermissionManager.updatePermissions(
17432                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17433                    if (deletedPs.sharedUser != null) {
17434                        // Remove permissions associated with package. Since runtime
17435                        // permissions are per user we have to kill the removed package
17436                        // or packages running under the shared user of the removed
17437                        // package if revoking the permissions requested only by the removed
17438                        // package is successful and this causes a change in gids.
17439                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17440                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17441                                    userId);
17442                            if (userIdToKill == UserHandle.USER_ALL
17443                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17444                                // If gids changed for this user, kill all affected packages.
17445                                mHandler.post(new Runnable() {
17446                                    @Override
17447                                    public void run() {
17448                                        // This has to happen with no lock held.
17449                                        killApplication(deletedPs.name, deletedPs.appId,
17450                                                KILL_APP_REASON_GIDS_CHANGED);
17451                                    }
17452                                });
17453                                break;
17454                            }
17455                        }
17456                    }
17457                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17458                }
17459                // make sure to preserve per-user disabled state if this removal was just
17460                // a downgrade of a system app to the factory package
17461                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17462                    if (DEBUG_REMOVE) {
17463                        Slog.d(TAG, "Propagating install state across downgrade");
17464                    }
17465                    for (int userId : allUserHandles) {
17466                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17467                        if (DEBUG_REMOVE) {
17468                            Slog.d(TAG, "    user " + userId + " => " + installed);
17469                        }
17470                        if (installed != ps.getInstalled(userId)) {
17471                            installedStateChanged = true;
17472                        }
17473                        ps.setInstalled(installed, userId);
17474                    }
17475                }
17476            }
17477            // can downgrade to reader
17478            if (writeSettings) {
17479                // Save settings now
17480                mSettings.writeLPr();
17481            }
17482            if (installedStateChanged) {
17483                mSettings.writeKernelMappingLPr(ps);
17484            }
17485        }
17486        if (removedAppId != -1) {
17487            // A user ID was deleted here. Go through all users and remove it
17488            // from KeyStore.
17489            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17490        }
17491    }
17492
17493    static boolean locationIsPrivileged(String path) {
17494        try {
17495            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
17496            return path.startsWith(privilegedAppDir.getCanonicalPath());
17497        } catch (IOException e) {
17498            Slog.e(TAG, "Unable to access code path " + path);
17499        }
17500        return false;
17501    }
17502
17503    static boolean locationIsOem(String path) {
17504        try {
17505            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
17506        } catch (IOException e) {
17507            Slog.e(TAG, "Unable to access code path " + path);
17508        }
17509        return false;
17510    }
17511
17512    /*
17513     * Tries to delete system package.
17514     */
17515    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17516            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17517            boolean writeSettings) {
17518        if (deletedPs.parentPackageName != null) {
17519            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17520            return false;
17521        }
17522
17523        final boolean applyUserRestrictions
17524                = (allUserHandles != null) && (outInfo.origUsers != null);
17525        final PackageSetting disabledPs;
17526        // Confirm if the system package has been updated
17527        // An updated system app can be deleted. This will also have to restore
17528        // the system pkg from system partition
17529        // reader
17530        synchronized (mPackages) {
17531            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17532        }
17533
17534        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17535                + " disabledPs=" + disabledPs);
17536
17537        if (disabledPs == null) {
17538            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17539            return false;
17540        } else if (DEBUG_REMOVE) {
17541            Slog.d(TAG, "Deleting system pkg from data partition");
17542        }
17543
17544        if (DEBUG_REMOVE) {
17545            if (applyUserRestrictions) {
17546                Slog.d(TAG, "Remembering install states:");
17547                for (int userId : allUserHandles) {
17548                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17549                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17550                }
17551            }
17552        }
17553
17554        // Delete the updated package
17555        outInfo.isRemovedPackageSystemUpdate = true;
17556        if (outInfo.removedChildPackages != null) {
17557            final int childCount = (deletedPs.childPackageNames != null)
17558                    ? deletedPs.childPackageNames.size() : 0;
17559            for (int i = 0; i < childCount; i++) {
17560                String childPackageName = deletedPs.childPackageNames.get(i);
17561                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17562                        .contains(childPackageName)) {
17563                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17564                            childPackageName);
17565                    if (childInfo != null) {
17566                        childInfo.isRemovedPackageSystemUpdate = true;
17567                    }
17568                }
17569            }
17570        }
17571
17572        if (disabledPs.versionCode < deletedPs.versionCode) {
17573            // Delete data for downgrades
17574            flags &= ~PackageManager.DELETE_KEEP_DATA;
17575        } else {
17576            // Preserve data by setting flag
17577            flags |= PackageManager.DELETE_KEEP_DATA;
17578        }
17579
17580        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17581                outInfo, writeSettings, disabledPs.pkg);
17582        if (!ret) {
17583            return false;
17584        }
17585
17586        // writer
17587        synchronized (mPackages) {
17588            // NOTE: The system package always needs to be enabled; even if it's for
17589            // a compressed stub. If we don't, installing the system package fails
17590            // during scan [scanning checks the disabled packages]. We will reverse
17591            // this later, after we've "installed" the stub.
17592            // Reinstate the old system package
17593            enableSystemPackageLPw(disabledPs.pkg);
17594            // Remove any native libraries from the upgraded package.
17595            removeNativeBinariesLI(deletedPs);
17596        }
17597
17598        // Install the system package
17599        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17600        try {
17601            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
17602                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17603        } catch (PackageManagerException e) {
17604            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17605                    + e.getMessage());
17606            return false;
17607        } finally {
17608            if (disabledPs.pkg.isStub) {
17609                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
17610            }
17611        }
17612        return true;
17613    }
17614
17615    /**
17616     * Installs a package that's already on the system partition.
17617     */
17618    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
17619            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
17620            @Nullable PermissionsState origPermissionState, boolean writeSettings)
17621                    throws PackageManagerException {
17622        @ParseFlags int parseFlags =
17623                mDefParseFlags
17624                | PackageParser.PARSE_MUST_BE_APK
17625                | PackageParser.PARSE_IS_SYSTEM_DIR;
17626        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
17627        if (isPrivileged || locationIsPrivileged(codePathString)) {
17628            scanFlags |= SCAN_AS_PRIVILEGED;
17629        }
17630        if (locationIsOem(codePathString)) {
17631            scanFlags |= SCAN_AS_OEM;
17632        }
17633
17634        final File codePath = new File(codePathString);
17635        final PackageParser.Package pkg =
17636                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
17637
17638        try {
17639            // update shared libraries for the newly re-installed system package
17640            updateSharedLibrariesLPr(pkg, null);
17641        } catch (PackageManagerException e) {
17642            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17643        }
17644
17645        prepareAppDataAfterInstallLIF(pkg);
17646
17647        // writer
17648        synchronized (mPackages) {
17649            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
17650
17651            // Propagate the permissions state as we do not want to drop on the floor
17652            // runtime permissions. The update permissions method below will take
17653            // care of removing obsolete permissions and grant install permissions.
17654            if (origPermissionState != null) {
17655                ps.getPermissionsState().copyFrom(origPermissionState);
17656            }
17657            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
17658                    mPermissionCallback);
17659
17660            final boolean applyUserRestrictions
17661                    = (allUserHandles != null) && (origUserHandles != null);
17662            if (applyUserRestrictions) {
17663                boolean installedStateChanged = false;
17664                if (DEBUG_REMOVE) {
17665                    Slog.d(TAG, "Propagating install state across reinstall");
17666                }
17667                for (int userId : allUserHandles) {
17668                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
17669                    if (DEBUG_REMOVE) {
17670                        Slog.d(TAG, "    user " + userId + " => " + installed);
17671                    }
17672                    if (installed != ps.getInstalled(userId)) {
17673                        installedStateChanged = true;
17674                    }
17675                    ps.setInstalled(installed, userId);
17676
17677                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17678                }
17679                // Regardless of writeSettings we need to ensure that this restriction
17680                // state propagation is persisted
17681                mSettings.writeAllUsersPackageRestrictionsLPr();
17682                if (installedStateChanged) {
17683                    mSettings.writeKernelMappingLPr(ps);
17684                }
17685            }
17686            // can downgrade to reader here
17687            if (writeSettings) {
17688                mSettings.writeLPr();
17689            }
17690        }
17691        return pkg;
17692    }
17693
17694    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17695            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17696            PackageRemovedInfo outInfo, boolean writeSettings,
17697            PackageParser.Package replacingPackage) {
17698        synchronized (mPackages) {
17699            if (outInfo != null) {
17700                outInfo.uid = ps.appId;
17701            }
17702
17703            if (outInfo != null && outInfo.removedChildPackages != null) {
17704                final int childCount = (ps.childPackageNames != null)
17705                        ? ps.childPackageNames.size() : 0;
17706                for (int i = 0; i < childCount; i++) {
17707                    String childPackageName = ps.childPackageNames.get(i);
17708                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17709                    if (childPs == null) {
17710                        return false;
17711                    }
17712                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17713                            childPackageName);
17714                    if (childInfo != null) {
17715                        childInfo.uid = childPs.appId;
17716                    }
17717                }
17718            }
17719        }
17720
17721        // Delete package data from internal structures and also remove data if flag is set
17722        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17723
17724        // Delete the child packages data
17725        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17726        for (int i = 0; i < childCount; i++) {
17727            PackageSetting childPs;
17728            synchronized (mPackages) {
17729                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17730            }
17731            if (childPs != null) {
17732                PackageRemovedInfo childOutInfo = (outInfo != null
17733                        && outInfo.removedChildPackages != null)
17734                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17735                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17736                        && (replacingPackage != null
17737                        && !replacingPackage.hasChildPackage(childPs.name))
17738                        ? flags & ~DELETE_KEEP_DATA : flags;
17739                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17740                        deleteFlags, writeSettings);
17741            }
17742        }
17743
17744        // Delete application code and resources only for parent packages
17745        if (ps.parentPackageName == null) {
17746            if (deleteCodeAndResources && (outInfo != null)) {
17747                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17748                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17749                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17750            }
17751        }
17752
17753        return true;
17754    }
17755
17756    @Override
17757    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17758            int userId) {
17759        mContext.enforceCallingOrSelfPermission(
17760                android.Manifest.permission.DELETE_PACKAGES, null);
17761        synchronized (mPackages) {
17762            // Cannot block uninstall of static shared libs as they are
17763            // considered a part of the using app (emulating static linking).
17764            // Also static libs are installed always on internal storage.
17765            PackageParser.Package pkg = mPackages.get(packageName);
17766            if (pkg != null && pkg.staticSharedLibName != null) {
17767                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17768                        + " providing static shared library: " + pkg.staticSharedLibName);
17769                return false;
17770            }
17771            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
17772            mSettings.writePackageRestrictionsLPr(userId);
17773        }
17774        return true;
17775    }
17776
17777    @Override
17778    public boolean getBlockUninstallForUser(String packageName, int userId) {
17779        synchronized (mPackages) {
17780            final PackageSetting ps = mSettings.mPackages.get(packageName);
17781            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
17782                return false;
17783            }
17784            return mSettings.getBlockUninstallLPr(userId, packageName);
17785        }
17786    }
17787
17788    @Override
17789    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17790        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
17791        synchronized (mPackages) {
17792            PackageSetting ps = mSettings.mPackages.get(packageName);
17793            if (ps == null) {
17794                Log.w(TAG, "Package doesn't exist: " + packageName);
17795                return false;
17796            }
17797            if (systemUserApp) {
17798                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17799            } else {
17800                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17801            }
17802            mSettings.writeLPr();
17803        }
17804        return true;
17805    }
17806
17807    /*
17808     * This method handles package deletion in general
17809     */
17810    private boolean deletePackageLIF(String packageName, UserHandle user,
17811            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17812            PackageRemovedInfo outInfo, boolean writeSettings,
17813            PackageParser.Package replacingPackage) {
17814        if (packageName == null) {
17815            Slog.w(TAG, "Attempt to delete null packageName.");
17816            return false;
17817        }
17818
17819        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17820
17821        PackageSetting ps;
17822        synchronized (mPackages) {
17823            ps = mSettings.mPackages.get(packageName);
17824            if (ps == null) {
17825                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17826                return false;
17827            }
17828
17829            if (ps.parentPackageName != null && (!isSystemApp(ps)
17830                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17831                if (DEBUG_REMOVE) {
17832                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17833                            + ((user == null) ? UserHandle.USER_ALL : user));
17834                }
17835                final int removedUserId = (user != null) ? user.getIdentifier()
17836                        : UserHandle.USER_ALL;
17837                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17838                    return false;
17839                }
17840                markPackageUninstalledForUserLPw(ps, user);
17841                scheduleWritePackageRestrictionsLocked(user);
17842                return true;
17843            }
17844        }
17845
17846        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17847                && user.getIdentifier() != UserHandle.USER_ALL)) {
17848            // The caller is asking that the package only be deleted for a single
17849            // user.  To do this, we just mark its uninstalled state and delete
17850            // its data. If this is a system app, we only allow this to happen if
17851            // they have set the special DELETE_SYSTEM_APP which requests different
17852            // semantics than normal for uninstalling system apps.
17853            markPackageUninstalledForUserLPw(ps, user);
17854
17855            if (!isSystemApp(ps)) {
17856                // Do not uninstall the APK if an app should be cached
17857                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17858                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17859                    // Other user still have this package installed, so all
17860                    // we need to do is clear this user's data and save that
17861                    // it is uninstalled.
17862                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17863                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17864                        return false;
17865                    }
17866                    scheduleWritePackageRestrictionsLocked(user);
17867                    return true;
17868                } else {
17869                    // We need to set it back to 'installed' so the uninstall
17870                    // broadcasts will be sent correctly.
17871                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17872                    ps.setInstalled(true, user.getIdentifier());
17873                    mSettings.writeKernelMappingLPr(ps);
17874                }
17875            } else {
17876                // This is a system app, so we assume that the
17877                // other users still have this package installed, so all
17878                // we need to do is clear this user's data and save that
17879                // it is uninstalled.
17880                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17881                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17882                    return false;
17883                }
17884                scheduleWritePackageRestrictionsLocked(user);
17885                return true;
17886            }
17887        }
17888
17889        // If we are deleting a composite package for all users, keep track
17890        // of result for each child.
17891        if (ps.childPackageNames != null && outInfo != null) {
17892            synchronized (mPackages) {
17893                final int childCount = ps.childPackageNames.size();
17894                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17895                for (int i = 0; i < childCount; i++) {
17896                    String childPackageName = ps.childPackageNames.get(i);
17897                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
17898                    childInfo.removedPackage = childPackageName;
17899                    childInfo.installerPackageName = ps.installerPackageName;
17900                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17901                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17902                    if (childPs != null) {
17903                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17904                    }
17905                }
17906            }
17907        }
17908
17909        boolean ret = false;
17910        if (isSystemApp(ps)) {
17911            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17912            // When an updated system application is deleted we delete the existing resources
17913            // as well and fall back to existing code in system partition
17914            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17915        } else {
17916            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17917            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17918                    outInfo, writeSettings, replacingPackage);
17919        }
17920
17921        // Take a note whether we deleted the package for all users
17922        if (outInfo != null) {
17923            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17924            if (outInfo.removedChildPackages != null) {
17925                synchronized (mPackages) {
17926                    final int childCount = outInfo.removedChildPackages.size();
17927                    for (int i = 0; i < childCount; i++) {
17928                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17929                        if (childInfo != null) {
17930                            childInfo.removedForAllUsers = mPackages.get(
17931                                    childInfo.removedPackage) == null;
17932                        }
17933                    }
17934                }
17935            }
17936            // If we uninstalled an update to a system app there may be some
17937            // child packages that appeared as they are declared in the system
17938            // app but were not declared in the update.
17939            if (isSystemApp(ps)) {
17940                synchronized (mPackages) {
17941                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17942                    final int childCount = (updatedPs.childPackageNames != null)
17943                            ? updatedPs.childPackageNames.size() : 0;
17944                    for (int i = 0; i < childCount; i++) {
17945                        String childPackageName = updatedPs.childPackageNames.get(i);
17946                        if (outInfo.removedChildPackages == null
17947                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17948                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17949                            if (childPs == null) {
17950                                continue;
17951                            }
17952                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17953                            installRes.name = childPackageName;
17954                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17955                            installRes.pkg = mPackages.get(childPackageName);
17956                            installRes.uid = childPs.pkg.applicationInfo.uid;
17957                            if (outInfo.appearedChildPackages == null) {
17958                                outInfo.appearedChildPackages = new ArrayMap<>();
17959                            }
17960                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17961                        }
17962                    }
17963                }
17964            }
17965        }
17966
17967        return ret;
17968    }
17969
17970    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17971        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17972                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17973        for (int nextUserId : userIds) {
17974            if (DEBUG_REMOVE) {
17975                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17976            }
17977            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17978                    false /*installed*/,
17979                    true /*stopped*/,
17980                    true /*notLaunched*/,
17981                    false /*hidden*/,
17982                    false /*suspended*/,
17983                    false /*instantApp*/,
17984                    false /*virtualPreload*/,
17985                    null /*lastDisableAppCaller*/,
17986                    null /*enabledComponents*/,
17987                    null /*disabledComponents*/,
17988                    ps.readUserState(nextUserId).domainVerificationStatus,
17989                    0, PackageManager.INSTALL_REASON_UNKNOWN);
17990        }
17991        mSettings.writeKernelMappingLPr(ps);
17992    }
17993
17994    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17995            PackageRemovedInfo outInfo) {
17996        final PackageParser.Package pkg;
17997        synchronized (mPackages) {
17998            pkg = mPackages.get(ps.name);
17999        }
18000
18001        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18002                : new int[] {userId};
18003        for (int nextUserId : userIds) {
18004            if (DEBUG_REMOVE) {
18005                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18006                        + nextUserId);
18007            }
18008
18009            destroyAppDataLIF(pkg, userId,
18010                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18011            destroyAppProfilesLIF(pkg, userId);
18012            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18013            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18014            schedulePackageCleaning(ps.name, nextUserId, false);
18015            synchronized (mPackages) {
18016                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18017                    scheduleWritePackageRestrictionsLocked(nextUserId);
18018                }
18019                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18020            }
18021        }
18022
18023        if (outInfo != null) {
18024            outInfo.removedPackage = ps.name;
18025            outInfo.installerPackageName = ps.installerPackageName;
18026            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18027            outInfo.removedAppId = ps.appId;
18028            outInfo.removedUsers = userIds;
18029            outInfo.broadcastUsers = userIds;
18030        }
18031
18032        return true;
18033    }
18034
18035    private final class ClearStorageConnection implements ServiceConnection {
18036        IMediaContainerService mContainerService;
18037
18038        @Override
18039        public void onServiceConnected(ComponentName name, IBinder service) {
18040            synchronized (this) {
18041                mContainerService = IMediaContainerService.Stub
18042                        .asInterface(Binder.allowBlocking(service));
18043                notifyAll();
18044            }
18045        }
18046
18047        @Override
18048        public void onServiceDisconnected(ComponentName name) {
18049        }
18050    }
18051
18052    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18053        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18054
18055        final boolean mounted;
18056        if (Environment.isExternalStorageEmulated()) {
18057            mounted = true;
18058        } else {
18059            final String status = Environment.getExternalStorageState();
18060
18061            mounted = status.equals(Environment.MEDIA_MOUNTED)
18062                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18063        }
18064
18065        if (!mounted) {
18066            return;
18067        }
18068
18069        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18070        int[] users;
18071        if (userId == UserHandle.USER_ALL) {
18072            users = sUserManager.getUserIds();
18073        } else {
18074            users = new int[] { userId };
18075        }
18076        final ClearStorageConnection conn = new ClearStorageConnection();
18077        if (mContext.bindServiceAsUser(
18078                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18079            try {
18080                for (int curUser : users) {
18081                    long timeout = SystemClock.uptimeMillis() + 5000;
18082                    synchronized (conn) {
18083                        long now;
18084                        while (conn.mContainerService == null &&
18085                                (now = SystemClock.uptimeMillis()) < timeout) {
18086                            try {
18087                                conn.wait(timeout - now);
18088                            } catch (InterruptedException e) {
18089                            }
18090                        }
18091                    }
18092                    if (conn.mContainerService == null) {
18093                        return;
18094                    }
18095
18096                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18097                    clearDirectory(conn.mContainerService,
18098                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18099                    if (allData) {
18100                        clearDirectory(conn.mContainerService,
18101                                userEnv.buildExternalStorageAppDataDirs(packageName));
18102                        clearDirectory(conn.mContainerService,
18103                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18104                    }
18105                }
18106            } finally {
18107                mContext.unbindService(conn);
18108            }
18109        }
18110    }
18111
18112    @Override
18113    public void clearApplicationProfileData(String packageName) {
18114        enforceSystemOrRoot("Only the system can clear all profile data");
18115
18116        final PackageParser.Package pkg;
18117        synchronized (mPackages) {
18118            pkg = mPackages.get(packageName);
18119        }
18120
18121        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18122            synchronized (mInstallLock) {
18123                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18124            }
18125        }
18126    }
18127
18128    @Override
18129    public void clearApplicationUserData(final String packageName,
18130            final IPackageDataObserver observer, final int userId) {
18131        mContext.enforceCallingOrSelfPermission(
18132                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18133
18134        final int callingUid = Binder.getCallingUid();
18135        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18136                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18137
18138        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18139        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18140        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18141            throw new SecurityException("Cannot clear data for a protected package: "
18142                    + packageName);
18143        }
18144        // Queue up an async operation since the package deletion may take a little while.
18145        mHandler.post(new Runnable() {
18146            public void run() {
18147                mHandler.removeCallbacks(this);
18148                final boolean succeeded;
18149                if (!filterApp) {
18150                    try (PackageFreezer freezer = freezePackage(packageName,
18151                            "clearApplicationUserData")) {
18152                        synchronized (mInstallLock) {
18153                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18154                        }
18155                        clearExternalStorageDataSync(packageName, userId, true);
18156                        synchronized (mPackages) {
18157                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18158                                    packageName, userId);
18159                        }
18160                    }
18161                    if (succeeded) {
18162                        // invoke DeviceStorageMonitor's update method to clear any notifications
18163                        DeviceStorageMonitorInternal dsm = LocalServices
18164                                .getService(DeviceStorageMonitorInternal.class);
18165                        if (dsm != null) {
18166                            dsm.checkMemory();
18167                        }
18168                    }
18169                } else {
18170                    succeeded = false;
18171                }
18172                if (observer != null) {
18173                    try {
18174                        observer.onRemoveCompleted(packageName, succeeded);
18175                    } catch (RemoteException e) {
18176                        Log.i(TAG, "Observer no longer exists.");
18177                    }
18178                } //end if observer
18179            } //end run
18180        });
18181    }
18182
18183    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18184        if (packageName == null) {
18185            Slog.w(TAG, "Attempt to delete null packageName.");
18186            return false;
18187        }
18188
18189        // Try finding details about the requested package
18190        PackageParser.Package pkg;
18191        synchronized (mPackages) {
18192            pkg = mPackages.get(packageName);
18193            if (pkg == null) {
18194                final PackageSetting ps = mSettings.mPackages.get(packageName);
18195                if (ps != null) {
18196                    pkg = ps.pkg;
18197                }
18198            }
18199
18200            if (pkg == null) {
18201                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18202                return false;
18203            }
18204
18205            PackageSetting ps = (PackageSetting) pkg.mExtras;
18206            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18207        }
18208
18209        clearAppDataLIF(pkg, userId,
18210                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18211
18212        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18213        removeKeystoreDataIfNeeded(userId, appId);
18214
18215        UserManagerInternal umInternal = getUserManagerInternal();
18216        final int flags;
18217        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18218            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18219        } else if (umInternal.isUserRunning(userId)) {
18220            flags = StorageManager.FLAG_STORAGE_DE;
18221        } else {
18222            flags = 0;
18223        }
18224        prepareAppDataContentsLIF(pkg, userId, flags);
18225
18226        return true;
18227    }
18228
18229    /**
18230     * Reverts user permission state changes (permissions and flags) in
18231     * all packages for a given user.
18232     *
18233     * @param userId The device user for which to do a reset.
18234     */
18235    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18236        final int packageCount = mPackages.size();
18237        for (int i = 0; i < packageCount; i++) {
18238            PackageParser.Package pkg = mPackages.valueAt(i);
18239            PackageSetting ps = (PackageSetting) pkg.mExtras;
18240            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18241        }
18242    }
18243
18244    private void resetNetworkPolicies(int userId) {
18245        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18246    }
18247
18248    /**
18249     * Reverts user permission state changes (permissions and flags).
18250     *
18251     * @param ps The package for which to reset.
18252     * @param userId The device user for which to do a reset.
18253     */
18254    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18255            final PackageSetting ps, final int userId) {
18256        if (ps.pkg == null) {
18257            return;
18258        }
18259
18260        // These are flags that can change base on user actions.
18261        final int userSettableMask = FLAG_PERMISSION_USER_SET
18262                | FLAG_PERMISSION_USER_FIXED
18263                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18264                | FLAG_PERMISSION_REVIEW_REQUIRED;
18265
18266        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18267                | FLAG_PERMISSION_POLICY_FIXED;
18268
18269        boolean writeInstallPermissions = false;
18270        boolean writeRuntimePermissions = false;
18271
18272        final int permissionCount = ps.pkg.requestedPermissions.size();
18273        for (int i = 0; i < permissionCount; i++) {
18274            final String permName = ps.pkg.requestedPermissions.get(i);
18275            final BasePermission bp =
18276                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18277            if (bp == null) {
18278                continue;
18279            }
18280
18281            // If shared user we just reset the state to which only this app contributed.
18282            if (ps.sharedUser != null) {
18283                boolean used = false;
18284                final int packageCount = ps.sharedUser.packages.size();
18285                for (int j = 0; j < packageCount; j++) {
18286                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18287                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18288                            && pkg.pkg.requestedPermissions.contains(permName)) {
18289                        used = true;
18290                        break;
18291                    }
18292                }
18293                if (used) {
18294                    continue;
18295                }
18296            }
18297
18298            final PermissionsState permissionsState = ps.getPermissionsState();
18299
18300            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18301
18302            // Always clear the user settable flags.
18303            final boolean hasInstallState =
18304                    permissionsState.getInstallPermissionState(permName) != null;
18305            // If permission review is enabled and this is a legacy app, mark the
18306            // permission as requiring a review as this is the initial state.
18307            int flags = 0;
18308            if (mSettings.mPermissions.mPermissionReviewRequired
18309                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18310                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18311            }
18312            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18313                if (hasInstallState) {
18314                    writeInstallPermissions = true;
18315                } else {
18316                    writeRuntimePermissions = true;
18317                }
18318            }
18319
18320            // Below is only runtime permission handling.
18321            if (!bp.isRuntime()) {
18322                continue;
18323            }
18324
18325            // Never clobber system or policy.
18326            if ((oldFlags & policyOrSystemFlags) != 0) {
18327                continue;
18328            }
18329
18330            // If this permission was granted by default, make sure it is.
18331            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18332                if (permissionsState.grantRuntimePermission(bp, userId)
18333                        != PERMISSION_OPERATION_FAILURE) {
18334                    writeRuntimePermissions = true;
18335                }
18336            // If permission review is enabled the permissions for a legacy apps
18337            // are represented as constantly granted runtime ones, so don't revoke.
18338            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18339                // Otherwise, reset the permission.
18340                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18341                switch (revokeResult) {
18342                    case PERMISSION_OPERATION_SUCCESS:
18343                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18344                        writeRuntimePermissions = true;
18345                        final int appId = ps.appId;
18346                        mHandler.post(new Runnable() {
18347                            @Override
18348                            public void run() {
18349                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18350                            }
18351                        });
18352                    } break;
18353                }
18354            }
18355        }
18356
18357        // Synchronously write as we are taking permissions away.
18358        if (writeRuntimePermissions) {
18359            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18360        }
18361
18362        // Synchronously write as we are taking permissions away.
18363        if (writeInstallPermissions) {
18364            mSettings.writeLPr();
18365        }
18366    }
18367
18368    /**
18369     * Remove entries from the keystore daemon. Will only remove it if the
18370     * {@code appId} is valid.
18371     */
18372    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18373        if (appId < 0) {
18374            return;
18375        }
18376
18377        final KeyStore keyStore = KeyStore.getInstance();
18378        if (keyStore != null) {
18379            if (userId == UserHandle.USER_ALL) {
18380                for (final int individual : sUserManager.getUserIds()) {
18381                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18382                }
18383            } else {
18384                keyStore.clearUid(UserHandle.getUid(userId, appId));
18385            }
18386        } else {
18387            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18388        }
18389    }
18390
18391    @Override
18392    public void deleteApplicationCacheFiles(final String packageName,
18393            final IPackageDataObserver observer) {
18394        final int userId = UserHandle.getCallingUserId();
18395        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18396    }
18397
18398    @Override
18399    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18400            final IPackageDataObserver observer) {
18401        final int callingUid = Binder.getCallingUid();
18402        mContext.enforceCallingOrSelfPermission(
18403                android.Manifest.permission.DELETE_CACHE_FILES, null);
18404        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18405                /* requireFullPermission= */ true, /* checkShell= */ false,
18406                "delete application cache files");
18407        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18408                android.Manifest.permission.ACCESS_INSTANT_APPS);
18409
18410        final PackageParser.Package pkg;
18411        synchronized (mPackages) {
18412            pkg = mPackages.get(packageName);
18413        }
18414
18415        // Queue up an async operation since the package deletion may take a little while.
18416        mHandler.post(new Runnable() {
18417            public void run() {
18418                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18419                boolean doClearData = true;
18420                if (ps != null) {
18421                    final boolean targetIsInstantApp =
18422                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18423                    doClearData = !targetIsInstantApp
18424                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18425                }
18426                if (doClearData) {
18427                    synchronized (mInstallLock) {
18428                        final int flags = StorageManager.FLAG_STORAGE_DE
18429                                | StorageManager.FLAG_STORAGE_CE;
18430                        // We're only clearing cache files, so we don't care if the
18431                        // app is unfrozen and still able to run
18432                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18433                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18434                    }
18435                    clearExternalStorageDataSync(packageName, userId, false);
18436                }
18437                if (observer != null) {
18438                    try {
18439                        observer.onRemoveCompleted(packageName, true);
18440                    } catch (RemoteException e) {
18441                        Log.i(TAG, "Observer no longer exists.");
18442                    }
18443                }
18444            }
18445        });
18446    }
18447
18448    @Override
18449    public void getPackageSizeInfo(final String packageName, int userHandle,
18450            final IPackageStatsObserver observer) {
18451        throw new UnsupportedOperationException(
18452                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18453    }
18454
18455    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18456        final PackageSetting ps;
18457        synchronized (mPackages) {
18458            ps = mSettings.mPackages.get(packageName);
18459            if (ps == null) {
18460                Slog.w(TAG, "Failed to find settings for " + packageName);
18461                return false;
18462            }
18463        }
18464
18465        final String[] packageNames = { packageName };
18466        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18467        final String[] codePaths = { ps.codePathString };
18468
18469        try {
18470            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18471                    ps.appId, ceDataInodes, codePaths, stats);
18472
18473            // For now, ignore code size of packages on system partition
18474            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18475                stats.codeSize = 0;
18476            }
18477
18478            // External clients expect these to be tracked separately
18479            stats.dataSize -= stats.cacheSize;
18480
18481        } catch (InstallerException e) {
18482            Slog.w(TAG, String.valueOf(e));
18483            return false;
18484        }
18485
18486        return true;
18487    }
18488
18489    private int getUidTargetSdkVersionLockedLPr(int uid) {
18490        Object obj = mSettings.getUserIdLPr(uid);
18491        if (obj instanceof SharedUserSetting) {
18492            final SharedUserSetting sus = (SharedUserSetting) obj;
18493            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18494            final Iterator<PackageSetting> it = sus.packages.iterator();
18495            while (it.hasNext()) {
18496                final PackageSetting ps = it.next();
18497                if (ps.pkg != null) {
18498                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18499                    if (v < vers) vers = v;
18500                }
18501            }
18502            return vers;
18503        } else if (obj instanceof PackageSetting) {
18504            final PackageSetting ps = (PackageSetting) obj;
18505            if (ps.pkg != null) {
18506                return ps.pkg.applicationInfo.targetSdkVersion;
18507            }
18508        }
18509        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18510    }
18511
18512    @Override
18513    public void addPreferredActivity(IntentFilter filter, int match,
18514            ComponentName[] set, ComponentName activity, int userId) {
18515        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18516                "Adding preferred");
18517    }
18518
18519    private void addPreferredActivityInternal(IntentFilter filter, int match,
18520            ComponentName[] set, ComponentName activity, boolean always, int userId,
18521            String opname) {
18522        // writer
18523        int callingUid = Binder.getCallingUid();
18524        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18525                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18526        if (filter.countActions() == 0) {
18527            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18528            return;
18529        }
18530        synchronized (mPackages) {
18531            if (mContext.checkCallingOrSelfPermission(
18532                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18533                    != PackageManager.PERMISSION_GRANTED) {
18534                if (getUidTargetSdkVersionLockedLPr(callingUid)
18535                        < Build.VERSION_CODES.FROYO) {
18536                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18537                            + callingUid);
18538                    return;
18539                }
18540                mContext.enforceCallingOrSelfPermission(
18541                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18542            }
18543
18544            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18545            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18546                    + userId + ":");
18547            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18548            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18549            scheduleWritePackageRestrictionsLocked(userId);
18550            postPreferredActivityChangedBroadcast(userId);
18551        }
18552    }
18553
18554    private void postPreferredActivityChangedBroadcast(int userId) {
18555        mHandler.post(() -> {
18556            final IActivityManager am = ActivityManager.getService();
18557            if (am == null) {
18558                return;
18559            }
18560
18561            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18562            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18563            try {
18564                am.broadcastIntent(null, intent, null, null,
18565                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18566                        null, false, false, userId);
18567            } catch (RemoteException e) {
18568            }
18569        });
18570    }
18571
18572    @Override
18573    public void replacePreferredActivity(IntentFilter filter, int match,
18574            ComponentName[] set, ComponentName activity, int userId) {
18575        if (filter.countActions() != 1) {
18576            throw new IllegalArgumentException(
18577                    "replacePreferredActivity expects filter to have only 1 action.");
18578        }
18579        if (filter.countDataAuthorities() != 0
18580                || filter.countDataPaths() != 0
18581                || filter.countDataSchemes() > 1
18582                || filter.countDataTypes() != 0) {
18583            throw new IllegalArgumentException(
18584                    "replacePreferredActivity expects filter to have no data authorities, " +
18585                    "paths, or types; and at most one scheme.");
18586        }
18587
18588        final int callingUid = Binder.getCallingUid();
18589        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18590                true /* requireFullPermission */, false /* checkShell */,
18591                "replace preferred activity");
18592        synchronized (mPackages) {
18593            if (mContext.checkCallingOrSelfPermission(
18594                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18595                    != PackageManager.PERMISSION_GRANTED) {
18596                if (getUidTargetSdkVersionLockedLPr(callingUid)
18597                        < Build.VERSION_CODES.FROYO) {
18598                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18599                            + Binder.getCallingUid());
18600                    return;
18601                }
18602                mContext.enforceCallingOrSelfPermission(
18603                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18604            }
18605
18606            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18607            if (pir != null) {
18608                // Get all of the existing entries that exactly match this filter.
18609                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18610                if (existing != null && existing.size() == 1) {
18611                    PreferredActivity cur = existing.get(0);
18612                    if (DEBUG_PREFERRED) {
18613                        Slog.i(TAG, "Checking replace of preferred:");
18614                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18615                        if (!cur.mPref.mAlways) {
18616                            Slog.i(TAG, "  -- CUR; not mAlways!");
18617                        } else {
18618                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18619                            Slog.i(TAG, "  -- CUR: mSet="
18620                                    + Arrays.toString(cur.mPref.mSetComponents));
18621                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18622                            Slog.i(TAG, "  -- NEW: mMatch="
18623                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18624                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18625                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18626                        }
18627                    }
18628                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18629                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18630                            && cur.mPref.sameSet(set)) {
18631                        // Setting the preferred activity to what it happens to be already
18632                        if (DEBUG_PREFERRED) {
18633                            Slog.i(TAG, "Replacing with same preferred activity "
18634                                    + cur.mPref.mShortComponent + " for user "
18635                                    + userId + ":");
18636                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18637                        }
18638                        return;
18639                    }
18640                }
18641
18642                if (existing != null) {
18643                    if (DEBUG_PREFERRED) {
18644                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18645                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18646                    }
18647                    for (int i = 0; i < existing.size(); i++) {
18648                        PreferredActivity pa = existing.get(i);
18649                        if (DEBUG_PREFERRED) {
18650                            Slog.i(TAG, "Removing existing preferred activity "
18651                                    + pa.mPref.mComponent + ":");
18652                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18653                        }
18654                        pir.removeFilter(pa);
18655                    }
18656                }
18657            }
18658            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18659                    "Replacing preferred");
18660        }
18661    }
18662
18663    @Override
18664    public void clearPackagePreferredActivities(String packageName) {
18665        final int callingUid = Binder.getCallingUid();
18666        if (getInstantAppPackageName(callingUid) != null) {
18667            return;
18668        }
18669        // writer
18670        synchronized (mPackages) {
18671            PackageParser.Package pkg = mPackages.get(packageName);
18672            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
18673                if (mContext.checkCallingOrSelfPermission(
18674                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18675                        != PackageManager.PERMISSION_GRANTED) {
18676                    if (getUidTargetSdkVersionLockedLPr(callingUid)
18677                            < Build.VERSION_CODES.FROYO) {
18678                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18679                                + callingUid);
18680                        return;
18681                    }
18682                    mContext.enforceCallingOrSelfPermission(
18683                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18684                }
18685            }
18686            final PackageSetting ps = mSettings.getPackageLPr(packageName);
18687            if (ps != null
18688                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
18689                return;
18690            }
18691            int user = UserHandle.getCallingUserId();
18692            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18693                scheduleWritePackageRestrictionsLocked(user);
18694            }
18695        }
18696    }
18697
18698    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18699    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18700        ArrayList<PreferredActivity> removed = null;
18701        boolean changed = false;
18702        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18703            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18704            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18705            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18706                continue;
18707            }
18708            Iterator<PreferredActivity> it = pir.filterIterator();
18709            while (it.hasNext()) {
18710                PreferredActivity pa = it.next();
18711                // Mark entry for removal only if it matches the package name
18712                // and the entry is of type "always".
18713                if (packageName == null ||
18714                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18715                                && pa.mPref.mAlways)) {
18716                    if (removed == null) {
18717                        removed = new ArrayList<PreferredActivity>();
18718                    }
18719                    removed.add(pa);
18720                }
18721            }
18722            if (removed != null) {
18723                for (int j=0; j<removed.size(); j++) {
18724                    PreferredActivity pa = removed.get(j);
18725                    pir.removeFilter(pa);
18726                }
18727                changed = true;
18728            }
18729        }
18730        if (changed) {
18731            postPreferredActivityChangedBroadcast(userId);
18732        }
18733        return changed;
18734    }
18735
18736    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18737    private void clearIntentFilterVerificationsLPw(int userId) {
18738        final int packageCount = mPackages.size();
18739        for (int i = 0; i < packageCount; i++) {
18740            PackageParser.Package pkg = mPackages.valueAt(i);
18741            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18742        }
18743    }
18744
18745    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18746    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18747        if (userId == UserHandle.USER_ALL) {
18748            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18749                    sUserManager.getUserIds())) {
18750                for (int oneUserId : sUserManager.getUserIds()) {
18751                    scheduleWritePackageRestrictionsLocked(oneUserId);
18752                }
18753            }
18754        } else {
18755            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18756                scheduleWritePackageRestrictionsLocked(userId);
18757            }
18758        }
18759    }
18760
18761    /** Clears state for all users, and touches intent filter verification policy */
18762    void clearDefaultBrowserIfNeeded(String packageName) {
18763        for (int oneUserId : sUserManager.getUserIds()) {
18764            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
18765        }
18766    }
18767
18768    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
18769        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
18770        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
18771            if (packageName.equals(defaultBrowserPackageName)) {
18772                setDefaultBrowserPackageName(null, userId);
18773            }
18774        }
18775    }
18776
18777    @Override
18778    public void resetApplicationPreferences(int userId) {
18779        mContext.enforceCallingOrSelfPermission(
18780                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18781        final long identity = Binder.clearCallingIdentity();
18782        // writer
18783        try {
18784            synchronized (mPackages) {
18785                clearPackagePreferredActivitiesLPw(null, userId);
18786                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18787                // TODO: We have to reset the default SMS and Phone. This requires
18788                // significant refactoring to keep all default apps in the package
18789                // manager (cleaner but more work) or have the services provide
18790                // callbacks to the package manager to request a default app reset.
18791                applyFactoryDefaultBrowserLPw(userId);
18792                clearIntentFilterVerificationsLPw(userId);
18793                primeDomainVerificationsLPw(userId);
18794                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18795                scheduleWritePackageRestrictionsLocked(userId);
18796            }
18797            resetNetworkPolicies(userId);
18798        } finally {
18799            Binder.restoreCallingIdentity(identity);
18800        }
18801    }
18802
18803    @Override
18804    public int getPreferredActivities(List<IntentFilter> outFilters,
18805            List<ComponentName> outActivities, String packageName) {
18806        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
18807            return 0;
18808        }
18809        int num = 0;
18810        final int userId = UserHandle.getCallingUserId();
18811        // reader
18812        synchronized (mPackages) {
18813            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18814            if (pir != null) {
18815                final Iterator<PreferredActivity> it = pir.filterIterator();
18816                while (it.hasNext()) {
18817                    final PreferredActivity pa = it.next();
18818                    if (packageName == null
18819                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18820                                    && pa.mPref.mAlways)) {
18821                        if (outFilters != null) {
18822                            outFilters.add(new IntentFilter(pa));
18823                        }
18824                        if (outActivities != null) {
18825                            outActivities.add(pa.mPref.mComponent);
18826                        }
18827                    }
18828                }
18829            }
18830        }
18831
18832        return num;
18833    }
18834
18835    @Override
18836    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18837            int userId) {
18838        int callingUid = Binder.getCallingUid();
18839        if (callingUid != Process.SYSTEM_UID) {
18840            throw new SecurityException(
18841                    "addPersistentPreferredActivity can only be run by the system");
18842        }
18843        if (filter.countActions() == 0) {
18844            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18845            return;
18846        }
18847        synchronized (mPackages) {
18848            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18849                    ":");
18850            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18851            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18852                    new PersistentPreferredActivity(filter, activity));
18853            scheduleWritePackageRestrictionsLocked(userId);
18854            postPreferredActivityChangedBroadcast(userId);
18855        }
18856    }
18857
18858    @Override
18859    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18860        int callingUid = Binder.getCallingUid();
18861        if (callingUid != Process.SYSTEM_UID) {
18862            throw new SecurityException(
18863                    "clearPackagePersistentPreferredActivities can only be run by the system");
18864        }
18865        ArrayList<PersistentPreferredActivity> removed = null;
18866        boolean changed = false;
18867        synchronized (mPackages) {
18868            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18869                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18870                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18871                        .valueAt(i);
18872                if (userId != thisUserId) {
18873                    continue;
18874                }
18875                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18876                while (it.hasNext()) {
18877                    PersistentPreferredActivity ppa = it.next();
18878                    // Mark entry for removal only if it matches the package name.
18879                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18880                        if (removed == null) {
18881                            removed = new ArrayList<PersistentPreferredActivity>();
18882                        }
18883                        removed.add(ppa);
18884                    }
18885                }
18886                if (removed != null) {
18887                    for (int j=0; j<removed.size(); j++) {
18888                        PersistentPreferredActivity ppa = removed.get(j);
18889                        ppir.removeFilter(ppa);
18890                    }
18891                    changed = true;
18892                }
18893            }
18894
18895            if (changed) {
18896                scheduleWritePackageRestrictionsLocked(userId);
18897                postPreferredActivityChangedBroadcast(userId);
18898            }
18899        }
18900    }
18901
18902    /**
18903     * Common machinery for picking apart a restored XML blob and passing
18904     * it to a caller-supplied functor to be applied to the running system.
18905     */
18906    private void restoreFromXml(XmlPullParser parser, int userId,
18907            String expectedStartTag, BlobXmlRestorer functor)
18908            throws IOException, XmlPullParserException {
18909        int type;
18910        while ((type = parser.next()) != XmlPullParser.START_TAG
18911                && type != XmlPullParser.END_DOCUMENT) {
18912        }
18913        if (type != XmlPullParser.START_TAG) {
18914            // oops didn't find a start tag?!
18915            if (DEBUG_BACKUP) {
18916                Slog.e(TAG, "Didn't find start tag during restore");
18917            }
18918            return;
18919        }
18920Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18921        // this is supposed to be TAG_PREFERRED_BACKUP
18922        if (!expectedStartTag.equals(parser.getName())) {
18923            if (DEBUG_BACKUP) {
18924                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18925            }
18926            return;
18927        }
18928
18929        // skip interfering stuff, then we're aligned with the backing implementation
18930        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18931Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18932        functor.apply(parser, userId);
18933    }
18934
18935    private interface BlobXmlRestorer {
18936        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18937    }
18938
18939    /**
18940     * Non-Binder method, support for the backup/restore mechanism: write the
18941     * full set of preferred activities in its canonical XML format.  Returns the
18942     * XML output as a byte array, or null if there is none.
18943     */
18944    @Override
18945    public byte[] getPreferredActivityBackup(int userId) {
18946        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18947            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18948        }
18949
18950        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18951        try {
18952            final XmlSerializer serializer = new FastXmlSerializer();
18953            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18954            serializer.startDocument(null, true);
18955            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18956
18957            synchronized (mPackages) {
18958                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18959            }
18960
18961            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18962            serializer.endDocument();
18963            serializer.flush();
18964        } catch (Exception e) {
18965            if (DEBUG_BACKUP) {
18966                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18967            }
18968            return null;
18969        }
18970
18971        return dataStream.toByteArray();
18972    }
18973
18974    @Override
18975    public void restorePreferredActivities(byte[] backup, int userId) {
18976        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18977            throw new SecurityException("Only the system may call restorePreferredActivities()");
18978        }
18979
18980        try {
18981            final XmlPullParser parser = Xml.newPullParser();
18982            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18983            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18984                    new BlobXmlRestorer() {
18985                        @Override
18986                        public void apply(XmlPullParser parser, int userId)
18987                                throws XmlPullParserException, IOException {
18988                            synchronized (mPackages) {
18989                                mSettings.readPreferredActivitiesLPw(parser, userId);
18990                            }
18991                        }
18992                    } );
18993        } catch (Exception e) {
18994            if (DEBUG_BACKUP) {
18995                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18996            }
18997        }
18998    }
18999
19000    /**
19001     * Non-Binder method, support for the backup/restore mechanism: write the
19002     * default browser (etc) settings in its canonical XML format.  Returns the default
19003     * browser XML representation as a byte array, or null if there is none.
19004     */
19005    @Override
19006    public byte[] getDefaultAppsBackup(int userId) {
19007        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19008            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19009        }
19010
19011        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19012        try {
19013            final XmlSerializer serializer = new FastXmlSerializer();
19014            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19015            serializer.startDocument(null, true);
19016            serializer.startTag(null, TAG_DEFAULT_APPS);
19017
19018            synchronized (mPackages) {
19019                mSettings.writeDefaultAppsLPr(serializer, userId);
19020            }
19021
19022            serializer.endTag(null, TAG_DEFAULT_APPS);
19023            serializer.endDocument();
19024            serializer.flush();
19025        } catch (Exception e) {
19026            if (DEBUG_BACKUP) {
19027                Slog.e(TAG, "Unable to write default apps for backup", e);
19028            }
19029            return null;
19030        }
19031
19032        return dataStream.toByteArray();
19033    }
19034
19035    @Override
19036    public void restoreDefaultApps(byte[] backup, int userId) {
19037        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19038            throw new SecurityException("Only the system may call restoreDefaultApps()");
19039        }
19040
19041        try {
19042            final XmlPullParser parser = Xml.newPullParser();
19043            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19044            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19045                    new BlobXmlRestorer() {
19046                        @Override
19047                        public void apply(XmlPullParser parser, int userId)
19048                                throws XmlPullParserException, IOException {
19049                            synchronized (mPackages) {
19050                                mSettings.readDefaultAppsLPw(parser, userId);
19051                            }
19052                        }
19053                    } );
19054        } catch (Exception e) {
19055            if (DEBUG_BACKUP) {
19056                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19057            }
19058        }
19059    }
19060
19061    @Override
19062    public byte[] getIntentFilterVerificationBackup(int userId) {
19063        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19064            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19065        }
19066
19067        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19068        try {
19069            final XmlSerializer serializer = new FastXmlSerializer();
19070            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19071            serializer.startDocument(null, true);
19072            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19073
19074            synchronized (mPackages) {
19075                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19076            }
19077
19078            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19079            serializer.endDocument();
19080            serializer.flush();
19081        } catch (Exception e) {
19082            if (DEBUG_BACKUP) {
19083                Slog.e(TAG, "Unable to write default apps for backup", e);
19084            }
19085            return null;
19086        }
19087
19088        return dataStream.toByteArray();
19089    }
19090
19091    @Override
19092    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19093        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19094            throw new SecurityException("Only the system may call restorePreferredActivities()");
19095        }
19096
19097        try {
19098            final XmlPullParser parser = Xml.newPullParser();
19099            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19100            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19101                    new BlobXmlRestorer() {
19102                        @Override
19103                        public void apply(XmlPullParser parser, int userId)
19104                                throws XmlPullParserException, IOException {
19105                            synchronized (mPackages) {
19106                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19107                                mSettings.writeLPr();
19108                            }
19109                        }
19110                    } );
19111        } catch (Exception e) {
19112            if (DEBUG_BACKUP) {
19113                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19114            }
19115        }
19116    }
19117
19118    @Override
19119    public byte[] getPermissionGrantBackup(int userId) {
19120        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19121            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19122        }
19123
19124        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19125        try {
19126            final XmlSerializer serializer = new FastXmlSerializer();
19127            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19128            serializer.startDocument(null, true);
19129            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19130
19131            synchronized (mPackages) {
19132                serializeRuntimePermissionGrantsLPr(serializer, userId);
19133            }
19134
19135            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19136            serializer.endDocument();
19137            serializer.flush();
19138        } catch (Exception e) {
19139            if (DEBUG_BACKUP) {
19140                Slog.e(TAG, "Unable to write default apps for backup", e);
19141            }
19142            return null;
19143        }
19144
19145        return dataStream.toByteArray();
19146    }
19147
19148    @Override
19149    public void restorePermissionGrants(byte[] backup, int userId) {
19150        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19151            throw new SecurityException("Only the system may call restorePermissionGrants()");
19152        }
19153
19154        try {
19155            final XmlPullParser parser = Xml.newPullParser();
19156            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19157            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19158                    new BlobXmlRestorer() {
19159                        @Override
19160                        public void apply(XmlPullParser parser, int userId)
19161                                throws XmlPullParserException, IOException {
19162                            synchronized (mPackages) {
19163                                processRestoredPermissionGrantsLPr(parser, userId);
19164                            }
19165                        }
19166                    } );
19167        } catch (Exception e) {
19168            if (DEBUG_BACKUP) {
19169                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19170            }
19171        }
19172    }
19173
19174    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19175            throws IOException {
19176        serializer.startTag(null, TAG_ALL_GRANTS);
19177
19178        final int N = mSettings.mPackages.size();
19179        for (int i = 0; i < N; i++) {
19180            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19181            boolean pkgGrantsKnown = false;
19182
19183            PermissionsState packagePerms = ps.getPermissionsState();
19184
19185            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19186                final int grantFlags = state.getFlags();
19187                // only look at grants that are not system/policy fixed
19188                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19189                    final boolean isGranted = state.isGranted();
19190                    // And only back up the user-twiddled state bits
19191                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19192                        final String packageName = mSettings.mPackages.keyAt(i);
19193                        if (!pkgGrantsKnown) {
19194                            serializer.startTag(null, TAG_GRANT);
19195                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19196                            pkgGrantsKnown = true;
19197                        }
19198
19199                        final boolean userSet =
19200                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19201                        final boolean userFixed =
19202                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19203                        final boolean revoke =
19204                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19205
19206                        serializer.startTag(null, TAG_PERMISSION);
19207                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19208                        if (isGranted) {
19209                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19210                        }
19211                        if (userSet) {
19212                            serializer.attribute(null, ATTR_USER_SET, "true");
19213                        }
19214                        if (userFixed) {
19215                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19216                        }
19217                        if (revoke) {
19218                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19219                        }
19220                        serializer.endTag(null, TAG_PERMISSION);
19221                    }
19222                }
19223            }
19224
19225            if (pkgGrantsKnown) {
19226                serializer.endTag(null, TAG_GRANT);
19227            }
19228        }
19229
19230        serializer.endTag(null, TAG_ALL_GRANTS);
19231    }
19232
19233    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19234            throws XmlPullParserException, IOException {
19235        String pkgName = null;
19236        int outerDepth = parser.getDepth();
19237        int type;
19238        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19239                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19240            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19241                continue;
19242            }
19243
19244            final String tagName = parser.getName();
19245            if (tagName.equals(TAG_GRANT)) {
19246                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19247                if (DEBUG_BACKUP) {
19248                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19249                }
19250            } else if (tagName.equals(TAG_PERMISSION)) {
19251
19252                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19253                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19254
19255                int newFlagSet = 0;
19256                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19257                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19258                }
19259                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19260                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19261                }
19262                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19263                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19264                }
19265                if (DEBUG_BACKUP) {
19266                    Slog.v(TAG, "  + Restoring grant:"
19267                            + " pkg=" + pkgName
19268                            + " perm=" + permName
19269                            + " granted=" + isGranted
19270                            + " bits=0x" + Integer.toHexString(newFlagSet));
19271                }
19272                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19273                if (ps != null) {
19274                    // Already installed so we apply the grant immediately
19275                    if (DEBUG_BACKUP) {
19276                        Slog.v(TAG, "        + already installed; applying");
19277                    }
19278                    PermissionsState perms = ps.getPermissionsState();
19279                    BasePermission bp =
19280                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19281                    if (bp != null) {
19282                        if (isGranted) {
19283                            perms.grantRuntimePermission(bp, userId);
19284                        }
19285                        if (newFlagSet != 0) {
19286                            perms.updatePermissionFlags(
19287                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19288                        }
19289                    }
19290                } else {
19291                    // Need to wait for post-restore install to apply the grant
19292                    if (DEBUG_BACKUP) {
19293                        Slog.v(TAG, "        - not yet installed; saving for later");
19294                    }
19295                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19296                            isGranted, newFlagSet, userId);
19297                }
19298            } else {
19299                PackageManagerService.reportSettingsProblem(Log.WARN,
19300                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19301                XmlUtils.skipCurrentTag(parser);
19302            }
19303        }
19304
19305        scheduleWriteSettingsLocked();
19306        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19307    }
19308
19309    @Override
19310    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19311            int sourceUserId, int targetUserId, int flags) {
19312        mContext.enforceCallingOrSelfPermission(
19313                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19314        int callingUid = Binder.getCallingUid();
19315        enforceOwnerRights(ownerPackage, callingUid);
19316        PackageManagerServiceUtils.enforceShellRestriction(
19317                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19318        if (intentFilter.countActions() == 0) {
19319            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19320            return;
19321        }
19322        synchronized (mPackages) {
19323            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19324                    ownerPackage, targetUserId, flags);
19325            CrossProfileIntentResolver resolver =
19326                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19327            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19328            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19329            if (existing != null) {
19330                int size = existing.size();
19331                for (int i = 0; i < size; i++) {
19332                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19333                        return;
19334                    }
19335                }
19336            }
19337            resolver.addFilter(newFilter);
19338            scheduleWritePackageRestrictionsLocked(sourceUserId);
19339        }
19340    }
19341
19342    @Override
19343    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19344        mContext.enforceCallingOrSelfPermission(
19345                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19346        final int callingUid = Binder.getCallingUid();
19347        enforceOwnerRights(ownerPackage, callingUid);
19348        PackageManagerServiceUtils.enforceShellRestriction(
19349                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19350        synchronized (mPackages) {
19351            CrossProfileIntentResolver resolver =
19352                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19353            ArraySet<CrossProfileIntentFilter> set =
19354                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19355            for (CrossProfileIntentFilter filter : set) {
19356                if (filter.getOwnerPackage().equals(ownerPackage)) {
19357                    resolver.removeFilter(filter);
19358                }
19359            }
19360            scheduleWritePackageRestrictionsLocked(sourceUserId);
19361        }
19362    }
19363
19364    // Enforcing that callingUid is owning pkg on userId
19365    private void enforceOwnerRights(String pkg, int callingUid) {
19366        // The system owns everything.
19367        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19368            return;
19369        }
19370        final int callingUserId = UserHandle.getUserId(callingUid);
19371        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19372        if (pi == null) {
19373            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19374                    + callingUserId);
19375        }
19376        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19377            throw new SecurityException("Calling uid " + callingUid
19378                    + " does not own package " + pkg);
19379        }
19380    }
19381
19382    @Override
19383    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19384        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19385            return null;
19386        }
19387        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19388    }
19389
19390    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19391        UserManagerService ums = UserManagerService.getInstance();
19392        if (ums != null) {
19393            final UserInfo parent = ums.getProfileParent(userId);
19394            final int launcherUid = (parent != null) ? parent.id : userId;
19395            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19396            if (launcherComponent != null) {
19397                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19398                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19399                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19400                        .setPackage(launcherComponent.getPackageName());
19401                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19402            }
19403        }
19404    }
19405
19406    /**
19407     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19408     * then reports the most likely home activity or null if there are more than one.
19409     */
19410    private ComponentName getDefaultHomeActivity(int userId) {
19411        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19412        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19413        if (cn != null) {
19414            return cn;
19415        }
19416
19417        // Find the launcher with the highest priority and return that component if there are no
19418        // other home activity with the same priority.
19419        int lastPriority = Integer.MIN_VALUE;
19420        ComponentName lastComponent = null;
19421        final int size = allHomeCandidates.size();
19422        for (int i = 0; i < size; i++) {
19423            final ResolveInfo ri = allHomeCandidates.get(i);
19424            if (ri.priority > lastPriority) {
19425                lastComponent = ri.activityInfo.getComponentName();
19426                lastPriority = ri.priority;
19427            } else if (ri.priority == lastPriority) {
19428                // Two components found with same priority.
19429                lastComponent = null;
19430            }
19431        }
19432        return lastComponent;
19433    }
19434
19435    private Intent getHomeIntent() {
19436        Intent intent = new Intent(Intent.ACTION_MAIN);
19437        intent.addCategory(Intent.CATEGORY_HOME);
19438        intent.addCategory(Intent.CATEGORY_DEFAULT);
19439        return intent;
19440    }
19441
19442    private IntentFilter getHomeFilter() {
19443        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19444        filter.addCategory(Intent.CATEGORY_HOME);
19445        filter.addCategory(Intent.CATEGORY_DEFAULT);
19446        return filter;
19447    }
19448
19449    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19450            int userId) {
19451        Intent intent  = getHomeIntent();
19452        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19453                PackageManager.GET_META_DATA, userId);
19454        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19455                true, false, false, userId);
19456
19457        allHomeCandidates.clear();
19458        if (list != null) {
19459            for (ResolveInfo ri : list) {
19460                allHomeCandidates.add(ri);
19461            }
19462        }
19463        return (preferred == null || preferred.activityInfo == null)
19464                ? null
19465                : new ComponentName(preferred.activityInfo.packageName,
19466                        preferred.activityInfo.name);
19467    }
19468
19469    @Override
19470    public void setHomeActivity(ComponentName comp, int userId) {
19471        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19472            return;
19473        }
19474        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19475        getHomeActivitiesAsUser(homeActivities, userId);
19476
19477        boolean found = false;
19478
19479        final int size = homeActivities.size();
19480        final ComponentName[] set = new ComponentName[size];
19481        for (int i = 0; i < size; i++) {
19482            final ResolveInfo candidate = homeActivities.get(i);
19483            final ActivityInfo info = candidate.activityInfo;
19484            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19485            set[i] = activityName;
19486            if (!found && activityName.equals(comp)) {
19487                found = true;
19488            }
19489        }
19490        if (!found) {
19491            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19492                    + userId);
19493        }
19494        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19495                set, comp, userId);
19496    }
19497
19498    private @Nullable String getSetupWizardPackageName() {
19499        final Intent intent = new Intent(Intent.ACTION_MAIN);
19500        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19501
19502        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19503                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19504                        | MATCH_DISABLED_COMPONENTS,
19505                UserHandle.myUserId());
19506        if (matches.size() == 1) {
19507            return matches.get(0).getComponentInfo().packageName;
19508        } else {
19509            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19510                    + ": matches=" + matches);
19511            return null;
19512        }
19513    }
19514
19515    private @Nullable String getStorageManagerPackageName() {
19516        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19517
19518        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19519                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19520                        | MATCH_DISABLED_COMPONENTS,
19521                UserHandle.myUserId());
19522        if (matches.size() == 1) {
19523            return matches.get(0).getComponentInfo().packageName;
19524        } else {
19525            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19526                    + matches.size() + ": matches=" + matches);
19527            return null;
19528        }
19529    }
19530
19531    @Override
19532    public void setApplicationEnabledSetting(String appPackageName,
19533            int newState, int flags, int userId, String callingPackage) {
19534        if (!sUserManager.exists(userId)) return;
19535        if (callingPackage == null) {
19536            callingPackage = Integer.toString(Binder.getCallingUid());
19537        }
19538        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19539    }
19540
19541    @Override
19542    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19543        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19544        synchronized (mPackages) {
19545            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19546            if (pkgSetting != null) {
19547                pkgSetting.setUpdateAvailable(updateAvailable);
19548            }
19549        }
19550    }
19551
19552    @Override
19553    public void setComponentEnabledSetting(ComponentName componentName,
19554            int newState, int flags, int userId) {
19555        if (!sUserManager.exists(userId)) return;
19556        setEnabledSetting(componentName.getPackageName(),
19557                componentName.getClassName(), newState, flags, userId, null);
19558    }
19559
19560    private void setEnabledSetting(final String packageName, String className, int newState,
19561            final int flags, int userId, String callingPackage) {
19562        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19563              || newState == COMPONENT_ENABLED_STATE_ENABLED
19564              || newState == COMPONENT_ENABLED_STATE_DISABLED
19565              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19566              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19567            throw new IllegalArgumentException("Invalid new component state: "
19568                    + newState);
19569        }
19570        PackageSetting pkgSetting;
19571        final int callingUid = Binder.getCallingUid();
19572        final int permission;
19573        if (callingUid == Process.SYSTEM_UID) {
19574            permission = PackageManager.PERMISSION_GRANTED;
19575        } else {
19576            permission = mContext.checkCallingOrSelfPermission(
19577                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19578        }
19579        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19580                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19581        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19582        boolean sendNow = false;
19583        boolean isApp = (className == null);
19584        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19585        String componentName = isApp ? packageName : className;
19586        int packageUid = -1;
19587        ArrayList<String> components;
19588
19589        // reader
19590        synchronized (mPackages) {
19591            pkgSetting = mSettings.mPackages.get(packageName);
19592            if (pkgSetting == null) {
19593                if (!isCallerInstantApp) {
19594                    if (className == null) {
19595                        throw new IllegalArgumentException("Unknown package: " + packageName);
19596                    }
19597                    throw new IllegalArgumentException(
19598                            "Unknown component: " + packageName + "/" + className);
19599                } else {
19600                    // throw SecurityException to prevent leaking package information
19601                    throw new SecurityException(
19602                            "Attempt to change component state; "
19603                            + "pid=" + Binder.getCallingPid()
19604                            + ", uid=" + callingUid
19605                            + (className == null
19606                                    ? ", package=" + packageName
19607                                    : ", component=" + packageName + "/" + className));
19608                }
19609            }
19610        }
19611
19612        // Limit who can change which apps
19613        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
19614            // Don't allow apps that don't have permission to modify other apps
19615            if (!allowedByPermission
19616                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
19617                throw new SecurityException(
19618                        "Attempt to change component state; "
19619                        + "pid=" + Binder.getCallingPid()
19620                        + ", uid=" + callingUid
19621                        + (className == null
19622                                ? ", package=" + packageName
19623                                : ", component=" + packageName + "/" + className));
19624            }
19625            // Don't allow changing protected packages.
19626            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19627                throw new SecurityException("Cannot disable a protected package: " + packageName);
19628            }
19629        }
19630
19631        synchronized (mPackages) {
19632            if (callingUid == Process.SHELL_UID
19633                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19634                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19635                // unless it is a test package.
19636                int oldState = pkgSetting.getEnabled(userId);
19637                if (className == null
19638                        &&
19639                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19640                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19641                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19642                        &&
19643                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19644                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
19645                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19646                    // ok
19647                } else {
19648                    throw new SecurityException(
19649                            "Shell cannot change component state for " + packageName + "/"
19650                                    + className + " to " + newState);
19651                }
19652            }
19653        }
19654        if (className == null) {
19655            // We're dealing with an application/package level state change
19656            synchronized (mPackages) {
19657                if (pkgSetting.getEnabled(userId) == newState) {
19658                    // Nothing to do
19659                    return;
19660                }
19661            }
19662            // If we're enabling a system stub, there's a little more work to do.
19663            // Prior to enabling the package, we need to decompress the APK(s) to the
19664            // data partition and then replace the version on the system partition.
19665            final PackageParser.Package deletedPkg = pkgSetting.pkg;
19666            final boolean isSystemStub = deletedPkg.isStub
19667                    && deletedPkg.isSystem();
19668            if (isSystemStub
19669                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19670                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
19671                final File codePath = decompressPackage(deletedPkg);
19672                if (codePath == null) {
19673                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
19674                    return;
19675                }
19676                // TODO remove direct parsing of the package object during internal cleanup
19677                // of scan package
19678                // We need to call parse directly here for no other reason than we need
19679                // the new package in order to disable the old one [we use the information
19680                // for some internal optimization to optionally create a new package setting
19681                // object on replace]. However, we can't get the package from the scan
19682                // because the scan modifies live structures and we need to remove the
19683                // old [system] package from the system before a scan can be attempted.
19684                // Once scan is indempotent we can remove this parse and use the package
19685                // object we scanned, prior to adding it to package settings.
19686                final PackageParser pp = new PackageParser();
19687                pp.setSeparateProcesses(mSeparateProcesses);
19688                pp.setDisplayMetrics(mMetrics);
19689                pp.setCallback(mPackageParserCallback);
19690                final PackageParser.Package tmpPkg;
19691                try {
19692                    final @ParseFlags int parseFlags = mDefParseFlags
19693                            | PackageParser.PARSE_MUST_BE_APK
19694                            | PackageParser.PARSE_IS_SYSTEM_DIR;
19695                    tmpPkg = pp.parsePackage(codePath, parseFlags);
19696                } catch (PackageParserException e) {
19697                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
19698                    return;
19699                }
19700                synchronized (mInstallLock) {
19701                    // Disable the stub and remove any package entries
19702                    removePackageLI(deletedPkg, true);
19703                    synchronized (mPackages) {
19704                        disableSystemPackageLPw(deletedPkg, tmpPkg);
19705                    }
19706                    final PackageParser.Package pkg;
19707                    try (PackageFreezer freezer =
19708                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19709                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
19710                                | PackageParser.PARSE_ENFORCE_CODE;
19711                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
19712                                0 /*currentTime*/, null /*user*/);
19713                        prepareAppDataAfterInstallLIF(pkg);
19714                        synchronized (mPackages) {
19715                            try {
19716                                updateSharedLibrariesLPr(pkg, null);
19717                            } catch (PackageManagerException e) {
19718                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
19719                            }
19720                            mPermissionManager.updatePermissions(
19721                                    pkg.packageName, pkg, true, mPackages.values(),
19722                                    mPermissionCallback);
19723                            mSettings.writeLPr();
19724                        }
19725                    } catch (PackageManagerException e) {
19726                        // Whoops! Something went wrong; try to roll back to the stub
19727                        Slog.w(TAG, "Failed to install compressed system package:"
19728                                + pkgSetting.name, e);
19729                        // Remove the failed install
19730                        removeCodePathLI(codePath);
19731
19732                        // Install the system package
19733                        try (PackageFreezer freezer =
19734                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19735                            synchronized (mPackages) {
19736                                // NOTE: The system package always needs to be enabled; even
19737                                // if it's for a compressed stub. If we don't, installing the
19738                                // system package fails during scan [scanning checks the disabled
19739                                // packages]. We will reverse this later, after we've "installed"
19740                                // the stub.
19741                                // This leaves us in a fragile state; the stub should never be
19742                                // enabled, so, cross your fingers and hope nothing goes wrong
19743                                // until we can disable the package later.
19744                                enableSystemPackageLPw(deletedPkg);
19745                            }
19746                            installPackageFromSystemLIF(deletedPkg.codePath,
19747                                    false /*isPrivileged*/, null /*allUserHandles*/,
19748                                    null /*origUserHandles*/, null /*origPermissionsState*/,
19749                                    true /*writeSettings*/);
19750                        } catch (PackageManagerException pme) {
19751                            Slog.w(TAG, "Failed to restore system package:"
19752                                    + deletedPkg.packageName, pme);
19753                        } finally {
19754                            synchronized (mPackages) {
19755                                mSettings.disableSystemPackageLPw(
19756                                        deletedPkg.packageName, true /*replaced*/);
19757                                mSettings.writeLPr();
19758                            }
19759                        }
19760                        return;
19761                    }
19762                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
19763                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19764                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19765                    mDexManager.notifyPackageUpdated(pkg.packageName,
19766                            pkg.baseCodePath, pkg.splitCodePaths);
19767                }
19768            }
19769            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19770                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19771                // Don't care about who enables an app.
19772                callingPackage = null;
19773            }
19774            synchronized (mPackages) {
19775                pkgSetting.setEnabled(newState, userId, callingPackage);
19776            }
19777        } else {
19778            synchronized (mPackages) {
19779                // We're dealing with a component level state change
19780                // First, verify that this is a valid class name.
19781                PackageParser.Package pkg = pkgSetting.pkg;
19782                if (pkg == null || !pkg.hasComponentClassName(className)) {
19783                    if (pkg != null &&
19784                            pkg.applicationInfo.targetSdkVersion >=
19785                                    Build.VERSION_CODES.JELLY_BEAN) {
19786                        throw new IllegalArgumentException("Component class " + className
19787                                + " does not exist in " + packageName);
19788                    } else {
19789                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19790                                + className + " does not exist in " + packageName);
19791                    }
19792                }
19793                switch (newState) {
19794                    case COMPONENT_ENABLED_STATE_ENABLED:
19795                        if (!pkgSetting.enableComponentLPw(className, userId)) {
19796                            return;
19797                        }
19798                        break;
19799                    case COMPONENT_ENABLED_STATE_DISABLED:
19800                        if (!pkgSetting.disableComponentLPw(className, userId)) {
19801                            return;
19802                        }
19803                        break;
19804                    case COMPONENT_ENABLED_STATE_DEFAULT:
19805                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
19806                            return;
19807                        }
19808                        break;
19809                    default:
19810                        Slog.e(TAG, "Invalid new component state: " + newState);
19811                        return;
19812                }
19813            }
19814        }
19815        synchronized (mPackages) {
19816            scheduleWritePackageRestrictionsLocked(userId);
19817            updateSequenceNumberLP(pkgSetting, new int[] { userId });
19818            final long callingId = Binder.clearCallingIdentity();
19819            try {
19820                updateInstantAppInstallerLocked(packageName);
19821            } finally {
19822                Binder.restoreCallingIdentity(callingId);
19823            }
19824            components = mPendingBroadcasts.get(userId, packageName);
19825            final boolean newPackage = components == null;
19826            if (newPackage) {
19827                components = new ArrayList<String>();
19828            }
19829            if (!components.contains(componentName)) {
19830                components.add(componentName);
19831            }
19832            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19833                sendNow = true;
19834                // Purge entry from pending broadcast list if another one exists already
19835                // since we are sending one right away.
19836                mPendingBroadcasts.remove(userId, packageName);
19837            } else {
19838                if (newPackage) {
19839                    mPendingBroadcasts.put(userId, packageName, components);
19840                }
19841                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19842                    // Schedule a message
19843                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19844                }
19845            }
19846        }
19847
19848        long callingId = Binder.clearCallingIdentity();
19849        try {
19850            if (sendNow) {
19851                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19852                sendPackageChangedBroadcast(packageName,
19853                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19854            }
19855        } finally {
19856            Binder.restoreCallingIdentity(callingId);
19857        }
19858    }
19859
19860    @Override
19861    public void flushPackageRestrictionsAsUser(int userId) {
19862        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19863            return;
19864        }
19865        if (!sUserManager.exists(userId)) {
19866            return;
19867        }
19868        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19869                false /* checkShell */, "flushPackageRestrictions");
19870        synchronized (mPackages) {
19871            mSettings.writePackageRestrictionsLPr(userId);
19872            mDirtyUsers.remove(userId);
19873            if (mDirtyUsers.isEmpty()) {
19874                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19875            }
19876        }
19877    }
19878
19879    private void sendPackageChangedBroadcast(String packageName,
19880            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19881        if (DEBUG_INSTALL)
19882            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19883                    + componentNames);
19884        Bundle extras = new Bundle(4);
19885        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19886        String nameList[] = new String[componentNames.size()];
19887        componentNames.toArray(nameList);
19888        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19889        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19890        extras.putInt(Intent.EXTRA_UID, packageUid);
19891        // If this is not reporting a change of the overall package, then only send it
19892        // to registered receivers.  We don't want to launch a swath of apps for every
19893        // little component state change.
19894        final int flags = !componentNames.contains(packageName)
19895                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19896        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19897                new int[] {UserHandle.getUserId(packageUid)});
19898    }
19899
19900    @Override
19901    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19902        if (!sUserManager.exists(userId)) return;
19903        final int callingUid = Binder.getCallingUid();
19904        if (getInstantAppPackageName(callingUid) != null) {
19905            return;
19906        }
19907        final int permission = mContext.checkCallingOrSelfPermission(
19908                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19909        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19910        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19911                true /* requireFullPermission */, true /* checkShell */, "stop package");
19912        // writer
19913        synchronized (mPackages) {
19914            final PackageSetting ps = mSettings.mPackages.get(packageName);
19915            if (!filterAppAccessLPr(ps, callingUid, userId)
19916                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19917                            allowedByPermission, callingUid, userId)) {
19918                scheduleWritePackageRestrictionsLocked(userId);
19919            }
19920        }
19921    }
19922
19923    @Override
19924    public String getInstallerPackageName(String packageName) {
19925        final int callingUid = Binder.getCallingUid();
19926        if (getInstantAppPackageName(callingUid) != null) {
19927            return null;
19928        }
19929        // reader
19930        synchronized (mPackages) {
19931            final PackageSetting ps = mSettings.mPackages.get(packageName);
19932            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19933                return null;
19934            }
19935            return mSettings.getInstallerPackageNameLPr(packageName);
19936        }
19937    }
19938
19939    public boolean isOrphaned(String packageName) {
19940        // reader
19941        synchronized (mPackages) {
19942            return mSettings.isOrphaned(packageName);
19943        }
19944    }
19945
19946    @Override
19947    public int getApplicationEnabledSetting(String packageName, int userId) {
19948        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19949        int callingUid = Binder.getCallingUid();
19950        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19951                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19952        // reader
19953        synchronized (mPackages) {
19954            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
19955                return COMPONENT_ENABLED_STATE_DISABLED;
19956            }
19957            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19958        }
19959    }
19960
19961    @Override
19962    public int getComponentEnabledSetting(ComponentName component, int userId) {
19963        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19964        int callingUid = Binder.getCallingUid();
19965        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19966                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
19967        synchronized (mPackages) {
19968            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
19969                    component, TYPE_UNKNOWN, userId)) {
19970                return COMPONENT_ENABLED_STATE_DISABLED;
19971            }
19972            return mSettings.getComponentEnabledSettingLPr(component, userId);
19973        }
19974    }
19975
19976    @Override
19977    public void enterSafeMode() {
19978        enforceSystemOrRoot("Only the system can request entering safe mode");
19979
19980        if (!mSystemReady) {
19981            mSafeMode = true;
19982        }
19983    }
19984
19985    @Override
19986    public void systemReady() {
19987        enforceSystemOrRoot("Only the system can claim the system is ready");
19988
19989        mSystemReady = true;
19990        final ContentResolver resolver = mContext.getContentResolver();
19991        ContentObserver co = new ContentObserver(mHandler) {
19992            @Override
19993            public void onChange(boolean selfChange) {
19994                mEphemeralAppsDisabled =
19995                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
19996                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
19997            }
19998        };
19999        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20000                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20001                false, co, UserHandle.USER_SYSTEM);
20002        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20003                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20004        co.onChange(true);
20005
20006        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20007        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20008        // it is done.
20009        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20010            @Override
20011            public void onChange(boolean selfChange) {
20012                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20013                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20014                        oobEnabled == 1 ? "true" : "false");
20015            }
20016        };
20017        mContext.getContentResolver().registerContentObserver(
20018                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20019                UserHandle.USER_SYSTEM);
20020        // At boot, restore the value from the setting, which persists across reboot.
20021        privAppOobObserver.onChange(true);
20022
20023        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20024        // disabled after already being started.
20025        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20026                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20027
20028        // Read the compatibilty setting when the system is ready.
20029        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20030                mContext.getContentResolver(),
20031                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20032        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20033        if (DEBUG_SETTINGS) {
20034            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20035        }
20036
20037        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20038
20039        synchronized (mPackages) {
20040            // Verify that all of the preferred activity components actually
20041            // exist.  It is possible for applications to be updated and at
20042            // that point remove a previously declared activity component that
20043            // had been set as a preferred activity.  We try to clean this up
20044            // the next time we encounter that preferred activity, but it is
20045            // possible for the user flow to never be able to return to that
20046            // situation so here we do a sanity check to make sure we haven't
20047            // left any junk around.
20048            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20049            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20050                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20051                removed.clear();
20052                for (PreferredActivity pa : pir.filterSet()) {
20053                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20054                        removed.add(pa);
20055                    }
20056                }
20057                if (removed.size() > 0) {
20058                    for (int r=0; r<removed.size(); r++) {
20059                        PreferredActivity pa = removed.get(r);
20060                        Slog.w(TAG, "Removing dangling preferred activity: "
20061                                + pa.mPref.mComponent);
20062                        pir.removeFilter(pa);
20063                    }
20064                    mSettings.writePackageRestrictionsLPr(
20065                            mSettings.mPreferredActivities.keyAt(i));
20066                }
20067            }
20068
20069            for (int userId : UserManagerService.getInstance().getUserIds()) {
20070                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20071                    grantPermissionsUserIds = ArrayUtils.appendInt(
20072                            grantPermissionsUserIds, userId);
20073                }
20074            }
20075        }
20076        sUserManager.systemReady();
20077
20078        // If we upgraded grant all default permissions before kicking off.
20079        for (int userId : grantPermissionsUserIds) {
20080            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
20081        }
20082
20083        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20084            // If we did not grant default permissions, we preload from this the
20085            // default permission exceptions lazily to ensure we don't hit the
20086            // disk on a new user creation.
20087            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20088        }
20089
20090        // Now that we've scanned all packages, and granted any default
20091        // permissions, ensure permissions are updated. Beware of dragons if you
20092        // try optimizing this.
20093        synchronized (mPackages) {
20094            mPermissionManager.updateAllPermissions(
20095                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20096                    mPermissionCallback);
20097        }
20098
20099        // Kick off any messages waiting for system ready
20100        if (mPostSystemReadyMessages != null) {
20101            for (Message msg : mPostSystemReadyMessages) {
20102                msg.sendToTarget();
20103            }
20104            mPostSystemReadyMessages = null;
20105        }
20106
20107        // Watch for external volumes that come and go over time
20108        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20109        storage.registerListener(mStorageListener);
20110
20111        mInstallerService.systemReady();
20112        mPackageDexOptimizer.systemReady();
20113
20114        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20115                StorageManagerInternal.class);
20116        StorageManagerInternal.addExternalStoragePolicy(
20117                new StorageManagerInternal.ExternalStorageMountPolicy() {
20118            @Override
20119            public int getMountMode(int uid, String packageName) {
20120                if (Process.isIsolated(uid)) {
20121                    return Zygote.MOUNT_EXTERNAL_NONE;
20122                }
20123                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20124                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20125                }
20126                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20127                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20128                }
20129                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20130                    return Zygote.MOUNT_EXTERNAL_READ;
20131                }
20132                return Zygote.MOUNT_EXTERNAL_WRITE;
20133            }
20134
20135            @Override
20136            public boolean hasExternalStorage(int uid, String packageName) {
20137                return true;
20138            }
20139        });
20140
20141        // Now that we're mostly running, clean up stale users and apps
20142        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20143        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20144
20145        mPermissionManager.systemReady();
20146    }
20147
20148    public void waitForAppDataPrepared() {
20149        if (mPrepareAppDataFuture == null) {
20150            return;
20151        }
20152        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20153        mPrepareAppDataFuture = null;
20154    }
20155
20156    @Override
20157    public boolean isSafeMode() {
20158        // allow instant applications
20159        return mSafeMode;
20160    }
20161
20162    @Override
20163    public boolean hasSystemUidErrors() {
20164        // allow instant applications
20165        return mHasSystemUidErrors;
20166    }
20167
20168    static String arrayToString(int[] array) {
20169        StringBuffer buf = new StringBuffer(128);
20170        buf.append('[');
20171        if (array != null) {
20172            for (int i=0; i<array.length; i++) {
20173                if (i > 0) buf.append(", ");
20174                buf.append(array[i]);
20175            }
20176        }
20177        buf.append(']');
20178        return buf.toString();
20179    }
20180
20181    @Override
20182    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20183            FileDescriptor err, String[] args, ShellCallback callback,
20184            ResultReceiver resultReceiver) {
20185        (new PackageManagerShellCommand(this)).exec(
20186                this, in, out, err, args, callback, resultReceiver);
20187    }
20188
20189    @Override
20190    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20191        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20192
20193        DumpState dumpState = new DumpState();
20194        boolean fullPreferred = false;
20195        boolean checkin = false;
20196
20197        String packageName = null;
20198        ArraySet<String> permissionNames = null;
20199
20200        int opti = 0;
20201        while (opti < args.length) {
20202            String opt = args[opti];
20203            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20204                break;
20205            }
20206            opti++;
20207
20208            if ("-a".equals(opt)) {
20209                // Right now we only know how to print all.
20210            } else if ("-h".equals(opt)) {
20211                pw.println("Package manager dump options:");
20212                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20213                pw.println("    --checkin: dump for a checkin");
20214                pw.println("    -f: print details of intent filters");
20215                pw.println("    -h: print this help");
20216                pw.println("  cmd may be one of:");
20217                pw.println("    l[ibraries]: list known shared libraries");
20218                pw.println("    f[eatures]: list device features");
20219                pw.println("    k[eysets]: print known keysets");
20220                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20221                pw.println("    perm[issions]: dump permissions");
20222                pw.println("    permission [name ...]: dump declaration and use of given permission");
20223                pw.println("    pref[erred]: print preferred package settings");
20224                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20225                pw.println("    prov[iders]: dump content providers");
20226                pw.println("    p[ackages]: dump installed packages");
20227                pw.println("    s[hared-users]: dump shared user IDs");
20228                pw.println("    m[essages]: print collected runtime messages");
20229                pw.println("    v[erifiers]: print package verifier info");
20230                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20231                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20232                pw.println("    version: print database version info");
20233                pw.println("    write: write current settings now");
20234                pw.println("    installs: details about install sessions");
20235                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20236                pw.println("    dexopt: dump dexopt state");
20237                pw.println("    compiler-stats: dump compiler statistics");
20238                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20239                pw.println("    <package.name>: info about given package");
20240                return;
20241            } else if ("--checkin".equals(opt)) {
20242                checkin = true;
20243            } else if ("-f".equals(opt)) {
20244                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20245            } else if ("--proto".equals(opt)) {
20246                dumpProto(fd);
20247                return;
20248            } else {
20249                pw.println("Unknown argument: " + opt + "; use -h for help");
20250            }
20251        }
20252
20253        // Is the caller requesting to dump a particular piece of data?
20254        if (opti < args.length) {
20255            String cmd = args[opti];
20256            opti++;
20257            // Is this a package name?
20258            if ("android".equals(cmd) || cmd.contains(".")) {
20259                packageName = cmd;
20260                // When dumping a single package, we always dump all of its
20261                // filter information since the amount of data will be reasonable.
20262                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20263            } else if ("check-permission".equals(cmd)) {
20264                if (opti >= args.length) {
20265                    pw.println("Error: check-permission missing permission argument");
20266                    return;
20267                }
20268                String perm = args[opti];
20269                opti++;
20270                if (opti >= args.length) {
20271                    pw.println("Error: check-permission missing package argument");
20272                    return;
20273                }
20274
20275                String pkg = args[opti];
20276                opti++;
20277                int user = UserHandle.getUserId(Binder.getCallingUid());
20278                if (opti < args.length) {
20279                    try {
20280                        user = Integer.parseInt(args[opti]);
20281                    } catch (NumberFormatException e) {
20282                        pw.println("Error: check-permission user argument is not a number: "
20283                                + args[opti]);
20284                        return;
20285                    }
20286                }
20287
20288                // Normalize package name to handle renamed packages and static libs
20289                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20290
20291                pw.println(checkPermission(perm, pkg, user));
20292                return;
20293            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20294                dumpState.setDump(DumpState.DUMP_LIBS);
20295            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20296                dumpState.setDump(DumpState.DUMP_FEATURES);
20297            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20298                if (opti >= args.length) {
20299                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20300                            | DumpState.DUMP_SERVICE_RESOLVERS
20301                            | DumpState.DUMP_RECEIVER_RESOLVERS
20302                            | DumpState.DUMP_CONTENT_RESOLVERS);
20303                } else {
20304                    while (opti < args.length) {
20305                        String name = args[opti];
20306                        if ("a".equals(name) || "activity".equals(name)) {
20307                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20308                        } else if ("s".equals(name) || "service".equals(name)) {
20309                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20310                        } else if ("r".equals(name) || "receiver".equals(name)) {
20311                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20312                        } else if ("c".equals(name) || "content".equals(name)) {
20313                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20314                        } else {
20315                            pw.println("Error: unknown resolver table type: " + name);
20316                            return;
20317                        }
20318                        opti++;
20319                    }
20320                }
20321            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20322                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20323            } else if ("permission".equals(cmd)) {
20324                if (opti >= args.length) {
20325                    pw.println("Error: permission requires permission name");
20326                    return;
20327                }
20328                permissionNames = new ArraySet<>();
20329                while (opti < args.length) {
20330                    permissionNames.add(args[opti]);
20331                    opti++;
20332                }
20333                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20334                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20335            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20336                dumpState.setDump(DumpState.DUMP_PREFERRED);
20337            } else if ("preferred-xml".equals(cmd)) {
20338                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20339                if (opti < args.length && "--full".equals(args[opti])) {
20340                    fullPreferred = true;
20341                    opti++;
20342                }
20343            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20344                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20345            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20346                dumpState.setDump(DumpState.DUMP_PACKAGES);
20347            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20348                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20349            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20350                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20351            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20352                dumpState.setDump(DumpState.DUMP_MESSAGES);
20353            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20354                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20355            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20356                    || "intent-filter-verifiers".equals(cmd)) {
20357                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20358            } else if ("version".equals(cmd)) {
20359                dumpState.setDump(DumpState.DUMP_VERSION);
20360            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20361                dumpState.setDump(DumpState.DUMP_KEYSETS);
20362            } else if ("installs".equals(cmd)) {
20363                dumpState.setDump(DumpState.DUMP_INSTALLS);
20364            } else if ("frozen".equals(cmd)) {
20365                dumpState.setDump(DumpState.DUMP_FROZEN);
20366            } else if ("volumes".equals(cmd)) {
20367                dumpState.setDump(DumpState.DUMP_VOLUMES);
20368            } else if ("dexopt".equals(cmd)) {
20369                dumpState.setDump(DumpState.DUMP_DEXOPT);
20370            } else if ("compiler-stats".equals(cmd)) {
20371                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20372            } else if ("changes".equals(cmd)) {
20373                dumpState.setDump(DumpState.DUMP_CHANGES);
20374            } else if ("write".equals(cmd)) {
20375                synchronized (mPackages) {
20376                    mSettings.writeLPr();
20377                    pw.println("Settings written.");
20378                    return;
20379                }
20380            }
20381        }
20382
20383        if (checkin) {
20384            pw.println("vers,1");
20385        }
20386
20387        // reader
20388        synchronized (mPackages) {
20389            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20390                if (!checkin) {
20391                    if (dumpState.onTitlePrinted())
20392                        pw.println();
20393                    pw.println("Database versions:");
20394                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20395                }
20396            }
20397
20398            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20399                if (!checkin) {
20400                    if (dumpState.onTitlePrinted())
20401                        pw.println();
20402                    pw.println("Verifiers:");
20403                    pw.print("  Required: ");
20404                    pw.print(mRequiredVerifierPackage);
20405                    pw.print(" (uid=");
20406                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20407                            UserHandle.USER_SYSTEM));
20408                    pw.println(")");
20409                } else if (mRequiredVerifierPackage != null) {
20410                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20411                    pw.print(",");
20412                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20413                            UserHandle.USER_SYSTEM));
20414                }
20415            }
20416
20417            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20418                    packageName == null) {
20419                if (mIntentFilterVerifierComponent != null) {
20420                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20421                    if (!checkin) {
20422                        if (dumpState.onTitlePrinted())
20423                            pw.println();
20424                        pw.println("Intent Filter Verifier:");
20425                        pw.print("  Using: ");
20426                        pw.print(verifierPackageName);
20427                        pw.print(" (uid=");
20428                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20429                                UserHandle.USER_SYSTEM));
20430                        pw.println(")");
20431                    } else if (verifierPackageName != null) {
20432                        pw.print("ifv,"); pw.print(verifierPackageName);
20433                        pw.print(",");
20434                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20435                                UserHandle.USER_SYSTEM));
20436                    }
20437                } else {
20438                    pw.println();
20439                    pw.println("No Intent Filter Verifier available!");
20440                }
20441            }
20442
20443            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20444                boolean printedHeader = false;
20445                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20446                while (it.hasNext()) {
20447                    String libName = it.next();
20448                    LongSparseArray<SharedLibraryEntry> versionedLib
20449                            = mSharedLibraries.get(libName);
20450                    if (versionedLib == null) {
20451                        continue;
20452                    }
20453                    final int versionCount = versionedLib.size();
20454                    for (int i = 0; i < versionCount; i++) {
20455                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20456                        if (!checkin) {
20457                            if (!printedHeader) {
20458                                if (dumpState.onTitlePrinted())
20459                                    pw.println();
20460                                pw.println("Libraries:");
20461                                printedHeader = true;
20462                            }
20463                            pw.print("  ");
20464                        } else {
20465                            pw.print("lib,");
20466                        }
20467                        pw.print(libEntry.info.getName());
20468                        if (libEntry.info.isStatic()) {
20469                            pw.print(" version=" + libEntry.info.getLongVersion());
20470                        }
20471                        if (!checkin) {
20472                            pw.print(" -> ");
20473                        }
20474                        if (libEntry.path != null) {
20475                            pw.print(" (jar) ");
20476                            pw.print(libEntry.path);
20477                        } else {
20478                            pw.print(" (apk) ");
20479                            pw.print(libEntry.apk);
20480                        }
20481                        pw.println();
20482                    }
20483                }
20484            }
20485
20486            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20487                if (dumpState.onTitlePrinted())
20488                    pw.println();
20489                if (!checkin) {
20490                    pw.println("Features:");
20491                }
20492
20493                synchronized (mAvailableFeatures) {
20494                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20495                        if (checkin) {
20496                            pw.print("feat,");
20497                            pw.print(feat.name);
20498                            pw.print(",");
20499                            pw.println(feat.version);
20500                        } else {
20501                            pw.print("  ");
20502                            pw.print(feat.name);
20503                            if (feat.version > 0) {
20504                                pw.print(" version=");
20505                                pw.print(feat.version);
20506                            }
20507                            pw.println();
20508                        }
20509                    }
20510                }
20511            }
20512
20513            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20514                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20515                        : "Activity Resolver Table:", "  ", packageName,
20516                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20517                    dumpState.setTitlePrinted(true);
20518                }
20519            }
20520            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20521                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20522                        : "Receiver Resolver Table:", "  ", packageName,
20523                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20524                    dumpState.setTitlePrinted(true);
20525                }
20526            }
20527            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20528                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20529                        : "Service Resolver Table:", "  ", packageName,
20530                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20531                    dumpState.setTitlePrinted(true);
20532                }
20533            }
20534            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20535                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20536                        : "Provider Resolver Table:", "  ", packageName,
20537                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20538                    dumpState.setTitlePrinted(true);
20539                }
20540            }
20541
20542            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20543                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20544                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20545                    int user = mSettings.mPreferredActivities.keyAt(i);
20546                    if (pir.dump(pw,
20547                            dumpState.getTitlePrinted()
20548                                ? "\nPreferred Activities User " + user + ":"
20549                                : "Preferred Activities User " + user + ":", "  ",
20550                            packageName, true, false)) {
20551                        dumpState.setTitlePrinted(true);
20552                    }
20553                }
20554            }
20555
20556            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20557                pw.flush();
20558                FileOutputStream fout = new FileOutputStream(fd);
20559                BufferedOutputStream str = new BufferedOutputStream(fout);
20560                XmlSerializer serializer = new FastXmlSerializer();
20561                try {
20562                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20563                    serializer.startDocument(null, true);
20564                    serializer.setFeature(
20565                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20566                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20567                    serializer.endDocument();
20568                    serializer.flush();
20569                } catch (IllegalArgumentException e) {
20570                    pw.println("Failed writing: " + e);
20571                } catch (IllegalStateException e) {
20572                    pw.println("Failed writing: " + e);
20573                } catch (IOException e) {
20574                    pw.println("Failed writing: " + e);
20575                }
20576            }
20577
20578            if (!checkin
20579                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20580                    && packageName == null) {
20581                pw.println();
20582                int count = mSettings.mPackages.size();
20583                if (count == 0) {
20584                    pw.println("No applications!");
20585                    pw.println();
20586                } else {
20587                    final String prefix = "  ";
20588                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20589                    if (allPackageSettings.size() == 0) {
20590                        pw.println("No domain preferred apps!");
20591                        pw.println();
20592                    } else {
20593                        pw.println("App verification status:");
20594                        pw.println();
20595                        count = 0;
20596                        for (PackageSetting ps : allPackageSettings) {
20597                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20598                            if (ivi == null || ivi.getPackageName() == null) continue;
20599                            pw.println(prefix + "Package: " + ivi.getPackageName());
20600                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20601                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20602                            pw.println();
20603                            count++;
20604                        }
20605                        if (count == 0) {
20606                            pw.println(prefix + "No app verification established.");
20607                            pw.println();
20608                        }
20609                        for (int userId : sUserManager.getUserIds()) {
20610                            pw.println("App linkages for user " + userId + ":");
20611                            pw.println();
20612                            count = 0;
20613                            for (PackageSetting ps : allPackageSettings) {
20614                                final long status = ps.getDomainVerificationStatusForUser(userId);
20615                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20616                                        && !DEBUG_DOMAIN_VERIFICATION) {
20617                                    continue;
20618                                }
20619                                pw.println(prefix + "Package: " + ps.name);
20620                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20621                                String statusStr = IntentFilterVerificationInfo.
20622                                        getStatusStringFromValue(status);
20623                                pw.println(prefix + "Status:  " + statusStr);
20624                                pw.println();
20625                                count++;
20626                            }
20627                            if (count == 0) {
20628                                pw.println(prefix + "No configured app linkages.");
20629                                pw.println();
20630                            }
20631                        }
20632                    }
20633                }
20634            }
20635
20636            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20637                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20638            }
20639
20640            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20641                boolean printedSomething = false;
20642                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20643                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20644                        continue;
20645                    }
20646                    if (!printedSomething) {
20647                        if (dumpState.onTitlePrinted())
20648                            pw.println();
20649                        pw.println("Registered ContentProviders:");
20650                        printedSomething = true;
20651                    }
20652                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20653                    pw.print("    "); pw.println(p.toString());
20654                }
20655                printedSomething = false;
20656                for (Map.Entry<String, PackageParser.Provider> entry :
20657                        mProvidersByAuthority.entrySet()) {
20658                    PackageParser.Provider p = entry.getValue();
20659                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20660                        continue;
20661                    }
20662                    if (!printedSomething) {
20663                        if (dumpState.onTitlePrinted())
20664                            pw.println();
20665                        pw.println("ContentProvider Authorities:");
20666                        printedSomething = true;
20667                    }
20668                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20669                    pw.print("    "); pw.println(p.toString());
20670                    if (p.info != null && p.info.applicationInfo != null) {
20671                        final String appInfo = p.info.applicationInfo.toString();
20672                        pw.print("      applicationInfo="); pw.println(appInfo);
20673                    }
20674                }
20675            }
20676
20677            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20678                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20679            }
20680
20681            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20682                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20683            }
20684
20685            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20686                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20687            }
20688
20689            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
20690                if (dumpState.onTitlePrinted()) pw.println();
20691                pw.println("Package Changes:");
20692                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
20693                final int K = mChangedPackages.size();
20694                for (int i = 0; i < K; i++) {
20695                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
20696                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
20697                    final int N = changes.size();
20698                    if (N == 0) {
20699                        pw.print("    "); pw.println("No packages changed");
20700                    } else {
20701                        for (int j = 0; j < N; j++) {
20702                            final String pkgName = changes.valueAt(j);
20703                            final int sequenceNumber = changes.keyAt(j);
20704                            pw.print("    ");
20705                            pw.print("seq=");
20706                            pw.print(sequenceNumber);
20707                            pw.print(", package=");
20708                            pw.println(pkgName);
20709                        }
20710                    }
20711                }
20712            }
20713
20714            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20715                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20716            }
20717
20718            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20719                // XXX should handle packageName != null by dumping only install data that
20720                // the given package is involved with.
20721                if (dumpState.onTitlePrinted()) pw.println();
20722
20723                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20724                ipw.println();
20725                ipw.println("Frozen packages:");
20726                ipw.increaseIndent();
20727                if (mFrozenPackages.size() == 0) {
20728                    ipw.println("(none)");
20729                } else {
20730                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20731                        ipw.println(mFrozenPackages.valueAt(i));
20732                    }
20733                }
20734                ipw.decreaseIndent();
20735            }
20736
20737            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
20738                if (dumpState.onTitlePrinted()) pw.println();
20739
20740                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20741                ipw.println();
20742                ipw.println("Loaded volumes:");
20743                ipw.increaseIndent();
20744                if (mLoadedVolumes.size() == 0) {
20745                    ipw.println("(none)");
20746                } else {
20747                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
20748                        ipw.println(mLoadedVolumes.valueAt(i));
20749                    }
20750                }
20751                ipw.decreaseIndent();
20752            }
20753
20754            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20755                if (dumpState.onTitlePrinted()) pw.println();
20756                dumpDexoptStateLPr(pw, packageName);
20757            }
20758
20759            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20760                if (dumpState.onTitlePrinted()) pw.println();
20761                dumpCompilerStatsLPr(pw, packageName);
20762            }
20763
20764            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20765                if (dumpState.onTitlePrinted()) pw.println();
20766                mSettings.dumpReadMessagesLPr(pw, dumpState);
20767
20768                pw.println();
20769                pw.println("Package warning messages:");
20770                dumpCriticalInfo(pw, null);
20771            }
20772
20773            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20774                dumpCriticalInfo(pw, "msg,");
20775            }
20776        }
20777
20778        // PackageInstaller should be called outside of mPackages lock
20779        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20780            // XXX should handle packageName != null by dumping only install data that
20781            // the given package is involved with.
20782            if (dumpState.onTitlePrinted()) pw.println();
20783            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20784        }
20785    }
20786
20787    private void dumpProto(FileDescriptor fd) {
20788        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20789
20790        synchronized (mPackages) {
20791            final long requiredVerifierPackageToken =
20792                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20793            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20794            proto.write(
20795                    PackageServiceDumpProto.PackageShortProto.UID,
20796                    getPackageUid(
20797                            mRequiredVerifierPackage,
20798                            MATCH_DEBUG_TRIAGED_MISSING,
20799                            UserHandle.USER_SYSTEM));
20800            proto.end(requiredVerifierPackageToken);
20801
20802            if (mIntentFilterVerifierComponent != null) {
20803                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20804                final long verifierPackageToken =
20805                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20806                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20807                proto.write(
20808                        PackageServiceDumpProto.PackageShortProto.UID,
20809                        getPackageUid(
20810                                verifierPackageName,
20811                                MATCH_DEBUG_TRIAGED_MISSING,
20812                                UserHandle.USER_SYSTEM));
20813                proto.end(verifierPackageToken);
20814            }
20815
20816            dumpSharedLibrariesProto(proto);
20817            dumpFeaturesProto(proto);
20818            mSettings.dumpPackagesProto(proto);
20819            mSettings.dumpSharedUsersProto(proto);
20820            dumpCriticalInfo(proto);
20821        }
20822        proto.flush();
20823    }
20824
20825    private void dumpFeaturesProto(ProtoOutputStream proto) {
20826        synchronized (mAvailableFeatures) {
20827            final int count = mAvailableFeatures.size();
20828            for (int i = 0; i < count; i++) {
20829                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
20830            }
20831        }
20832    }
20833
20834    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20835        final int count = mSharedLibraries.size();
20836        for (int i = 0; i < count; i++) {
20837            final String libName = mSharedLibraries.keyAt(i);
20838            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20839            if (versionedLib == null) {
20840                continue;
20841            }
20842            final int versionCount = versionedLib.size();
20843            for (int j = 0; j < versionCount; j++) {
20844                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20845                final long sharedLibraryToken =
20846                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20847                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20848                final boolean isJar = (libEntry.path != null);
20849                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20850                if (isJar) {
20851                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20852                } else {
20853                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20854                }
20855                proto.end(sharedLibraryToken);
20856            }
20857        }
20858    }
20859
20860    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20861        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20862        ipw.println();
20863        ipw.println("Dexopt state:");
20864        ipw.increaseIndent();
20865        Collection<PackageParser.Package> packages = null;
20866        if (packageName != null) {
20867            PackageParser.Package targetPackage = mPackages.get(packageName);
20868            if (targetPackage != null) {
20869                packages = Collections.singletonList(targetPackage);
20870            } else {
20871                ipw.println("Unable to find package: " + packageName);
20872                return;
20873            }
20874        } else {
20875            packages = mPackages.values();
20876        }
20877
20878        for (PackageParser.Package pkg : packages) {
20879            ipw.println("[" + pkg.packageName + "]");
20880            ipw.increaseIndent();
20881            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
20882                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
20883            ipw.decreaseIndent();
20884        }
20885    }
20886
20887    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20888        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20889        ipw.println();
20890        ipw.println("Compiler stats:");
20891        ipw.increaseIndent();
20892        Collection<PackageParser.Package> packages = null;
20893        if (packageName != null) {
20894            PackageParser.Package targetPackage = mPackages.get(packageName);
20895            if (targetPackage != null) {
20896                packages = Collections.singletonList(targetPackage);
20897            } else {
20898                ipw.println("Unable to find package: " + packageName);
20899                return;
20900            }
20901        } else {
20902            packages = mPackages.values();
20903        }
20904
20905        for (PackageParser.Package pkg : packages) {
20906            ipw.println("[" + pkg.packageName + "]");
20907            ipw.increaseIndent();
20908
20909            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20910            if (stats == null) {
20911                ipw.println("(No recorded stats)");
20912            } else {
20913                stats.dump(ipw);
20914            }
20915            ipw.decreaseIndent();
20916        }
20917    }
20918
20919    private String dumpDomainString(String packageName) {
20920        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20921                .getList();
20922        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20923
20924        ArraySet<String> result = new ArraySet<>();
20925        if (iviList.size() > 0) {
20926            for (IntentFilterVerificationInfo ivi : iviList) {
20927                for (String host : ivi.getDomains()) {
20928                    result.add(host);
20929                }
20930            }
20931        }
20932        if (filters != null && filters.size() > 0) {
20933            for (IntentFilter filter : filters) {
20934                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20935                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20936                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20937                    result.addAll(filter.getHostsList());
20938                }
20939            }
20940        }
20941
20942        StringBuilder sb = new StringBuilder(result.size() * 16);
20943        for (String domain : result) {
20944            if (sb.length() > 0) sb.append(" ");
20945            sb.append(domain);
20946        }
20947        return sb.toString();
20948    }
20949
20950    // ------- apps on sdcard specific code -------
20951    static final boolean DEBUG_SD_INSTALL = false;
20952
20953    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20954
20955    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20956
20957    private boolean mMediaMounted = false;
20958
20959    static String getEncryptKey() {
20960        try {
20961            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20962                    SD_ENCRYPTION_KEYSTORE_NAME);
20963            if (sdEncKey == null) {
20964                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20965                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20966                if (sdEncKey == null) {
20967                    Slog.e(TAG, "Failed to create encryption keys");
20968                    return null;
20969                }
20970            }
20971            return sdEncKey;
20972        } catch (NoSuchAlgorithmException nsae) {
20973            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20974            return null;
20975        } catch (IOException ioe) {
20976            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20977            return null;
20978        }
20979    }
20980
20981    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20982            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20983        final int size = infos.size();
20984        final String[] packageNames = new String[size];
20985        final int[] packageUids = new int[size];
20986        for (int i = 0; i < size; i++) {
20987            final ApplicationInfo info = infos.get(i);
20988            packageNames[i] = info.packageName;
20989            packageUids[i] = info.uid;
20990        }
20991        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20992                finishedReceiver);
20993    }
20994
20995    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20996            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20997        sendResourcesChangedBroadcast(mediaStatus, replacing,
20998                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20999    }
21000
21001    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21002            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21003        int size = pkgList.length;
21004        if (size > 0) {
21005            // Send broadcasts here
21006            Bundle extras = new Bundle();
21007            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21008            if (uidArr != null) {
21009                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21010            }
21011            if (replacing) {
21012                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21013            }
21014            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21015                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21016            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21017        }
21018    }
21019
21020    private void loadPrivatePackages(final VolumeInfo vol) {
21021        mHandler.post(new Runnable() {
21022            @Override
21023            public void run() {
21024                loadPrivatePackagesInner(vol);
21025            }
21026        });
21027    }
21028
21029    private void loadPrivatePackagesInner(VolumeInfo vol) {
21030        final String volumeUuid = vol.fsUuid;
21031        if (TextUtils.isEmpty(volumeUuid)) {
21032            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21033            return;
21034        }
21035
21036        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21037        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21038        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21039
21040        final VersionInfo ver;
21041        final List<PackageSetting> packages;
21042        synchronized (mPackages) {
21043            ver = mSettings.findOrCreateVersion(volumeUuid);
21044            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21045        }
21046
21047        for (PackageSetting ps : packages) {
21048            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21049            synchronized (mInstallLock) {
21050                final PackageParser.Package pkg;
21051                try {
21052                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21053                    loaded.add(pkg.applicationInfo);
21054
21055                } catch (PackageManagerException e) {
21056                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21057                }
21058
21059                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21060                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21061                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21062                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21063                }
21064            }
21065        }
21066
21067        // Reconcile app data for all started/unlocked users
21068        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21069        final UserManager um = mContext.getSystemService(UserManager.class);
21070        UserManagerInternal umInternal = getUserManagerInternal();
21071        for (UserInfo user : um.getUsers()) {
21072            final int flags;
21073            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21074                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21075            } else if (umInternal.isUserRunning(user.id)) {
21076                flags = StorageManager.FLAG_STORAGE_DE;
21077            } else {
21078                continue;
21079            }
21080
21081            try {
21082                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21083                synchronized (mInstallLock) {
21084                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21085                }
21086            } catch (IllegalStateException e) {
21087                // Device was probably ejected, and we'll process that event momentarily
21088                Slog.w(TAG, "Failed to prepare storage: " + e);
21089            }
21090        }
21091
21092        synchronized (mPackages) {
21093            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21094            if (sdkUpdated) {
21095                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21096                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21097            }
21098            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21099                    mPermissionCallback);
21100
21101            // Yay, everything is now upgraded
21102            ver.forceCurrent();
21103
21104            mSettings.writeLPr();
21105        }
21106
21107        for (PackageFreezer freezer : freezers) {
21108            freezer.close();
21109        }
21110
21111        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21112        sendResourcesChangedBroadcast(true, false, loaded, null);
21113        mLoadedVolumes.add(vol.getId());
21114    }
21115
21116    private void unloadPrivatePackages(final VolumeInfo vol) {
21117        mHandler.post(new Runnable() {
21118            @Override
21119            public void run() {
21120                unloadPrivatePackagesInner(vol);
21121            }
21122        });
21123    }
21124
21125    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21126        final String volumeUuid = vol.fsUuid;
21127        if (TextUtils.isEmpty(volumeUuid)) {
21128            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21129            return;
21130        }
21131
21132        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21133        synchronized (mInstallLock) {
21134        synchronized (mPackages) {
21135            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21136            for (PackageSetting ps : packages) {
21137                if (ps.pkg == null) continue;
21138
21139                final ApplicationInfo info = ps.pkg.applicationInfo;
21140                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21141                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21142
21143                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21144                        "unloadPrivatePackagesInner")) {
21145                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21146                            false, null)) {
21147                        unloaded.add(info);
21148                    } else {
21149                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21150                    }
21151                }
21152
21153                // Try very hard to release any references to this package
21154                // so we don't risk the system server being killed due to
21155                // open FDs
21156                AttributeCache.instance().removePackage(ps.name);
21157            }
21158
21159            mSettings.writeLPr();
21160        }
21161        }
21162
21163        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21164        sendResourcesChangedBroadcast(false, false, unloaded, null);
21165        mLoadedVolumes.remove(vol.getId());
21166
21167        // Try very hard to release any references to this path so we don't risk
21168        // the system server being killed due to open FDs
21169        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21170
21171        for (int i = 0; i < 3; i++) {
21172            System.gc();
21173            System.runFinalization();
21174        }
21175    }
21176
21177    private void assertPackageKnown(String volumeUuid, String packageName)
21178            throws PackageManagerException {
21179        synchronized (mPackages) {
21180            // Normalize package name to handle renamed packages
21181            packageName = normalizePackageNameLPr(packageName);
21182
21183            final PackageSetting ps = mSettings.mPackages.get(packageName);
21184            if (ps == null) {
21185                throw new PackageManagerException("Package " + packageName + " is unknown");
21186            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21187                throw new PackageManagerException(
21188                        "Package " + packageName + " found on unknown volume " + volumeUuid
21189                                + "; expected volume " + ps.volumeUuid);
21190            }
21191        }
21192    }
21193
21194    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21195            throws PackageManagerException {
21196        synchronized (mPackages) {
21197            // Normalize package name to handle renamed packages
21198            packageName = normalizePackageNameLPr(packageName);
21199
21200            final PackageSetting ps = mSettings.mPackages.get(packageName);
21201            if (ps == null) {
21202                throw new PackageManagerException("Package " + packageName + " is unknown");
21203            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21204                throw new PackageManagerException(
21205                        "Package " + packageName + " found on unknown volume " + volumeUuid
21206                                + "; expected volume " + ps.volumeUuid);
21207            } else if (!ps.getInstalled(userId)) {
21208                throw new PackageManagerException(
21209                        "Package " + packageName + " not installed for user " + userId);
21210            }
21211        }
21212    }
21213
21214    private List<String> collectAbsoluteCodePaths() {
21215        synchronized (mPackages) {
21216            List<String> codePaths = new ArrayList<>();
21217            final int packageCount = mSettings.mPackages.size();
21218            for (int i = 0; i < packageCount; i++) {
21219                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21220                codePaths.add(ps.codePath.getAbsolutePath());
21221            }
21222            return codePaths;
21223        }
21224    }
21225
21226    /**
21227     * Examine all apps present on given mounted volume, and destroy apps that
21228     * aren't expected, either due to uninstallation or reinstallation on
21229     * another volume.
21230     */
21231    private void reconcileApps(String volumeUuid) {
21232        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21233        List<File> filesToDelete = null;
21234
21235        final File[] files = FileUtils.listFilesOrEmpty(
21236                Environment.getDataAppDirectory(volumeUuid));
21237        for (File file : files) {
21238            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21239                    && !PackageInstallerService.isStageName(file.getName());
21240            if (!isPackage) {
21241                // Ignore entries which are not packages
21242                continue;
21243            }
21244
21245            String absolutePath = file.getAbsolutePath();
21246
21247            boolean pathValid = false;
21248            final int absoluteCodePathCount = absoluteCodePaths.size();
21249            for (int i = 0; i < absoluteCodePathCount; i++) {
21250                String absoluteCodePath = absoluteCodePaths.get(i);
21251                if (absolutePath.startsWith(absoluteCodePath)) {
21252                    pathValid = true;
21253                    break;
21254                }
21255            }
21256
21257            if (!pathValid) {
21258                if (filesToDelete == null) {
21259                    filesToDelete = new ArrayList<>();
21260                }
21261                filesToDelete.add(file);
21262            }
21263        }
21264
21265        if (filesToDelete != null) {
21266            final int fileToDeleteCount = filesToDelete.size();
21267            for (int i = 0; i < fileToDeleteCount; i++) {
21268                File fileToDelete = filesToDelete.get(i);
21269                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21270                synchronized (mInstallLock) {
21271                    removeCodePathLI(fileToDelete);
21272                }
21273            }
21274        }
21275    }
21276
21277    /**
21278     * Reconcile all app data for the given user.
21279     * <p>
21280     * Verifies that directories exist and that ownership and labeling is
21281     * correct for all installed apps on all mounted volumes.
21282     */
21283    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21284        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21285        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21286            final String volumeUuid = vol.getFsUuid();
21287            synchronized (mInstallLock) {
21288                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21289            }
21290        }
21291    }
21292
21293    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21294            boolean migrateAppData) {
21295        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21296    }
21297
21298    /**
21299     * Reconcile all app data on given mounted volume.
21300     * <p>
21301     * Destroys app data that isn't expected, either due to uninstallation or
21302     * reinstallation on another volume.
21303     * <p>
21304     * Verifies that directories exist and that ownership and labeling is
21305     * correct for all installed apps.
21306     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21307     */
21308    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21309            boolean migrateAppData, boolean onlyCoreApps) {
21310        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21311                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21312        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21313
21314        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21315        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21316
21317        // First look for stale data that doesn't belong, and check if things
21318        // have changed since we did our last restorecon
21319        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21320            if (StorageManager.isFileEncryptedNativeOrEmulated()
21321                    && !StorageManager.isUserKeyUnlocked(userId)) {
21322                throw new RuntimeException(
21323                        "Yikes, someone asked us to reconcile CE storage while " + userId
21324                                + " was still locked; this would have caused massive data loss!");
21325            }
21326
21327            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21328            for (File file : files) {
21329                final String packageName = file.getName();
21330                try {
21331                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21332                } catch (PackageManagerException e) {
21333                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21334                    try {
21335                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21336                                StorageManager.FLAG_STORAGE_CE, 0);
21337                    } catch (InstallerException e2) {
21338                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21339                    }
21340                }
21341            }
21342        }
21343        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21344            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21345            for (File file : files) {
21346                final String packageName = file.getName();
21347                try {
21348                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21349                } catch (PackageManagerException e) {
21350                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21351                    try {
21352                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21353                                StorageManager.FLAG_STORAGE_DE, 0);
21354                    } catch (InstallerException e2) {
21355                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21356                    }
21357                }
21358            }
21359        }
21360
21361        // Ensure that data directories are ready to roll for all packages
21362        // installed for this volume and user
21363        final List<PackageSetting> packages;
21364        synchronized (mPackages) {
21365            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21366        }
21367        int preparedCount = 0;
21368        for (PackageSetting ps : packages) {
21369            final String packageName = ps.name;
21370            if (ps.pkg == null) {
21371                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21372                // TODO: might be due to legacy ASEC apps; we should circle back
21373                // and reconcile again once they're scanned
21374                continue;
21375            }
21376            // Skip non-core apps if requested
21377            if (onlyCoreApps && !ps.pkg.coreApp) {
21378                result.add(packageName);
21379                continue;
21380            }
21381
21382            if (ps.getInstalled(userId)) {
21383                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21384                preparedCount++;
21385            }
21386        }
21387
21388        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21389        return result;
21390    }
21391
21392    /**
21393     * Prepare app data for the given app just after it was installed or
21394     * upgraded. This method carefully only touches users that it's installed
21395     * for, and it forces a restorecon to handle any seinfo changes.
21396     * <p>
21397     * Verifies that directories exist and that ownership and labeling is
21398     * correct for all installed apps. If there is an ownership mismatch, it
21399     * will try recovering system apps by wiping data; third-party app data is
21400     * left intact.
21401     * <p>
21402     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21403     */
21404    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21405        final PackageSetting ps;
21406        synchronized (mPackages) {
21407            ps = mSettings.mPackages.get(pkg.packageName);
21408            mSettings.writeKernelMappingLPr(ps);
21409        }
21410
21411        final UserManager um = mContext.getSystemService(UserManager.class);
21412        UserManagerInternal umInternal = getUserManagerInternal();
21413        for (UserInfo user : um.getUsers()) {
21414            final int flags;
21415            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21416                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21417            } else if (umInternal.isUserRunning(user.id)) {
21418                flags = StorageManager.FLAG_STORAGE_DE;
21419            } else {
21420                continue;
21421            }
21422
21423            if (ps.getInstalled(user.id)) {
21424                // TODO: when user data is locked, mark that we're still dirty
21425                prepareAppDataLIF(pkg, user.id, flags);
21426            }
21427        }
21428    }
21429
21430    /**
21431     * Prepare app data for the given app.
21432     * <p>
21433     * Verifies that directories exist and that ownership and labeling is
21434     * correct for all installed apps. If there is an ownership mismatch, this
21435     * will try recovering system apps by wiping data; third-party app data is
21436     * left intact.
21437     */
21438    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21439        if (pkg == null) {
21440            Slog.wtf(TAG, "Package was null!", new Throwable());
21441            return;
21442        }
21443        prepareAppDataLeafLIF(pkg, userId, flags);
21444        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21445        for (int i = 0; i < childCount; i++) {
21446            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21447        }
21448    }
21449
21450    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21451            boolean maybeMigrateAppData) {
21452        prepareAppDataLIF(pkg, userId, flags);
21453
21454        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21455            // We may have just shuffled around app data directories, so
21456            // prepare them one more time
21457            prepareAppDataLIF(pkg, userId, flags);
21458        }
21459    }
21460
21461    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21462        if (DEBUG_APP_DATA) {
21463            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21464                    + Integer.toHexString(flags));
21465        }
21466
21467        final String volumeUuid = pkg.volumeUuid;
21468        final String packageName = pkg.packageName;
21469        final ApplicationInfo app = pkg.applicationInfo;
21470        final int appId = UserHandle.getAppId(app.uid);
21471
21472        Preconditions.checkNotNull(app.seInfo);
21473
21474        long ceDataInode = -1;
21475        try {
21476            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21477                    appId, app.seInfo, app.targetSdkVersion);
21478        } catch (InstallerException e) {
21479            if (app.isSystemApp()) {
21480                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21481                        + ", but trying to recover: " + e);
21482                destroyAppDataLeafLIF(pkg, userId, flags);
21483                try {
21484                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21485                            appId, app.seInfo, app.targetSdkVersion);
21486                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21487                } catch (InstallerException e2) {
21488                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21489                }
21490            } else {
21491                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21492            }
21493        }
21494
21495        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21496            // TODO: mark this structure as dirty so we persist it!
21497            synchronized (mPackages) {
21498                final PackageSetting ps = mSettings.mPackages.get(packageName);
21499                if (ps != null) {
21500                    ps.setCeDataInode(ceDataInode, userId);
21501                }
21502            }
21503        }
21504
21505        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21506    }
21507
21508    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21509        if (pkg == null) {
21510            Slog.wtf(TAG, "Package was null!", new Throwable());
21511            return;
21512        }
21513        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21514        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21515        for (int i = 0; i < childCount; i++) {
21516            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21517        }
21518    }
21519
21520    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21521        final String volumeUuid = pkg.volumeUuid;
21522        final String packageName = pkg.packageName;
21523        final ApplicationInfo app = pkg.applicationInfo;
21524
21525        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21526            // Create a native library symlink only if we have native libraries
21527            // and if the native libraries are 32 bit libraries. We do not provide
21528            // this symlink for 64 bit libraries.
21529            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21530                final String nativeLibPath = app.nativeLibraryDir;
21531                try {
21532                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21533                            nativeLibPath, userId);
21534                } catch (InstallerException e) {
21535                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21536                }
21537            }
21538        }
21539    }
21540
21541    /**
21542     * For system apps on non-FBE devices, this method migrates any existing
21543     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21544     * requested by the app.
21545     */
21546    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21547        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21548                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21549            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21550                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21551            try {
21552                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21553                        storageTarget);
21554            } catch (InstallerException e) {
21555                logCriticalInfo(Log.WARN,
21556                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21557            }
21558            return true;
21559        } else {
21560            return false;
21561        }
21562    }
21563
21564    public PackageFreezer freezePackage(String packageName, String killReason) {
21565        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21566    }
21567
21568    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21569        return new PackageFreezer(packageName, userId, killReason);
21570    }
21571
21572    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21573            String killReason) {
21574        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21575    }
21576
21577    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21578            String killReason) {
21579        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21580            return new PackageFreezer();
21581        } else {
21582            return freezePackage(packageName, userId, killReason);
21583        }
21584    }
21585
21586    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21587            String killReason) {
21588        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21589    }
21590
21591    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21592            String killReason) {
21593        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21594            return new PackageFreezer();
21595        } else {
21596            return freezePackage(packageName, userId, killReason);
21597        }
21598    }
21599
21600    /**
21601     * Class that freezes and kills the given package upon creation, and
21602     * unfreezes it upon closing. This is typically used when doing surgery on
21603     * app code/data to prevent the app from running while you're working.
21604     */
21605    private class PackageFreezer implements AutoCloseable {
21606        private final String mPackageName;
21607        private final PackageFreezer[] mChildren;
21608
21609        private final boolean mWeFroze;
21610
21611        private final AtomicBoolean mClosed = new AtomicBoolean();
21612        private final CloseGuard mCloseGuard = CloseGuard.get();
21613
21614        /**
21615         * Create and return a stub freezer that doesn't actually do anything,
21616         * typically used when someone requested
21617         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21618         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21619         */
21620        public PackageFreezer() {
21621            mPackageName = null;
21622            mChildren = null;
21623            mWeFroze = false;
21624            mCloseGuard.open("close");
21625        }
21626
21627        public PackageFreezer(String packageName, int userId, String killReason) {
21628            synchronized (mPackages) {
21629                mPackageName = packageName;
21630                mWeFroze = mFrozenPackages.add(mPackageName);
21631
21632                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21633                if (ps != null) {
21634                    killApplication(ps.name, ps.appId, userId, killReason);
21635                }
21636
21637                final PackageParser.Package p = mPackages.get(packageName);
21638                if (p != null && p.childPackages != null) {
21639                    final int N = p.childPackages.size();
21640                    mChildren = new PackageFreezer[N];
21641                    for (int i = 0; i < N; i++) {
21642                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21643                                userId, killReason);
21644                    }
21645                } else {
21646                    mChildren = null;
21647                }
21648            }
21649            mCloseGuard.open("close");
21650        }
21651
21652        @Override
21653        protected void finalize() throws Throwable {
21654            try {
21655                if (mCloseGuard != null) {
21656                    mCloseGuard.warnIfOpen();
21657                }
21658
21659                close();
21660            } finally {
21661                super.finalize();
21662            }
21663        }
21664
21665        @Override
21666        public void close() {
21667            mCloseGuard.close();
21668            if (mClosed.compareAndSet(false, true)) {
21669                synchronized (mPackages) {
21670                    if (mWeFroze) {
21671                        mFrozenPackages.remove(mPackageName);
21672                    }
21673
21674                    if (mChildren != null) {
21675                        for (PackageFreezer freezer : mChildren) {
21676                            freezer.close();
21677                        }
21678                    }
21679                }
21680            }
21681        }
21682    }
21683
21684    /**
21685     * Verify that given package is currently frozen.
21686     */
21687    private void checkPackageFrozen(String packageName) {
21688        synchronized (mPackages) {
21689            if (!mFrozenPackages.contains(packageName)) {
21690                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21691            }
21692        }
21693    }
21694
21695    @Override
21696    public int movePackage(final String packageName, final String volumeUuid) {
21697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21698
21699        final int callingUid = Binder.getCallingUid();
21700        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
21701        final int moveId = mNextMoveId.getAndIncrement();
21702        mHandler.post(new Runnable() {
21703            @Override
21704            public void run() {
21705                try {
21706                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
21707                } catch (PackageManagerException e) {
21708                    Slog.w(TAG, "Failed to move " + packageName, e);
21709                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
21710                }
21711            }
21712        });
21713        return moveId;
21714    }
21715
21716    private void movePackageInternal(final String packageName, final String volumeUuid,
21717            final int moveId, final int callingUid, UserHandle user)
21718                    throws PackageManagerException {
21719        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21720        final PackageManager pm = mContext.getPackageManager();
21721
21722        final boolean currentAsec;
21723        final String currentVolumeUuid;
21724        final File codeFile;
21725        final String installerPackageName;
21726        final String packageAbiOverride;
21727        final int appId;
21728        final String seinfo;
21729        final String label;
21730        final int targetSdkVersion;
21731        final PackageFreezer freezer;
21732        final int[] installedUserIds;
21733
21734        // reader
21735        synchronized (mPackages) {
21736            final PackageParser.Package pkg = mPackages.get(packageName);
21737            final PackageSetting ps = mSettings.mPackages.get(packageName);
21738            if (pkg == null
21739                    || ps == null
21740                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
21741                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21742            }
21743            if (pkg.applicationInfo.isSystemApp()) {
21744                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21745                        "Cannot move system application");
21746            }
21747
21748            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21749            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21750                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21751            if (isInternalStorage && !allow3rdPartyOnInternal) {
21752                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21753                        "3rd party apps are not allowed on internal storage");
21754            }
21755
21756            if (pkg.applicationInfo.isExternalAsec()) {
21757                currentAsec = true;
21758                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21759            } else if (pkg.applicationInfo.isForwardLocked()) {
21760                currentAsec = true;
21761                currentVolumeUuid = "forward_locked";
21762            } else {
21763                currentAsec = false;
21764                currentVolumeUuid = ps.volumeUuid;
21765
21766                final File probe = new File(pkg.codePath);
21767                final File probeOat = new File(probe, "oat");
21768                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21769                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21770                            "Move only supported for modern cluster style installs");
21771                }
21772            }
21773
21774            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21775                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21776                        "Package already moved to " + volumeUuid);
21777            }
21778            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21779                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21780                        "Device admin cannot be moved");
21781            }
21782
21783            if (mFrozenPackages.contains(packageName)) {
21784                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21785                        "Failed to move already frozen package");
21786            }
21787
21788            codeFile = new File(pkg.codePath);
21789            installerPackageName = ps.installerPackageName;
21790            packageAbiOverride = ps.cpuAbiOverrideString;
21791            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21792            seinfo = pkg.applicationInfo.seInfo;
21793            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21794            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21795            freezer = freezePackage(packageName, "movePackageInternal");
21796            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21797        }
21798
21799        final Bundle extras = new Bundle();
21800        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21801        extras.putString(Intent.EXTRA_TITLE, label);
21802        mMoveCallbacks.notifyCreated(moveId, extras);
21803
21804        int installFlags;
21805        final boolean moveCompleteApp;
21806        final File measurePath;
21807
21808        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21809            installFlags = INSTALL_INTERNAL;
21810            moveCompleteApp = !currentAsec;
21811            measurePath = Environment.getDataAppDirectory(volumeUuid);
21812        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21813            installFlags = INSTALL_EXTERNAL;
21814            moveCompleteApp = false;
21815            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21816        } else {
21817            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21818            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21819                    || !volume.isMountedWritable()) {
21820                freezer.close();
21821                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21822                        "Move location not mounted private volume");
21823            }
21824
21825            Preconditions.checkState(!currentAsec);
21826
21827            installFlags = INSTALL_INTERNAL;
21828            moveCompleteApp = true;
21829            measurePath = Environment.getDataAppDirectory(volumeUuid);
21830        }
21831
21832        // If we're moving app data around, we need all the users unlocked
21833        if (moveCompleteApp) {
21834            for (int userId : installedUserIds) {
21835                if (StorageManager.isFileEncryptedNativeOrEmulated()
21836                        && !StorageManager.isUserKeyUnlocked(userId)) {
21837                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
21838                            "User " + userId + " must be unlocked");
21839                }
21840            }
21841        }
21842
21843        final PackageStats stats = new PackageStats(null, -1);
21844        synchronized (mInstaller) {
21845            for (int userId : installedUserIds) {
21846                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21847                    freezer.close();
21848                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21849                            "Failed to measure package size");
21850                }
21851            }
21852        }
21853
21854        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21855                + stats.dataSize);
21856
21857        final long startFreeBytes = measurePath.getUsableSpace();
21858        final long sizeBytes;
21859        if (moveCompleteApp) {
21860            sizeBytes = stats.codeSize + stats.dataSize;
21861        } else {
21862            sizeBytes = stats.codeSize;
21863        }
21864
21865        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21866            freezer.close();
21867            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21868                    "Not enough free space to move");
21869        }
21870
21871        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21872
21873        final CountDownLatch installedLatch = new CountDownLatch(1);
21874        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21875            @Override
21876            public void onUserActionRequired(Intent intent) throws RemoteException {
21877                throw new IllegalStateException();
21878            }
21879
21880            @Override
21881            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21882                    Bundle extras) throws RemoteException {
21883                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21884                        + PackageManager.installStatusToString(returnCode, msg));
21885
21886                installedLatch.countDown();
21887                freezer.close();
21888
21889                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21890                switch (status) {
21891                    case PackageInstaller.STATUS_SUCCESS:
21892                        mMoveCallbacks.notifyStatusChanged(moveId,
21893                                PackageManager.MOVE_SUCCEEDED);
21894                        break;
21895                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21896                        mMoveCallbacks.notifyStatusChanged(moveId,
21897                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21898                        break;
21899                    default:
21900                        mMoveCallbacks.notifyStatusChanged(moveId,
21901                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21902                        break;
21903                }
21904            }
21905        };
21906
21907        final MoveInfo move;
21908        if (moveCompleteApp) {
21909            // Kick off a thread to report progress estimates
21910            new Thread() {
21911                @Override
21912                public void run() {
21913                    while (true) {
21914                        try {
21915                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21916                                break;
21917                            }
21918                        } catch (InterruptedException ignored) {
21919                        }
21920
21921                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
21922                        final int progress = 10 + (int) MathUtils.constrain(
21923                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21924                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21925                    }
21926                }
21927            }.start();
21928
21929            final String dataAppName = codeFile.getName();
21930            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21931                    dataAppName, appId, seinfo, targetSdkVersion);
21932        } else {
21933            move = null;
21934        }
21935
21936        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21937
21938        final Message msg = mHandler.obtainMessage(INIT_COPY);
21939        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21940        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21941                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21942                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21943                PackageManager.INSTALL_REASON_UNKNOWN);
21944        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21945        msg.obj = params;
21946
21947        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21948                System.identityHashCode(msg.obj));
21949        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21950                System.identityHashCode(msg.obj));
21951
21952        mHandler.sendMessage(msg);
21953    }
21954
21955    @Override
21956    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21957        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21958
21959        final int realMoveId = mNextMoveId.getAndIncrement();
21960        final Bundle extras = new Bundle();
21961        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21962        mMoveCallbacks.notifyCreated(realMoveId, extras);
21963
21964        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21965            @Override
21966            public void onCreated(int moveId, Bundle extras) {
21967                // Ignored
21968            }
21969
21970            @Override
21971            public void onStatusChanged(int moveId, int status, long estMillis) {
21972                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21973            }
21974        };
21975
21976        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21977        storage.setPrimaryStorageUuid(volumeUuid, callback);
21978        return realMoveId;
21979    }
21980
21981    @Override
21982    public int getMoveStatus(int moveId) {
21983        mContext.enforceCallingOrSelfPermission(
21984                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21985        return mMoveCallbacks.mLastStatus.get(moveId);
21986    }
21987
21988    @Override
21989    public void registerMoveCallback(IPackageMoveObserver callback) {
21990        mContext.enforceCallingOrSelfPermission(
21991                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21992        mMoveCallbacks.register(callback);
21993    }
21994
21995    @Override
21996    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21997        mContext.enforceCallingOrSelfPermission(
21998                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21999        mMoveCallbacks.unregister(callback);
22000    }
22001
22002    @Override
22003    public boolean setInstallLocation(int loc) {
22004        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22005                null);
22006        if (getInstallLocation() == loc) {
22007            return true;
22008        }
22009        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22010                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22011            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22012                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22013            return true;
22014        }
22015        return false;
22016   }
22017
22018    @Override
22019    public int getInstallLocation() {
22020        // allow instant app access
22021        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22022                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22023                PackageHelper.APP_INSTALL_AUTO);
22024    }
22025
22026    /** Called by UserManagerService */
22027    void cleanUpUser(UserManagerService userManager, int userHandle) {
22028        synchronized (mPackages) {
22029            mDirtyUsers.remove(userHandle);
22030            mUserNeedsBadging.delete(userHandle);
22031            mSettings.removeUserLPw(userHandle);
22032            mPendingBroadcasts.remove(userHandle);
22033            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22034            removeUnusedPackagesLPw(userManager, userHandle);
22035        }
22036    }
22037
22038    /**
22039     * We're removing userHandle and would like to remove any downloaded packages
22040     * that are no longer in use by any other user.
22041     * @param userHandle the user being removed
22042     */
22043    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22044        final boolean DEBUG_CLEAN_APKS = false;
22045        int [] users = userManager.getUserIds();
22046        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22047        while (psit.hasNext()) {
22048            PackageSetting ps = psit.next();
22049            if (ps.pkg == null) {
22050                continue;
22051            }
22052            final String packageName = ps.pkg.packageName;
22053            // Skip over if system app
22054            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22055                continue;
22056            }
22057            if (DEBUG_CLEAN_APKS) {
22058                Slog.i(TAG, "Checking package " + packageName);
22059            }
22060            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22061            if (keep) {
22062                if (DEBUG_CLEAN_APKS) {
22063                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22064                }
22065            } else {
22066                for (int i = 0; i < users.length; i++) {
22067                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22068                        keep = true;
22069                        if (DEBUG_CLEAN_APKS) {
22070                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22071                                    + users[i]);
22072                        }
22073                        break;
22074                    }
22075                }
22076            }
22077            if (!keep) {
22078                if (DEBUG_CLEAN_APKS) {
22079                    Slog.i(TAG, "  Removing package " + packageName);
22080                }
22081                mHandler.post(new Runnable() {
22082                    public void run() {
22083                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22084                                userHandle, 0);
22085                    } //end run
22086                });
22087            }
22088        }
22089    }
22090
22091    /** Called by UserManagerService */
22092    void createNewUser(int userId, String[] disallowedPackages) {
22093        synchronized (mInstallLock) {
22094            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22095        }
22096        synchronized (mPackages) {
22097            scheduleWritePackageRestrictionsLocked(userId);
22098            scheduleWritePackageListLocked(userId);
22099            applyFactoryDefaultBrowserLPw(userId);
22100            primeDomainVerificationsLPw(userId);
22101        }
22102    }
22103
22104    void onNewUserCreated(final int userId) {
22105        synchronized(mPackages) {
22106            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
22107            // If permission review for legacy apps is required, we represent
22108            // dagerous permissions for such apps as always granted runtime
22109            // permissions to keep per user flag state whether review is needed.
22110            // Hence, if a new user is added we have to propagate dangerous
22111            // permission grants for these legacy apps.
22112            if (mSettings.mPermissions.mPermissionReviewRequired) {
22113// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22114                mPermissionManager.updateAllPermissions(
22115                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22116                        mPermissionCallback);
22117            }
22118        }
22119    }
22120
22121    @Override
22122    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22123        mContext.enforceCallingOrSelfPermission(
22124                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22125                "Only package verification agents can read the verifier device identity");
22126
22127        synchronized (mPackages) {
22128            return mSettings.getVerifierDeviceIdentityLPw();
22129        }
22130    }
22131
22132    @Override
22133    public void setPermissionEnforced(String permission, boolean enforced) {
22134        // TODO: Now that we no longer change GID for storage, this should to away.
22135        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22136                "setPermissionEnforced");
22137        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22138            synchronized (mPackages) {
22139                if (mSettings.mReadExternalStorageEnforced == null
22140                        || mSettings.mReadExternalStorageEnforced != enforced) {
22141                    mSettings.mReadExternalStorageEnforced =
22142                            enforced ? Boolean.TRUE : Boolean.FALSE;
22143                    mSettings.writeLPr();
22144                }
22145            }
22146            // kill any non-foreground processes so we restart them and
22147            // grant/revoke the GID.
22148            final IActivityManager am = ActivityManager.getService();
22149            if (am != null) {
22150                final long token = Binder.clearCallingIdentity();
22151                try {
22152                    am.killProcessesBelowForeground("setPermissionEnforcement");
22153                } catch (RemoteException e) {
22154                } finally {
22155                    Binder.restoreCallingIdentity(token);
22156                }
22157            }
22158        } else {
22159            throw new IllegalArgumentException("No selective enforcement for " + permission);
22160        }
22161    }
22162
22163    @Override
22164    @Deprecated
22165    public boolean isPermissionEnforced(String permission) {
22166        // allow instant applications
22167        return true;
22168    }
22169
22170    @Override
22171    public boolean isStorageLow() {
22172        // allow instant applications
22173        final long token = Binder.clearCallingIdentity();
22174        try {
22175            final DeviceStorageMonitorInternal
22176                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22177            if (dsm != null) {
22178                return dsm.isMemoryLow();
22179            } else {
22180                return false;
22181            }
22182        } finally {
22183            Binder.restoreCallingIdentity(token);
22184        }
22185    }
22186
22187    @Override
22188    public IPackageInstaller getPackageInstaller() {
22189        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22190            return null;
22191        }
22192        return mInstallerService;
22193    }
22194
22195    private boolean userNeedsBadging(int userId) {
22196        int index = mUserNeedsBadging.indexOfKey(userId);
22197        if (index < 0) {
22198            final UserInfo userInfo;
22199            final long token = Binder.clearCallingIdentity();
22200            try {
22201                userInfo = sUserManager.getUserInfo(userId);
22202            } finally {
22203                Binder.restoreCallingIdentity(token);
22204            }
22205            final boolean b;
22206            if (userInfo != null && userInfo.isManagedProfile()) {
22207                b = true;
22208            } else {
22209                b = false;
22210            }
22211            mUserNeedsBadging.put(userId, b);
22212            return b;
22213        }
22214        return mUserNeedsBadging.valueAt(index);
22215    }
22216
22217    @Override
22218    public KeySet getKeySetByAlias(String packageName, String alias) {
22219        if (packageName == null || alias == null) {
22220            return null;
22221        }
22222        synchronized(mPackages) {
22223            final PackageParser.Package pkg = mPackages.get(packageName);
22224            if (pkg == null) {
22225                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22226                throw new IllegalArgumentException("Unknown package: " + packageName);
22227            }
22228            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22229            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22230                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22231                throw new IllegalArgumentException("Unknown package: " + packageName);
22232            }
22233            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22234            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22235        }
22236    }
22237
22238    @Override
22239    public KeySet getSigningKeySet(String packageName) {
22240        if (packageName == null) {
22241            return null;
22242        }
22243        synchronized(mPackages) {
22244            final int callingUid = Binder.getCallingUid();
22245            final int callingUserId = UserHandle.getUserId(callingUid);
22246            final PackageParser.Package pkg = mPackages.get(packageName);
22247            if (pkg == null) {
22248                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22249                throw new IllegalArgumentException("Unknown package: " + packageName);
22250            }
22251            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22252            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22253                // filter and pretend the package doesn't exist
22254                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22255                        + ", uid:" + callingUid);
22256                throw new IllegalArgumentException("Unknown package: " + packageName);
22257            }
22258            if (pkg.applicationInfo.uid != callingUid
22259                    && Process.SYSTEM_UID != callingUid) {
22260                throw new SecurityException("May not access signing KeySet of other apps.");
22261            }
22262            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22263            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22264        }
22265    }
22266
22267    @Override
22268    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22269        final int callingUid = Binder.getCallingUid();
22270        if (getInstantAppPackageName(callingUid) != null) {
22271            return false;
22272        }
22273        if (packageName == null || ks == null) {
22274            return false;
22275        }
22276        synchronized(mPackages) {
22277            final PackageParser.Package pkg = mPackages.get(packageName);
22278            if (pkg == null
22279                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22280                            UserHandle.getUserId(callingUid))) {
22281                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22282                throw new IllegalArgumentException("Unknown package: " + packageName);
22283            }
22284            IBinder ksh = ks.getToken();
22285            if (ksh instanceof KeySetHandle) {
22286                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22287                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22288            }
22289            return false;
22290        }
22291    }
22292
22293    @Override
22294    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22295        final int callingUid = Binder.getCallingUid();
22296        if (getInstantAppPackageName(callingUid) != null) {
22297            return false;
22298        }
22299        if (packageName == null || ks == null) {
22300            return false;
22301        }
22302        synchronized(mPackages) {
22303            final PackageParser.Package pkg = mPackages.get(packageName);
22304            if (pkg == null
22305                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22306                            UserHandle.getUserId(callingUid))) {
22307                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22308                throw new IllegalArgumentException("Unknown package: " + packageName);
22309            }
22310            IBinder ksh = ks.getToken();
22311            if (ksh instanceof KeySetHandle) {
22312                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22313                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22314            }
22315            return false;
22316        }
22317    }
22318
22319    private void deletePackageIfUnusedLPr(final String packageName) {
22320        PackageSetting ps = mSettings.mPackages.get(packageName);
22321        if (ps == null) {
22322            return;
22323        }
22324        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22325            // TODO Implement atomic delete if package is unused
22326            // It is currently possible that the package will be deleted even if it is installed
22327            // after this method returns.
22328            mHandler.post(new Runnable() {
22329                public void run() {
22330                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22331                            0, PackageManager.DELETE_ALL_USERS);
22332                }
22333            });
22334        }
22335    }
22336
22337    /**
22338     * Check and throw if the given before/after packages would be considered a
22339     * downgrade.
22340     */
22341    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22342            throws PackageManagerException {
22343        if (after.getLongVersionCode() < before.getLongVersionCode()) {
22344            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22345                    "Update version code " + after.versionCode + " is older than current "
22346                    + before.getLongVersionCode());
22347        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
22348            if (after.baseRevisionCode < before.baseRevisionCode) {
22349                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22350                        "Update base revision code " + after.baseRevisionCode
22351                        + " is older than current " + before.baseRevisionCode);
22352            }
22353
22354            if (!ArrayUtils.isEmpty(after.splitNames)) {
22355                for (int i = 0; i < after.splitNames.length; i++) {
22356                    final String splitName = after.splitNames[i];
22357                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22358                    if (j != -1) {
22359                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22360                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22361                                    "Update split " + splitName + " revision code "
22362                                    + after.splitRevisionCodes[i] + " is older than current "
22363                                    + before.splitRevisionCodes[j]);
22364                        }
22365                    }
22366                }
22367            }
22368        }
22369    }
22370
22371    private static class MoveCallbacks extends Handler {
22372        private static final int MSG_CREATED = 1;
22373        private static final int MSG_STATUS_CHANGED = 2;
22374
22375        private final RemoteCallbackList<IPackageMoveObserver>
22376                mCallbacks = new RemoteCallbackList<>();
22377
22378        private final SparseIntArray mLastStatus = new SparseIntArray();
22379
22380        public MoveCallbacks(Looper looper) {
22381            super(looper);
22382        }
22383
22384        public void register(IPackageMoveObserver callback) {
22385            mCallbacks.register(callback);
22386        }
22387
22388        public void unregister(IPackageMoveObserver callback) {
22389            mCallbacks.unregister(callback);
22390        }
22391
22392        @Override
22393        public void handleMessage(Message msg) {
22394            final SomeArgs args = (SomeArgs) msg.obj;
22395            final int n = mCallbacks.beginBroadcast();
22396            for (int i = 0; i < n; i++) {
22397                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22398                try {
22399                    invokeCallback(callback, msg.what, args);
22400                } catch (RemoteException ignored) {
22401                }
22402            }
22403            mCallbacks.finishBroadcast();
22404            args.recycle();
22405        }
22406
22407        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22408                throws RemoteException {
22409            switch (what) {
22410                case MSG_CREATED: {
22411                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22412                    break;
22413                }
22414                case MSG_STATUS_CHANGED: {
22415                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22416                    break;
22417                }
22418            }
22419        }
22420
22421        private void notifyCreated(int moveId, Bundle extras) {
22422            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22423
22424            final SomeArgs args = SomeArgs.obtain();
22425            args.argi1 = moveId;
22426            args.arg2 = extras;
22427            obtainMessage(MSG_CREATED, args).sendToTarget();
22428        }
22429
22430        private void notifyStatusChanged(int moveId, int status) {
22431            notifyStatusChanged(moveId, status, -1);
22432        }
22433
22434        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22435            Slog.v(TAG, "Move " + moveId + " status " + status);
22436
22437            final SomeArgs args = SomeArgs.obtain();
22438            args.argi1 = moveId;
22439            args.argi2 = status;
22440            args.arg3 = estMillis;
22441            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22442
22443            synchronized (mLastStatus) {
22444                mLastStatus.put(moveId, status);
22445            }
22446        }
22447    }
22448
22449    private final static class OnPermissionChangeListeners extends Handler {
22450        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22451
22452        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22453                new RemoteCallbackList<>();
22454
22455        public OnPermissionChangeListeners(Looper looper) {
22456            super(looper);
22457        }
22458
22459        @Override
22460        public void handleMessage(Message msg) {
22461            switch (msg.what) {
22462                case MSG_ON_PERMISSIONS_CHANGED: {
22463                    final int uid = msg.arg1;
22464                    handleOnPermissionsChanged(uid);
22465                } break;
22466            }
22467        }
22468
22469        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22470            mPermissionListeners.register(listener);
22471
22472        }
22473
22474        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22475            mPermissionListeners.unregister(listener);
22476        }
22477
22478        public void onPermissionsChanged(int uid) {
22479            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22480                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22481            }
22482        }
22483
22484        private void handleOnPermissionsChanged(int uid) {
22485            final int count = mPermissionListeners.beginBroadcast();
22486            try {
22487                for (int i = 0; i < count; i++) {
22488                    IOnPermissionsChangeListener callback = mPermissionListeners
22489                            .getBroadcastItem(i);
22490                    try {
22491                        callback.onPermissionsChanged(uid);
22492                    } catch (RemoteException e) {
22493                        Log.e(TAG, "Permission listener is dead", e);
22494                    }
22495                }
22496            } finally {
22497                mPermissionListeners.finishBroadcast();
22498            }
22499        }
22500    }
22501
22502    private class PackageManagerNative extends IPackageManagerNative.Stub {
22503        @Override
22504        public String[] getNamesForUids(int[] uids) throws RemoteException {
22505            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22506            // massage results so they can be parsed by the native binder
22507            for (int i = results.length - 1; i >= 0; --i) {
22508                if (results[i] == null) {
22509                    results[i] = "";
22510                }
22511            }
22512            return results;
22513        }
22514
22515        // NB: this differentiates between preloads and sideloads
22516        @Override
22517        public String getInstallerForPackage(String packageName) throws RemoteException {
22518            final String installerName = getInstallerPackageName(packageName);
22519            if (!TextUtils.isEmpty(installerName)) {
22520                return installerName;
22521            }
22522            // differentiate between preload and sideload
22523            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22524            ApplicationInfo appInfo = getApplicationInfo(packageName,
22525                                    /*flags*/ 0,
22526                                    /*userId*/ callingUser);
22527            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22528                return "preload";
22529            }
22530            return "";
22531        }
22532
22533        @Override
22534        public long getVersionCodeForPackage(String packageName) throws RemoteException {
22535            try {
22536                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22537                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22538                if (pInfo != null) {
22539                    return pInfo.getLongVersionCode();
22540                }
22541            } catch (Exception e) {
22542            }
22543            return 0;
22544        }
22545    }
22546
22547    private class PackageManagerInternalImpl extends PackageManagerInternal {
22548        @Override
22549        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22550                int flagValues, int userId) {
22551            PackageManagerService.this.updatePermissionFlags(
22552                    permName, packageName, flagMask, flagValues, userId);
22553        }
22554
22555        @Override
22556        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22557            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22558        }
22559
22560        @Override
22561        public boolean isInstantApp(String packageName, int userId) {
22562            return PackageManagerService.this.isInstantApp(packageName, userId);
22563        }
22564
22565        @Override
22566        public String getInstantAppPackageName(int uid) {
22567            return PackageManagerService.this.getInstantAppPackageName(uid);
22568        }
22569
22570        @Override
22571        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
22572            synchronized (mPackages) {
22573                return PackageManagerService.this.filterAppAccessLPr(
22574                        (PackageSetting) pkg.mExtras, callingUid, userId);
22575            }
22576        }
22577
22578        @Override
22579        public PackageParser.Package getPackage(String packageName) {
22580            synchronized (mPackages) {
22581                packageName = resolveInternalPackageNameLPr(
22582                        packageName, PackageManager.VERSION_CODE_HIGHEST);
22583                return mPackages.get(packageName);
22584            }
22585        }
22586
22587        @Override
22588        public PackageParser.Package getDisabledPackage(String packageName) {
22589            synchronized (mPackages) {
22590                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
22591                return (ps != null) ? ps.pkg : null;
22592            }
22593        }
22594
22595        @Override
22596        public String getKnownPackageName(int knownPackage, int userId) {
22597            switch(knownPackage) {
22598                case PackageManagerInternal.PACKAGE_BROWSER:
22599                    return getDefaultBrowserPackageName(userId);
22600                case PackageManagerInternal.PACKAGE_INSTALLER:
22601                    return mRequiredInstallerPackage;
22602                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
22603                    return mSetupWizardPackage;
22604                case PackageManagerInternal.PACKAGE_SYSTEM:
22605                    return "android";
22606                case PackageManagerInternal.PACKAGE_VERIFIER:
22607                    return mRequiredVerifierPackage;
22608            }
22609            return null;
22610        }
22611
22612        @Override
22613        public boolean isResolveActivityComponent(ComponentInfo component) {
22614            return mResolveActivity.packageName.equals(component.packageName)
22615                    && mResolveActivity.name.equals(component.name);
22616        }
22617
22618        @Override
22619        public void setLocationPackagesProvider(PackagesProvider provider) {
22620            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
22621        }
22622
22623        @Override
22624        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22625            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
22626        }
22627
22628        @Override
22629        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22630            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
22631        }
22632
22633        @Override
22634        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22635            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
22636        }
22637
22638        @Override
22639        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22640            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
22641        }
22642
22643        @Override
22644        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22645            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
22646        }
22647
22648        @Override
22649        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22650            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
22651        }
22652
22653        @Override
22654        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22655            synchronized (mPackages) {
22656                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22657            }
22658            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
22659        }
22660
22661        @Override
22662        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22663            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
22664                    packageName, userId);
22665        }
22666
22667        @Override
22668        public void setKeepUninstalledPackages(final List<String> packageList) {
22669            Preconditions.checkNotNull(packageList);
22670            List<String> removedFromList = null;
22671            synchronized (mPackages) {
22672                if (mKeepUninstalledPackages != null) {
22673                    final int packagesCount = mKeepUninstalledPackages.size();
22674                    for (int i = 0; i < packagesCount; i++) {
22675                        String oldPackage = mKeepUninstalledPackages.get(i);
22676                        if (packageList != null && packageList.contains(oldPackage)) {
22677                            continue;
22678                        }
22679                        if (removedFromList == null) {
22680                            removedFromList = new ArrayList<>();
22681                        }
22682                        removedFromList.add(oldPackage);
22683                    }
22684                }
22685                mKeepUninstalledPackages = new ArrayList<>(packageList);
22686                if (removedFromList != null) {
22687                    final int removedCount = removedFromList.size();
22688                    for (int i = 0; i < removedCount; i++) {
22689                        deletePackageIfUnusedLPr(removedFromList.get(i));
22690                    }
22691                }
22692            }
22693        }
22694
22695        @Override
22696        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22697            synchronized (mPackages) {
22698                return mPermissionManager.isPermissionsReviewRequired(
22699                        mPackages.get(packageName), userId);
22700            }
22701        }
22702
22703        @Override
22704        public PackageInfo getPackageInfo(
22705                String packageName, int flags, int filterCallingUid, int userId) {
22706            return PackageManagerService.this
22707                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
22708                            flags, filterCallingUid, userId);
22709        }
22710
22711        @Override
22712        public int getPackageUid(String packageName, int flags, int userId) {
22713            return PackageManagerService.this
22714                    .getPackageUid(packageName, flags, userId);
22715        }
22716
22717        @Override
22718        public ApplicationInfo getApplicationInfo(
22719                String packageName, int flags, int filterCallingUid, int userId) {
22720            return PackageManagerService.this
22721                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
22722        }
22723
22724        @Override
22725        public ActivityInfo getActivityInfo(
22726                ComponentName component, int flags, int filterCallingUid, int userId) {
22727            return PackageManagerService.this
22728                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
22729        }
22730
22731        @Override
22732        public List<ResolveInfo> queryIntentActivities(
22733                Intent intent, int flags, int filterCallingUid, int userId) {
22734            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22735            return PackageManagerService.this
22736                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
22737                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
22738        }
22739
22740        @Override
22741        public List<ResolveInfo> queryIntentServices(
22742                Intent intent, int flags, int callingUid, int userId) {
22743            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22744            return PackageManagerService.this
22745                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
22746                            false);
22747        }
22748
22749        @Override
22750        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22751                int userId) {
22752            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22753        }
22754
22755        @Override
22756        public void setDeviceAndProfileOwnerPackages(
22757                int deviceOwnerUserId, String deviceOwnerPackage,
22758                SparseArray<String> profileOwnerPackages) {
22759            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22760                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22761        }
22762
22763        @Override
22764        public boolean isPackageDataProtected(int userId, String packageName) {
22765            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22766        }
22767
22768        @Override
22769        public boolean isPackageEphemeral(int userId, String packageName) {
22770            synchronized (mPackages) {
22771                final PackageSetting ps = mSettings.mPackages.get(packageName);
22772                return ps != null ? ps.getInstantApp(userId) : false;
22773            }
22774        }
22775
22776        @Override
22777        public boolean wasPackageEverLaunched(String packageName, int userId) {
22778            synchronized (mPackages) {
22779                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22780            }
22781        }
22782
22783        @Override
22784        public void grantRuntimePermission(String packageName, String permName, int userId,
22785                boolean overridePolicy) {
22786            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
22787                    permName, packageName, overridePolicy, getCallingUid(), userId,
22788                    mPermissionCallback);
22789        }
22790
22791        @Override
22792        public void revokeRuntimePermission(String packageName, String permName, int userId,
22793                boolean overridePolicy) {
22794            mPermissionManager.revokeRuntimePermission(
22795                    permName, packageName, overridePolicy, getCallingUid(), userId,
22796                    mPermissionCallback);
22797        }
22798
22799        @Override
22800        public String getNameForUid(int uid) {
22801            return PackageManagerService.this.getNameForUid(uid);
22802        }
22803
22804        @Override
22805        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22806                Intent origIntent, String resolvedType, String callingPackage,
22807                Bundle verificationBundle, int userId) {
22808            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22809                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
22810                    userId);
22811        }
22812
22813        @Override
22814        public void grantEphemeralAccess(int userId, Intent intent,
22815                int targetAppId, int ephemeralAppId) {
22816            synchronized (mPackages) {
22817                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22818                        targetAppId, ephemeralAppId);
22819            }
22820        }
22821
22822        @Override
22823        public boolean isInstantAppInstallerComponent(ComponentName component) {
22824            synchronized (mPackages) {
22825                return mInstantAppInstallerActivity != null
22826                        && mInstantAppInstallerActivity.getComponentName().equals(component);
22827            }
22828        }
22829
22830        @Override
22831        public void pruneInstantApps() {
22832            mInstantAppRegistry.pruneInstantApps();
22833        }
22834
22835        @Override
22836        public String getSetupWizardPackageName() {
22837            return mSetupWizardPackage;
22838        }
22839
22840        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22841            if (policy != null) {
22842                mExternalSourcesPolicy = policy;
22843            }
22844        }
22845
22846        @Override
22847        public boolean isPackagePersistent(String packageName) {
22848            synchronized (mPackages) {
22849                PackageParser.Package pkg = mPackages.get(packageName);
22850                return pkg != null
22851                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22852                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22853                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22854                        : false;
22855            }
22856        }
22857
22858        @Override
22859        public boolean isLegacySystemApp(Package pkg) {
22860            synchronized (mPackages) {
22861                final PackageSetting ps = (PackageSetting) pkg.mExtras;
22862                return mPromoteSystemApps
22863                        && ps.isSystem()
22864                        && mExistingSystemPackages.contains(ps.name);
22865            }
22866        }
22867
22868        @Override
22869        public List<PackageInfo> getOverlayPackages(int userId) {
22870            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22871            synchronized (mPackages) {
22872                for (PackageParser.Package p : mPackages.values()) {
22873                    if (p.mOverlayTarget != null) {
22874                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22875                        if (pkg != null) {
22876                            overlayPackages.add(pkg);
22877                        }
22878                    }
22879                }
22880            }
22881            return overlayPackages;
22882        }
22883
22884        @Override
22885        public List<String> getTargetPackageNames(int userId) {
22886            List<String> targetPackages = new ArrayList<>();
22887            synchronized (mPackages) {
22888                for (PackageParser.Package p : mPackages.values()) {
22889                    if (p.mOverlayTarget == null) {
22890                        targetPackages.add(p.packageName);
22891                    }
22892                }
22893            }
22894            return targetPackages;
22895        }
22896
22897        @Override
22898        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
22899                @Nullable List<String> overlayPackageNames) {
22900            synchronized (mPackages) {
22901                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
22902                    Slog.e(TAG, "failed to find package " + targetPackageName);
22903                    return false;
22904                }
22905                ArrayList<String> overlayPaths = null;
22906                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
22907                    final int N = overlayPackageNames.size();
22908                    overlayPaths = new ArrayList<>(N);
22909                    for (int i = 0; i < N; i++) {
22910                        final String packageName = overlayPackageNames.get(i);
22911                        final PackageParser.Package pkg = mPackages.get(packageName);
22912                        if (pkg == null) {
22913                            Slog.e(TAG, "failed to find package " + packageName);
22914                            return false;
22915                        }
22916                        overlayPaths.add(pkg.baseCodePath);
22917                    }
22918                }
22919
22920                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
22921                ps.setOverlayPaths(overlayPaths, userId);
22922                return true;
22923            }
22924        }
22925
22926        @Override
22927        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
22928                int flags, int userId, boolean resolveForStart) {
22929            return resolveIntentInternal(
22930                    intent, resolvedType, flags, userId, resolveForStart);
22931        }
22932
22933        @Override
22934        public ResolveInfo resolveService(Intent intent, String resolvedType,
22935                int flags, int userId, int callingUid) {
22936            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
22937        }
22938
22939        @Override
22940        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
22941            return PackageManagerService.this.resolveContentProviderInternal(
22942                    name, flags, userId);
22943        }
22944
22945        @Override
22946        public void addIsolatedUid(int isolatedUid, int ownerUid) {
22947            synchronized (mPackages) {
22948                mIsolatedOwners.put(isolatedUid, ownerUid);
22949            }
22950        }
22951
22952        @Override
22953        public void removeIsolatedUid(int isolatedUid) {
22954            synchronized (mPackages) {
22955                mIsolatedOwners.delete(isolatedUid);
22956            }
22957        }
22958
22959        @Override
22960        public int getUidTargetSdkVersion(int uid) {
22961            synchronized (mPackages) {
22962                return getUidTargetSdkVersionLockedLPr(uid);
22963            }
22964        }
22965
22966        @Override
22967        public boolean canAccessInstantApps(int callingUid, int userId) {
22968            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
22969        }
22970
22971        @Override
22972        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
22973            synchronized (mPackages) {
22974                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
22975            }
22976        }
22977
22978        @Override
22979        public void notifyPackageUse(String packageName, int reason) {
22980            synchronized (mPackages) {
22981                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
22982            }
22983        }
22984    }
22985
22986    @Override
22987    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22988        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22989        synchronized (mPackages) {
22990            final long identity = Binder.clearCallingIdentity();
22991            try {
22992                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
22993                        packageNames, userId);
22994            } finally {
22995                Binder.restoreCallingIdentity(identity);
22996            }
22997        }
22998    }
22999
23000    @Override
23001    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23002        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23003        synchronized (mPackages) {
23004            final long identity = Binder.clearCallingIdentity();
23005            try {
23006                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23007                        packageNames, userId);
23008            } finally {
23009                Binder.restoreCallingIdentity(identity);
23010            }
23011        }
23012    }
23013
23014    private static void enforceSystemOrPhoneCaller(String tag) {
23015        int callingUid = Binder.getCallingUid();
23016        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23017            throw new SecurityException(
23018                    "Cannot call " + tag + " from UID " + callingUid);
23019        }
23020    }
23021
23022    boolean isHistoricalPackageUsageAvailable() {
23023        return mPackageUsage.isHistoricalPackageUsageAvailable();
23024    }
23025
23026    /**
23027     * Return a <b>copy</b> of the collection of packages known to the package manager.
23028     * @return A copy of the values of mPackages.
23029     */
23030    Collection<PackageParser.Package> getPackages() {
23031        synchronized (mPackages) {
23032            return new ArrayList<>(mPackages.values());
23033        }
23034    }
23035
23036    /**
23037     * Logs process start information (including base APK hash) to the security log.
23038     * @hide
23039     */
23040    @Override
23041    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23042            String apkFile, int pid) {
23043        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23044            return;
23045        }
23046        if (!SecurityLog.isLoggingEnabled()) {
23047            return;
23048        }
23049        Bundle data = new Bundle();
23050        data.putLong("startTimestamp", System.currentTimeMillis());
23051        data.putString("processName", processName);
23052        data.putInt("uid", uid);
23053        data.putString("seinfo", seinfo);
23054        data.putString("apkFile", apkFile);
23055        data.putInt("pid", pid);
23056        Message msg = mProcessLoggingHandler.obtainMessage(
23057                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23058        msg.setData(data);
23059        mProcessLoggingHandler.sendMessage(msg);
23060    }
23061
23062    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23063        return mCompilerStats.getPackageStats(pkgName);
23064    }
23065
23066    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23067        return getOrCreateCompilerPackageStats(pkg.packageName);
23068    }
23069
23070    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23071        return mCompilerStats.getOrCreatePackageStats(pkgName);
23072    }
23073
23074    public void deleteCompilerPackageStats(String pkgName) {
23075        mCompilerStats.deletePackageStats(pkgName);
23076    }
23077
23078    @Override
23079    public int getInstallReason(String packageName, int userId) {
23080        final int callingUid = Binder.getCallingUid();
23081        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23082                true /* requireFullPermission */, false /* checkShell */,
23083                "get install reason");
23084        synchronized (mPackages) {
23085            final PackageSetting ps = mSettings.mPackages.get(packageName);
23086            if (filterAppAccessLPr(ps, callingUid, userId)) {
23087                return PackageManager.INSTALL_REASON_UNKNOWN;
23088            }
23089            if (ps != null) {
23090                return ps.getInstallReason(userId);
23091            }
23092        }
23093        return PackageManager.INSTALL_REASON_UNKNOWN;
23094    }
23095
23096    @Override
23097    public boolean canRequestPackageInstalls(String packageName, int userId) {
23098        return canRequestPackageInstallsInternal(packageName, 0, userId,
23099                true /* throwIfPermNotDeclared*/);
23100    }
23101
23102    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23103            boolean throwIfPermNotDeclared) {
23104        int callingUid = Binder.getCallingUid();
23105        int uid = getPackageUid(packageName, 0, userId);
23106        if (callingUid != uid && callingUid != Process.ROOT_UID
23107                && callingUid != Process.SYSTEM_UID) {
23108            throw new SecurityException(
23109                    "Caller uid " + callingUid + " does not own package " + packageName);
23110        }
23111        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23112        if (info == null) {
23113            return false;
23114        }
23115        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23116            return false;
23117        }
23118        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23119        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23120        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23121            if (throwIfPermNotDeclared) {
23122                throw new SecurityException("Need to declare " + appOpPermission
23123                        + " to call this api");
23124            } else {
23125                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23126                return false;
23127            }
23128        }
23129        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23130            return false;
23131        }
23132        if (mExternalSourcesPolicy != null) {
23133            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23134            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23135                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23136            }
23137        }
23138        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23139    }
23140
23141    @Override
23142    public ComponentName getInstantAppResolverSettingsComponent() {
23143        return mInstantAppResolverSettingsComponent;
23144    }
23145
23146    @Override
23147    public ComponentName getInstantAppInstallerComponent() {
23148        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23149            return null;
23150        }
23151        return mInstantAppInstallerActivity == null
23152                ? null : mInstantAppInstallerActivity.getComponentName();
23153    }
23154
23155    @Override
23156    public String getInstantAppAndroidId(String packageName, int userId) {
23157        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23158                "getInstantAppAndroidId");
23159        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23160                true /* requireFullPermission */, false /* checkShell */,
23161                "getInstantAppAndroidId");
23162        // Make sure the target is an Instant App.
23163        if (!isInstantApp(packageName, userId)) {
23164            return null;
23165        }
23166        synchronized (mPackages) {
23167            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23168        }
23169    }
23170
23171    boolean canHaveOatDir(String packageName) {
23172        synchronized (mPackages) {
23173            PackageParser.Package p = mPackages.get(packageName);
23174            if (p == null) {
23175                return false;
23176            }
23177            return p.canHaveOatDir();
23178        }
23179    }
23180
23181    private String getOatDir(PackageParser.Package pkg) {
23182        if (!pkg.canHaveOatDir()) {
23183            return null;
23184        }
23185        File codePath = new File(pkg.codePath);
23186        if (codePath.isDirectory()) {
23187            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23188        }
23189        return null;
23190    }
23191
23192    void deleteOatArtifactsOfPackage(String packageName) {
23193        final String[] instructionSets;
23194        final List<String> codePaths;
23195        final String oatDir;
23196        final PackageParser.Package pkg;
23197        synchronized (mPackages) {
23198            pkg = mPackages.get(packageName);
23199        }
23200        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23201        codePaths = pkg.getAllCodePaths();
23202        oatDir = getOatDir(pkg);
23203
23204        for (String codePath : codePaths) {
23205            for (String isa : instructionSets) {
23206                try {
23207                    mInstaller.deleteOdex(codePath, isa, oatDir);
23208                } catch (InstallerException e) {
23209                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23210                }
23211            }
23212        }
23213    }
23214
23215    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23216        Set<String> unusedPackages = new HashSet<>();
23217        long currentTimeInMillis = System.currentTimeMillis();
23218        synchronized (mPackages) {
23219            for (PackageParser.Package pkg : mPackages.values()) {
23220                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23221                if (ps == null) {
23222                    continue;
23223                }
23224                PackageDexUsage.PackageUseInfo packageUseInfo =
23225                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23226                if (PackageManagerServiceUtils
23227                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23228                                downgradeTimeThresholdMillis, packageUseInfo,
23229                                pkg.getLatestPackageUseTimeInMills(),
23230                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23231                    unusedPackages.add(pkg.packageName);
23232                }
23233            }
23234        }
23235        return unusedPackages;
23236    }
23237}
23238
23239interface PackageSender {
23240    void sendPackageBroadcast(final String action, final String pkg,
23241        final Bundle extras, final int flags, final String targetPkg,
23242        final IIntentReceiver finishedReceiver, final int[] userIds);
23243    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23244        boolean includeStopped, int appId, int... userIds);
23245}
23246