PackageManagerService.java revision 232d29e0cdfd906da6b23c328c132bfc30607142
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;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
115import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
116
117import android.Manifest;
118import android.annotation.IntDef;
119import android.annotation.NonNull;
120import android.annotation.Nullable;
121import android.app.ActivityManager;
122import android.app.AppOpsManager;
123import android.app.IActivityManager;
124import android.app.ResourcesManager;
125import android.app.admin.IDevicePolicyManager;
126import android.app.admin.SecurityLog;
127import android.app.backup.IBackupManager;
128import android.content.BroadcastReceiver;
129import android.content.ComponentName;
130import android.content.ContentResolver;
131import android.content.Context;
132import android.content.IIntentReceiver;
133import android.content.Intent;
134import android.content.IntentFilter;
135import android.content.IntentSender;
136import android.content.IntentSender.SendIntentException;
137import android.content.ServiceConnection;
138import android.content.pm.ActivityInfo;
139import android.content.pm.ApplicationInfo;
140import android.content.pm.AppsQueryHelper;
141import android.content.pm.AuxiliaryResolveInfo;
142import android.content.pm.ChangedPackages;
143import android.content.pm.ComponentInfo;
144import android.content.pm.FallbackCategoryProvider;
145import android.content.pm.FeatureInfo;
146import android.content.pm.IDexModuleRegisterCallback;
147import android.content.pm.IOnPermissionsChangeListener;
148import android.content.pm.IPackageDataObserver;
149import android.content.pm.IPackageDeleteObserver;
150import android.content.pm.IPackageDeleteObserver2;
151import android.content.pm.IPackageInstallObserver2;
152import android.content.pm.IPackageInstaller;
153import android.content.pm.IPackageManager;
154import android.content.pm.IPackageManagerNative;
155import android.content.pm.IPackageMoveObserver;
156import android.content.pm.IPackageStatsObserver;
157import android.content.pm.InstantAppInfo;
158import android.content.pm.InstantAppRequest;
159import android.content.pm.InstantAppResolveInfo;
160import android.content.pm.InstrumentationInfo;
161import android.content.pm.IntentFilterVerificationInfo;
162import android.content.pm.KeySet;
163import android.content.pm.PackageCleanItem;
164import android.content.pm.PackageInfo;
165import android.content.pm.PackageInfoLite;
166import android.content.pm.PackageInstaller;
167import android.content.pm.PackageManager;
168import android.content.pm.PackageManagerInternal;
169import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
170import android.content.pm.PackageParser;
171import android.content.pm.PackageParser.ActivityIntentInfo;
172import android.content.pm.PackageParser.Package;
173import android.content.pm.PackageParser.PackageLite;
174import android.content.pm.PackageParser.PackageParserException;
175import android.content.pm.PackageParser.ParseFlags;
176import android.content.pm.PackageStats;
177import android.content.pm.PackageUserState;
178import android.content.pm.ParceledListSlice;
179import android.content.pm.PermissionGroupInfo;
180import android.content.pm.PermissionInfo;
181import android.content.pm.ProviderInfo;
182import android.content.pm.ResolveInfo;
183import android.content.pm.ServiceInfo;
184import android.content.pm.SharedLibraryInfo;
185import android.content.pm.Signature;
186import android.content.pm.UserInfo;
187import android.content.pm.VerifierDeviceIdentity;
188import android.content.pm.VerifierInfo;
189import android.content.pm.VersionedPackage;
190import android.content.res.Resources;
191import android.database.ContentObserver;
192import android.graphics.Bitmap;
193import android.hardware.display.DisplayManager;
194import android.net.Uri;
195import android.os.Binder;
196import android.os.Build;
197import android.os.Bundle;
198import android.os.Debug;
199import android.os.Environment;
200import android.os.Environment.UserEnvironment;
201import android.os.FileUtils;
202import android.os.Handler;
203import android.os.IBinder;
204import android.os.Looper;
205import android.os.Message;
206import android.os.Parcel;
207import android.os.ParcelFileDescriptor;
208import android.os.PatternMatcher;
209import android.os.Process;
210import android.os.RemoteCallbackList;
211import android.os.RemoteException;
212import android.os.ResultReceiver;
213import android.os.SELinux;
214import android.os.ServiceManager;
215import android.os.ShellCallback;
216import android.os.SystemClock;
217import android.os.SystemProperties;
218import android.os.Trace;
219import android.os.UserHandle;
220import android.os.UserManager;
221import android.os.UserManagerInternal;
222import android.os.storage.IStorageManager;
223import android.os.storage.StorageEventListener;
224import android.os.storage.StorageManager;
225import android.os.storage.StorageManagerInternal;
226import android.os.storage.VolumeInfo;
227import android.os.storage.VolumeRecord;
228import android.provider.Settings.Global;
229import android.provider.Settings.Secure;
230import android.security.KeyStore;
231import android.security.SystemKeyStore;
232import android.service.pm.PackageServiceDumpProto;
233import android.system.ErrnoException;
234import android.system.Os;
235import android.text.TextUtils;
236import android.text.format.DateUtils;
237import android.util.ArrayMap;
238import android.util.ArraySet;
239import android.util.Base64;
240import android.util.DisplayMetrics;
241import android.util.EventLog;
242import android.util.ExceptionUtils;
243import android.util.Log;
244import android.util.LogPrinter;
245import android.util.MathUtils;
246import android.util.PackageUtils;
247import android.util.Pair;
248import android.util.PrintStreamPrinter;
249import android.util.Slog;
250import android.util.SparseArray;
251import android.util.SparseBooleanArray;
252import android.util.SparseIntArray;
253import android.util.TimingsTraceLog;
254import android.util.Xml;
255import android.util.jar.StrictJarFile;
256import android.util.proto.ProtoOutputStream;
257import android.view.Display;
258
259import com.android.internal.R;
260import com.android.internal.annotations.GuardedBy;
261import com.android.internal.app.IMediaContainerService;
262import com.android.internal.app.ResolverActivity;
263import com.android.internal.content.NativeLibraryHelper;
264import com.android.internal.content.PackageHelper;
265import com.android.internal.logging.MetricsLogger;
266import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
267import com.android.internal.os.IParcelFileDescriptorFactory;
268import com.android.internal.os.RoSystemProperties;
269import com.android.internal.os.SomeArgs;
270import com.android.internal.os.Zygote;
271import com.android.internal.telephony.CarrierAppUtils;
272import com.android.internal.util.ArrayUtils;
273import com.android.internal.util.ConcurrentUtils;
274import com.android.internal.util.DumpUtils;
275import com.android.internal.util.FastPrintWriter;
276import com.android.internal.util.FastXmlSerializer;
277import com.android.internal.util.IndentingPrintWriter;
278import com.android.internal.util.Preconditions;
279import com.android.internal.util.XmlUtils;
280import com.android.server.AttributeCache;
281import com.android.server.DeviceIdleController;
282import com.android.server.EventLogTags;
283import com.android.server.FgThread;
284import com.android.server.IntentResolver;
285import com.android.server.LocalServices;
286import com.android.server.LockGuard;
287import com.android.server.ServiceThread;
288import com.android.server.SystemConfig;
289import com.android.server.SystemServerInitThreadPool;
290import com.android.server.Watchdog;
291import com.android.server.net.NetworkPolicyManagerInternal;
292import com.android.server.pm.Installer.InstallerException;
293import com.android.server.pm.Settings.DatabaseVersion;
294import com.android.server.pm.Settings.VersionInfo;
295import com.android.server.pm.dex.DexManager;
296import com.android.server.pm.dex.DexoptOptions;
297import com.android.server.pm.dex.PackageDexUsage;
298import com.android.server.pm.permission.BasePermission;
299import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
300import com.android.server.pm.permission.PermissionManagerService;
301import com.android.server.pm.permission.PermissionManagerInternal;
302import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
303import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
304import com.android.server.pm.permission.PermissionsState;
305import com.android.server.pm.permission.PermissionsState.PermissionState;
306import com.android.server.storage.DeviceStorageMonitorInternal;
307
308import dalvik.system.CloseGuard;
309import dalvik.system.DexFile;
310import dalvik.system.VMRuntime;
311
312import libcore.io.IoUtils;
313import libcore.io.Streams;
314import libcore.util.EmptyArray;
315
316import org.xmlpull.v1.XmlPullParser;
317import org.xmlpull.v1.XmlPullParserException;
318import org.xmlpull.v1.XmlSerializer;
319
320import java.io.BufferedOutputStream;
321import java.io.BufferedReader;
322import java.io.ByteArrayInputStream;
323import java.io.ByteArrayOutputStream;
324import java.io.File;
325import java.io.FileDescriptor;
326import java.io.FileInputStream;
327import java.io.FileOutputStream;
328import java.io.FileReader;
329import java.io.FilenameFilter;
330import java.io.IOException;
331import java.io.InputStream;
332import java.io.OutputStream;
333import java.io.PrintWriter;
334import java.lang.annotation.Retention;
335import java.lang.annotation.RetentionPolicy;
336import java.nio.charset.StandardCharsets;
337import java.security.DigestInputStream;
338import java.security.MessageDigest;
339import java.security.NoSuchAlgorithmException;
340import java.security.PublicKey;
341import java.security.SecureRandom;
342import java.security.cert.Certificate;
343import java.security.cert.CertificateEncodingException;
344import java.security.cert.CertificateException;
345import java.text.SimpleDateFormat;
346import java.util.ArrayList;
347import java.util.Arrays;
348import java.util.Collection;
349import java.util.Collections;
350import java.util.Comparator;
351import java.util.Date;
352import java.util.HashMap;
353import java.util.HashSet;
354import java.util.Iterator;
355import java.util.LinkedHashSet;
356import java.util.List;
357import java.util.Map;
358import java.util.Objects;
359import java.util.Set;
360import java.util.concurrent.CountDownLatch;
361import java.util.concurrent.Future;
362import java.util.concurrent.TimeUnit;
363import java.util.concurrent.atomic.AtomicBoolean;
364import java.util.concurrent.atomic.AtomicInteger;
365import java.util.zip.GZIPInputStream;
366
367/**
368 * Keep track of all those APKs everywhere.
369 * <p>
370 * Internally there are two important locks:
371 * <ul>
372 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
373 * and other related state. It is a fine-grained lock that should only be held
374 * momentarily, as it's one of the most contended locks in the system.
375 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
376 * operations typically involve heavy lifting of application data on disk. Since
377 * {@code installd} is single-threaded, and it's operations can often be slow,
378 * this lock should never be acquired while already holding {@link #mPackages}.
379 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
380 * holding {@link #mInstallLock}.
381 * </ul>
382 * Many internal methods rely on the caller to hold the appropriate locks, and
383 * this contract is expressed through method name suffixes:
384 * <ul>
385 * <li>fooLI(): the caller must hold {@link #mInstallLock}
386 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
387 * being modified must be frozen
388 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
389 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
390 * </ul>
391 * <p>
392 * Because this class is very central to the platform's security; please run all
393 * CTS and unit tests whenever making modifications:
394 *
395 * <pre>
396 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
397 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
398 * </pre>
399 */
400public class PackageManagerService extends IPackageManager.Stub
401        implements PackageSender {
402    static final String TAG = "PackageManager";
403    public static final boolean DEBUG_SETTINGS = false;
404    static final boolean DEBUG_PREFERRED = false;
405    static final boolean DEBUG_UPGRADE = false;
406    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
407    private static final boolean DEBUG_BACKUP = false;
408    public static final boolean DEBUG_INSTALL = false;
409    public static final boolean DEBUG_REMOVE = false;
410    private static final boolean DEBUG_BROADCASTS = false;
411    private static final boolean DEBUG_SHOW_INFO = false;
412    private static final boolean DEBUG_PACKAGE_INFO = false;
413    private static final boolean DEBUG_INTENT_MATCHING = false;
414    public static final boolean DEBUG_PACKAGE_SCANNING = false;
415    private static final boolean DEBUG_VERIFY = false;
416    private static final boolean DEBUG_FILTERS = false;
417    public static final boolean DEBUG_PERMISSIONS = false;
418    private static final boolean DEBUG_SHARED_LIBRARIES = false;
419    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
420
421    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
422    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
423    // user, but by default initialize to this.
424    public static final boolean DEBUG_DEXOPT = false;
425
426    private static final boolean DEBUG_ABI_SELECTION = false;
427    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
428    private static final boolean DEBUG_TRIAGED_MISSING = false;
429    private static final boolean DEBUG_APP_DATA = false;
430
431    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
432    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
433
434    private static final boolean HIDE_EPHEMERAL_APIS = false;
435
436    private static final boolean ENABLE_FREE_CACHE_V2 =
437            SystemProperties.getBoolean("fw.free_cache_v2", true);
438
439    private static final int RADIO_UID = Process.PHONE_UID;
440    private static final int LOG_UID = Process.LOG_UID;
441    private static final int NFC_UID = Process.NFC_UID;
442    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
443    private static final int SHELL_UID = Process.SHELL_UID;
444
445    // Suffix used during package installation when copying/moving
446    // package apks to install directory.
447    private static final String INSTALL_PACKAGE_SUFFIX = "-";
448
449    static final int SCAN_NO_DEX = 1<<0;
450    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
451    static final int SCAN_NEW_INSTALL = 1<<2;
452    static final int SCAN_UPDATE_TIME = 1<<3;
453    static final int SCAN_BOOTING = 1<<4;
454    static final int SCAN_TRUSTED_OVERLAY = 1<<5;
455    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
456    static final int SCAN_REQUIRE_KNOWN = 1<<7;
457    static final int SCAN_MOVE = 1<<8;
458    static final int SCAN_INITIAL = 1<<9;
459    static final int SCAN_CHECK_ONLY = 1<<10;
460    static final int SCAN_DONT_KILL_APP = 1<<11;
461    static final int SCAN_IGNORE_FROZEN = 1<<12;
462    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
463    static final int SCAN_AS_INSTANT_APP = 1<<14;
464    static final int SCAN_AS_FULL_APP = 1<<15;
465    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
466    static final int SCAN_AS_SYSTEM = 1<<17;
467    static final int SCAN_AS_PRIVILEGED = 1<<18;
468    static final int SCAN_AS_OEM = 1<<19;
469
470    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
471            SCAN_NO_DEX,
472            SCAN_UPDATE_SIGNATURE,
473            SCAN_NEW_INSTALL,
474            SCAN_UPDATE_TIME,
475            SCAN_BOOTING,
476            SCAN_TRUSTED_OVERLAY,
477            SCAN_DELETE_DATA_ON_FAILURES,
478            SCAN_REQUIRE_KNOWN,
479            SCAN_MOVE,
480            SCAN_INITIAL,
481            SCAN_CHECK_ONLY,
482            SCAN_DONT_KILL_APP,
483            SCAN_IGNORE_FROZEN,
484            SCAN_FIRST_BOOT_OR_UPGRADE,
485            SCAN_AS_INSTANT_APP,
486            SCAN_AS_FULL_APP,
487            SCAN_AS_VIRTUAL_PRELOAD,
488    })
489    @Retention(RetentionPolicy.SOURCE)
490    public @interface ScanFlags {}
491
492    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
493    /** Extension of the compressed packages */
494    public final static String COMPRESSED_EXTENSION = ".gz";
495    /** Suffix of stub packages on the system partition */
496    public final static String STUB_SUFFIX = "-Stub";
497
498    private static final int[] EMPTY_INT_ARRAY = new int[0];
499
500    private static final int TYPE_UNKNOWN = 0;
501    private static final int TYPE_ACTIVITY = 1;
502    private static final int TYPE_RECEIVER = 2;
503    private static final int TYPE_SERVICE = 3;
504    private static final int TYPE_PROVIDER = 4;
505    @IntDef(prefix = { "TYPE_" }, value = {
506            TYPE_UNKNOWN,
507            TYPE_ACTIVITY,
508            TYPE_RECEIVER,
509            TYPE_SERVICE,
510            TYPE_PROVIDER,
511    })
512    @Retention(RetentionPolicy.SOURCE)
513    public @interface ComponentType {}
514
515    /**
516     * Timeout (in milliseconds) after which the watchdog should declare that
517     * our handler thread is wedged.  The usual default for such things is one
518     * minute but we sometimes do very lengthy I/O operations on this thread,
519     * such as installing multi-gigabyte applications, so ours needs to be longer.
520     */
521    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
522
523    /**
524     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
525     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
526     * settings entry if available, otherwise we use the hardcoded default.  If it's been
527     * more than this long since the last fstrim, we force one during the boot sequence.
528     *
529     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
530     * one gets run at the next available charging+idle time.  This final mandatory
531     * no-fstrim check kicks in only of the other scheduling criteria is never met.
532     */
533    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
534
535    /**
536     * Whether verification is enabled by default.
537     */
538    private static final boolean DEFAULT_VERIFY_ENABLE = true;
539
540    /**
541     * The default maximum time to wait for the verification agent to return in
542     * milliseconds.
543     */
544    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
545
546    /**
547     * The default response for package verification timeout.
548     *
549     * This can be either PackageManager.VERIFICATION_ALLOW or
550     * PackageManager.VERIFICATION_REJECT.
551     */
552    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
553
554    public static final String PLATFORM_PACKAGE_NAME = "android";
555
556    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
557
558    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
559            DEFAULT_CONTAINER_PACKAGE,
560            "com.android.defcontainer.DefaultContainerService");
561
562    private static final String KILL_APP_REASON_GIDS_CHANGED =
563            "permission grant or revoke changed gids";
564
565    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
566            "permissions revoked";
567
568    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
569
570    private static final String PACKAGE_SCHEME = "package";
571
572    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
573
574    /** Canonical intent used to identify what counts as a "web browser" app */
575    private static final Intent sBrowserIntent;
576    static {
577        sBrowserIntent = new Intent();
578        sBrowserIntent.setAction(Intent.ACTION_VIEW);
579        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
580        sBrowserIntent.setData(Uri.parse("http:"));
581    }
582
583    /**
584     * The set of all protected actions [i.e. those actions for which a high priority
585     * intent filter is disallowed].
586     */
587    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
588    static {
589        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
590        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
591        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
592        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
593    }
594
595    // Compilation reasons.
596    public static final int REASON_FIRST_BOOT = 0;
597    public static final int REASON_BOOT = 1;
598    public static final int REASON_INSTALL = 2;
599    public static final int REASON_BACKGROUND_DEXOPT = 3;
600    public static final int REASON_AB_OTA = 4;
601    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
602    public static final int REASON_SHARED = 6;
603
604    public static final int REASON_LAST = REASON_SHARED;
605
606    /**
607     * Version number for the package parser cache. Increment this whenever the format or
608     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
609     */
610    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
611
612    /**
613     * Whether the package parser cache is enabled.
614     */
615    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
616
617    final ServiceThread mHandlerThread;
618
619    final PackageHandler mHandler;
620
621    private final ProcessLoggingHandler mProcessLoggingHandler;
622
623    /**
624     * Messages for {@link #mHandler} that need to wait for system ready before
625     * being dispatched.
626     */
627    private ArrayList<Message> mPostSystemReadyMessages;
628
629    final int mSdkVersion = Build.VERSION.SDK_INT;
630
631    final Context mContext;
632    final boolean mFactoryTest;
633    final boolean mOnlyCore;
634    final DisplayMetrics mMetrics;
635    final int mDefParseFlags;
636    final String[] mSeparateProcesses;
637    final boolean mIsUpgrade;
638    final boolean mIsPreNUpgrade;
639    final boolean mIsPreNMR1Upgrade;
640
641    // Have we told the Activity Manager to whitelist the default container service by uid yet?
642    @GuardedBy("mPackages")
643    boolean mDefaultContainerWhitelisted = false;
644
645    @GuardedBy("mPackages")
646    private boolean mDexOptDialogShown;
647
648    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
649    // LOCK HELD.  Can be called with mInstallLock held.
650    @GuardedBy("mInstallLock")
651    final Installer mInstaller;
652
653    /** Directory where installed third-party apps stored */
654    final File mAppInstallDir;
655
656    /**
657     * Directory to which applications installed internally have their
658     * 32 bit native libraries copied.
659     */
660    private File mAppLib32InstallDir;
661
662    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
663    // apps.
664    final File mDrmAppPrivateInstallDir;
665
666    // ----------------------------------------------------------------
667
668    // Lock for state used when installing and doing other long running
669    // operations.  Methods that must be called with this lock held have
670    // the suffix "LI".
671    final Object mInstallLock = new Object();
672
673    // ----------------------------------------------------------------
674
675    // Keys are String (package name), values are Package.  This also serves
676    // as the lock for the global state.  Methods that must be called with
677    // this lock held have the prefix "LP".
678    @GuardedBy("mPackages")
679    final ArrayMap<String, PackageParser.Package> mPackages =
680            new ArrayMap<String, PackageParser.Package>();
681
682    final ArrayMap<String, Set<String>> mKnownCodebase =
683            new ArrayMap<String, Set<String>>();
684
685    // Keys are isolated uids and values are the uid of the application
686    // that created the isolated proccess.
687    @GuardedBy("mPackages")
688    final SparseIntArray mIsolatedOwners = new SparseIntArray();
689
690    /**
691     * Tracks new system packages [received in an OTA] that we expect to
692     * find updated user-installed versions. Keys are package name, values
693     * are package location.
694     */
695    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
696    /**
697     * Tracks high priority intent filters for protected actions. During boot, certain
698     * filter actions are protected and should never be allowed to have a high priority
699     * intent filter for them. However, there is one, and only one exception -- the
700     * setup wizard. It must be able to define a high priority intent filter for these
701     * actions to ensure there are no escapes from the wizard. We need to delay processing
702     * of these during boot as we need to look at all of the system packages in order
703     * to know which component is the setup wizard.
704     */
705    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
706    /**
707     * Whether or not processing protected filters should be deferred.
708     */
709    private boolean mDeferProtectedFilters = true;
710
711    /**
712     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
713     */
714    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
715    /**
716     * Whether or not system app permissions should be promoted from install to runtime.
717     */
718    boolean mPromoteSystemApps;
719
720    @GuardedBy("mPackages")
721    final Settings mSettings;
722
723    /**
724     * Set of package names that are currently "frozen", which means active
725     * surgery is being done on the code/data for that package. The platform
726     * will refuse to launch frozen packages to avoid race conditions.
727     *
728     * @see PackageFreezer
729     */
730    @GuardedBy("mPackages")
731    final ArraySet<String> mFrozenPackages = new ArraySet<>();
732
733    final ProtectedPackages mProtectedPackages;
734
735    @GuardedBy("mLoadedVolumes")
736    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
737
738    boolean mFirstBoot;
739
740    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
741
742    @GuardedBy("mAvailableFeatures")
743    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
744
745    // If mac_permissions.xml was found for seinfo labeling.
746    boolean mFoundPolicyFile;
747
748    private final InstantAppRegistry mInstantAppRegistry;
749
750    @GuardedBy("mPackages")
751    int mChangedPackagesSequenceNumber;
752    /**
753     * List of changed [installed, removed or updated] packages.
754     * mapping from user id -> sequence number -> package name
755     */
756    @GuardedBy("mPackages")
757    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
758    /**
759     * The sequence number of the last change to a package.
760     * mapping from user id -> package name -> sequence number
761     */
762    @GuardedBy("mPackages")
763    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
764
765    class PackageParserCallback implements PackageParser.Callback {
766        @Override public final boolean hasFeature(String feature) {
767            return PackageManagerService.this.hasSystemFeature(feature, 0);
768        }
769
770        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
771                Collection<PackageParser.Package> allPackages, String targetPackageName) {
772            List<PackageParser.Package> overlayPackages = null;
773            for (PackageParser.Package p : allPackages) {
774                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
775                    if (overlayPackages == null) {
776                        overlayPackages = new ArrayList<PackageParser.Package>();
777                    }
778                    overlayPackages.add(p);
779                }
780            }
781            if (overlayPackages != null) {
782                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
783                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
784                        return p1.mOverlayPriority - p2.mOverlayPriority;
785                    }
786                };
787                Collections.sort(overlayPackages, cmp);
788            }
789            return overlayPackages;
790        }
791
792        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
793                String targetPackageName, String targetPath) {
794            if ("android".equals(targetPackageName)) {
795                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
796                // native AssetManager.
797                return null;
798            }
799            List<PackageParser.Package> overlayPackages =
800                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
801            if (overlayPackages == null || overlayPackages.isEmpty()) {
802                return null;
803            }
804            List<String> overlayPathList = null;
805            for (PackageParser.Package overlayPackage : overlayPackages) {
806                if (targetPath == null) {
807                    if (overlayPathList == null) {
808                        overlayPathList = new ArrayList<String>();
809                    }
810                    overlayPathList.add(overlayPackage.baseCodePath);
811                    continue;
812                }
813
814                try {
815                    // Creates idmaps for system to parse correctly the Android manifest of the
816                    // target package.
817                    //
818                    // OverlayManagerService will update each of them with a correct gid from its
819                    // target package app id.
820                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
821                            UserHandle.getSharedAppGid(
822                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
823                    if (overlayPathList == null) {
824                        overlayPathList = new ArrayList<String>();
825                    }
826                    overlayPathList.add(overlayPackage.baseCodePath);
827                } catch (InstallerException e) {
828                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
829                            overlayPackage.baseCodePath);
830                }
831            }
832            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
833        }
834
835        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
836            synchronized (mPackages) {
837                return getStaticOverlayPathsLocked(
838                        mPackages.values(), targetPackageName, targetPath);
839            }
840        }
841
842        @Override public final String[] getOverlayApks(String targetPackageName) {
843            return getStaticOverlayPaths(targetPackageName, null);
844        }
845
846        @Override public final String[] getOverlayPaths(String targetPackageName,
847                String targetPath) {
848            return getStaticOverlayPaths(targetPackageName, targetPath);
849        }
850    }
851
852    class ParallelPackageParserCallback extends PackageParserCallback {
853        List<PackageParser.Package> mOverlayPackages = null;
854
855        void findStaticOverlayPackages() {
856            synchronized (mPackages) {
857                for (PackageParser.Package p : mPackages.values()) {
858                    if (p.mIsStaticOverlay) {
859                        if (mOverlayPackages == null) {
860                            mOverlayPackages = new ArrayList<PackageParser.Package>();
861                        }
862                        mOverlayPackages.add(p);
863                    }
864                }
865            }
866        }
867
868        @Override
869        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
870            // We can trust mOverlayPackages without holding mPackages because package uninstall
871            // can't happen while running parallel parsing.
872            // Moreover holding mPackages on each parsing thread causes dead-lock.
873            return mOverlayPackages == null ? null :
874                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
875        }
876    }
877
878    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
879    final ParallelPackageParserCallback mParallelPackageParserCallback =
880            new ParallelPackageParserCallback();
881
882    public static final class SharedLibraryEntry {
883        public final @Nullable String path;
884        public final @Nullable String apk;
885        public final @NonNull SharedLibraryInfo info;
886
887        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
888                String declaringPackageName, int declaringPackageVersionCode) {
889            path = _path;
890            apk = _apk;
891            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
892                    declaringPackageName, declaringPackageVersionCode), null);
893        }
894    }
895
896    // Currently known shared libraries.
897    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
898    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
899            new ArrayMap<>();
900
901    // All available activities, for your resolving pleasure.
902    final ActivityIntentResolver mActivities =
903            new ActivityIntentResolver();
904
905    // All available receivers, for your resolving pleasure.
906    final ActivityIntentResolver mReceivers =
907            new ActivityIntentResolver();
908
909    // All available services, for your resolving pleasure.
910    final ServiceIntentResolver mServices = new ServiceIntentResolver();
911
912    // All available providers, for your resolving pleasure.
913    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
914
915    // Mapping from provider base names (first directory in content URI codePath)
916    // to the provider information.
917    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
918            new ArrayMap<String, PackageParser.Provider>();
919
920    // Mapping from instrumentation class names to info about them.
921    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
922            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
923
924    // Packages whose data we have transfered into another package, thus
925    // should no longer exist.
926    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
927
928    // Broadcast actions that are only available to the system.
929    @GuardedBy("mProtectedBroadcasts")
930    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
931
932    /** List of packages waiting for verification. */
933    final SparseArray<PackageVerificationState> mPendingVerification
934            = new SparseArray<PackageVerificationState>();
935
936    final PackageInstallerService mInstallerService;
937
938    private final PackageDexOptimizer mPackageDexOptimizer;
939    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
940    // is used by other apps).
941    private final DexManager mDexManager;
942
943    private AtomicInteger mNextMoveId = new AtomicInteger();
944    private final MoveCallbacks mMoveCallbacks;
945
946    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
947
948    // Cache of users who need badging.
949    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
950
951    /** Token for keys in mPendingVerification. */
952    private int mPendingVerificationToken = 0;
953
954    volatile boolean mSystemReady;
955    volatile boolean mSafeMode;
956    volatile boolean mHasSystemUidErrors;
957    private volatile boolean mEphemeralAppsDisabled;
958
959    ApplicationInfo mAndroidApplication;
960    final ActivityInfo mResolveActivity = new ActivityInfo();
961    final ResolveInfo mResolveInfo = new ResolveInfo();
962    ComponentName mResolveComponentName;
963    PackageParser.Package mPlatformPackage;
964    ComponentName mCustomResolverComponentName;
965
966    boolean mResolverReplaced = false;
967
968    private final @Nullable ComponentName mIntentFilterVerifierComponent;
969    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
970
971    private int mIntentFilterVerificationToken = 0;
972
973    /** The service connection to the ephemeral resolver */
974    final EphemeralResolverConnection mInstantAppResolverConnection;
975    /** Component used to show resolver settings for Instant Apps */
976    final ComponentName mInstantAppResolverSettingsComponent;
977
978    /** Activity used to install instant applications */
979    ActivityInfo mInstantAppInstallerActivity;
980    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
981
982    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
983            = new SparseArray<IntentFilterVerificationState>();
984
985    // TODO remove this and go through mPermissonManager directly
986    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
987    private final PermissionManagerInternal mPermissionManager;
988
989    // List of packages names to keep cached, even if they are uninstalled for all users
990    private List<String> mKeepUninstalledPackages;
991
992    private UserManagerInternal mUserManagerInternal;
993
994    private DeviceIdleController.LocalService mDeviceIdleController;
995
996    private File mCacheDir;
997
998    private Future<?> mPrepareAppDataFuture;
999
1000    private static class IFVerificationParams {
1001        PackageParser.Package pkg;
1002        boolean replacing;
1003        int userId;
1004        int verifierUid;
1005
1006        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1007                int _userId, int _verifierUid) {
1008            pkg = _pkg;
1009            replacing = _replacing;
1010            userId = _userId;
1011            replacing = _replacing;
1012            verifierUid = _verifierUid;
1013        }
1014    }
1015
1016    private interface IntentFilterVerifier<T extends IntentFilter> {
1017        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1018                                               T filter, String packageName);
1019        void startVerifications(int userId);
1020        void receiveVerificationResponse(int verificationId);
1021    }
1022
1023    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1024        private Context mContext;
1025        private ComponentName mIntentFilterVerifierComponent;
1026        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1027
1028        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1029            mContext = context;
1030            mIntentFilterVerifierComponent = verifierComponent;
1031        }
1032
1033        private String getDefaultScheme() {
1034            return IntentFilter.SCHEME_HTTPS;
1035        }
1036
1037        @Override
1038        public void startVerifications(int userId) {
1039            // Launch verifications requests
1040            int count = mCurrentIntentFilterVerifications.size();
1041            for (int n=0; n<count; n++) {
1042                int verificationId = mCurrentIntentFilterVerifications.get(n);
1043                final IntentFilterVerificationState ivs =
1044                        mIntentFilterVerificationStates.get(verificationId);
1045
1046                String packageName = ivs.getPackageName();
1047
1048                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1049                final int filterCount = filters.size();
1050                ArraySet<String> domainsSet = new ArraySet<>();
1051                for (int m=0; m<filterCount; m++) {
1052                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1053                    domainsSet.addAll(filter.getHostsList());
1054                }
1055                synchronized (mPackages) {
1056                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1057                            packageName, domainsSet) != null) {
1058                        scheduleWriteSettingsLocked();
1059                    }
1060                }
1061                sendVerificationRequest(verificationId, ivs);
1062            }
1063            mCurrentIntentFilterVerifications.clear();
1064        }
1065
1066        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1067            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1068            verificationIntent.putExtra(
1069                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1070                    verificationId);
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1073                    getDefaultScheme());
1074            verificationIntent.putExtra(
1075                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1076                    ivs.getHostsString());
1077            verificationIntent.putExtra(
1078                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1079                    ivs.getPackageName());
1080            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1081            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1082
1083            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1084            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1085                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1086                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1087
1088            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1089            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1090                    "Sending IntentFilter verification broadcast");
1091        }
1092
1093        public void receiveVerificationResponse(int verificationId) {
1094            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1095
1096            final boolean verified = ivs.isVerified();
1097
1098            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1099            final int count = filters.size();
1100            if (DEBUG_DOMAIN_VERIFICATION) {
1101                Slog.i(TAG, "Received verification response " + verificationId
1102                        + " for " + count + " filters, verified=" + verified);
1103            }
1104            for (int n=0; n<count; n++) {
1105                PackageParser.ActivityIntentInfo filter = filters.get(n);
1106                filter.setVerified(verified);
1107
1108                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1109                        + " verified with result:" + verified + " and hosts:"
1110                        + ivs.getHostsString());
1111            }
1112
1113            mIntentFilterVerificationStates.remove(verificationId);
1114
1115            final String packageName = ivs.getPackageName();
1116            IntentFilterVerificationInfo ivi = null;
1117
1118            synchronized (mPackages) {
1119                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1120            }
1121            if (ivi == null) {
1122                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1123                        + verificationId + " packageName:" + packageName);
1124                return;
1125            }
1126            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1127                    "Updating IntentFilterVerificationInfo for package " + packageName
1128                            +" verificationId:" + verificationId);
1129
1130            synchronized (mPackages) {
1131                if (verified) {
1132                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1133                } else {
1134                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1135                }
1136                scheduleWriteSettingsLocked();
1137
1138                final int userId = ivs.getUserId();
1139                if (userId != UserHandle.USER_ALL) {
1140                    final int userStatus =
1141                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1142
1143                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1144                    boolean needUpdate = false;
1145
1146                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1147                    // already been set by the User thru the Disambiguation dialog
1148                    switch (userStatus) {
1149                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1150                            if (verified) {
1151                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1152                            } else {
1153                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1154                            }
1155                            needUpdate = true;
1156                            break;
1157
1158                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1159                            if (verified) {
1160                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1161                                needUpdate = true;
1162                            }
1163                            break;
1164
1165                        default:
1166                            // Nothing to do
1167                    }
1168
1169                    if (needUpdate) {
1170                        mSettings.updateIntentFilterVerificationStatusLPw(
1171                                packageName, updatedStatus, userId);
1172                        scheduleWritePackageRestrictionsLocked(userId);
1173                    }
1174                }
1175            }
1176        }
1177
1178        @Override
1179        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1180                    ActivityIntentInfo filter, String packageName) {
1181            if (!hasValidDomains(filter)) {
1182                return false;
1183            }
1184            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1185            if (ivs == null) {
1186                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1187                        packageName);
1188            }
1189            if (DEBUG_DOMAIN_VERIFICATION) {
1190                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1191            }
1192            ivs.addFilter(filter);
1193            return true;
1194        }
1195
1196        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1197                int userId, int verificationId, String packageName) {
1198            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1199                    verifierUid, userId, packageName);
1200            ivs.setPendingState();
1201            synchronized (mPackages) {
1202                mIntentFilterVerificationStates.append(verificationId, ivs);
1203                mCurrentIntentFilterVerifications.add(verificationId);
1204            }
1205            return ivs;
1206        }
1207    }
1208
1209    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1210        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1211                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1212                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1213    }
1214
1215    // Set of pending broadcasts for aggregating enable/disable of components.
1216    static class PendingPackageBroadcasts {
1217        // for each user id, a map of <package name -> components within that package>
1218        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1219
1220        public PendingPackageBroadcasts() {
1221            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1222        }
1223
1224        public ArrayList<String> get(int userId, String packageName) {
1225            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1226            return packages.get(packageName);
1227        }
1228
1229        public void put(int userId, String packageName, ArrayList<String> components) {
1230            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231            packages.put(packageName, components);
1232        }
1233
1234        public void remove(int userId, String packageName) {
1235            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1236            if (packages != null) {
1237                packages.remove(packageName);
1238            }
1239        }
1240
1241        public void remove(int userId) {
1242            mUidMap.remove(userId);
1243        }
1244
1245        public int userIdCount() {
1246            return mUidMap.size();
1247        }
1248
1249        public int userIdAt(int n) {
1250            return mUidMap.keyAt(n);
1251        }
1252
1253        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1254            return mUidMap.get(userId);
1255        }
1256
1257        public int size() {
1258            // total number of pending broadcast entries across all userIds
1259            int num = 0;
1260            for (int i = 0; i< mUidMap.size(); i++) {
1261                num += mUidMap.valueAt(i).size();
1262            }
1263            return num;
1264        }
1265
1266        public void clear() {
1267            mUidMap.clear();
1268        }
1269
1270        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1271            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1272            if (map == null) {
1273                map = new ArrayMap<String, ArrayList<String>>();
1274                mUidMap.put(userId, map);
1275            }
1276            return map;
1277        }
1278    }
1279    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1280
1281    // Service Connection to remote media container service to copy
1282    // package uri's from external media onto secure containers
1283    // or internal storage.
1284    private IMediaContainerService mContainerService = null;
1285
1286    static final int SEND_PENDING_BROADCAST = 1;
1287    static final int MCS_BOUND = 3;
1288    static final int END_COPY = 4;
1289    static final int INIT_COPY = 5;
1290    static final int MCS_UNBIND = 6;
1291    static final int START_CLEANING_PACKAGE = 7;
1292    static final int FIND_INSTALL_LOC = 8;
1293    static final int POST_INSTALL = 9;
1294    static final int MCS_RECONNECT = 10;
1295    static final int MCS_GIVE_UP = 11;
1296    static final int WRITE_SETTINGS = 13;
1297    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1298    static final int PACKAGE_VERIFIED = 15;
1299    static final int CHECK_PENDING_VERIFICATION = 16;
1300    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1301    static final int INTENT_FILTER_VERIFIED = 18;
1302    static final int WRITE_PACKAGE_LIST = 19;
1303    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1304
1305    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1306
1307    // Delay time in millisecs
1308    static final int BROADCAST_DELAY = 10 * 1000;
1309
1310    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1311            2 * 60 * 60 * 1000L; /* two hours */
1312
1313    static UserManagerService sUserManager;
1314
1315    // Stores a list of users whose package restrictions file needs to be updated
1316    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1317
1318    final private DefaultContainerConnection mDefContainerConn =
1319            new DefaultContainerConnection();
1320    class DefaultContainerConnection implements ServiceConnection {
1321        public void onServiceConnected(ComponentName name, IBinder service) {
1322            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1323            final IMediaContainerService imcs = IMediaContainerService.Stub
1324                    .asInterface(Binder.allowBlocking(service));
1325            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1326        }
1327
1328        public void onServiceDisconnected(ComponentName name) {
1329            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1330        }
1331    }
1332
1333    // Recordkeeping of restore-after-install operations that are currently in flight
1334    // between the Package Manager and the Backup Manager
1335    static class PostInstallData {
1336        public InstallArgs args;
1337        public PackageInstalledInfo res;
1338
1339        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1340            args = _a;
1341            res = _r;
1342        }
1343    }
1344
1345    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1346    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1347
1348    // XML tags for backup/restore of various bits of state
1349    private static final String TAG_PREFERRED_BACKUP = "pa";
1350    private static final String TAG_DEFAULT_APPS = "da";
1351    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1352
1353    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1354    private static final String TAG_ALL_GRANTS = "rt-grants";
1355    private static final String TAG_GRANT = "grant";
1356    private static final String ATTR_PACKAGE_NAME = "pkg";
1357
1358    private static final String TAG_PERMISSION = "perm";
1359    private static final String ATTR_PERMISSION_NAME = "name";
1360    private static final String ATTR_IS_GRANTED = "g";
1361    private static final String ATTR_USER_SET = "set";
1362    private static final String ATTR_USER_FIXED = "fixed";
1363    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1364
1365    // System/policy permission grants are not backed up
1366    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1367            FLAG_PERMISSION_POLICY_FIXED
1368            | FLAG_PERMISSION_SYSTEM_FIXED
1369            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1370
1371    // And we back up these user-adjusted states
1372    private static final int USER_RUNTIME_GRANT_MASK =
1373            FLAG_PERMISSION_USER_SET
1374            | FLAG_PERMISSION_USER_FIXED
1375            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1376
1377    final @Nullable String mRequiredVerifierPackage;
1378    final @NonNull String mRequiredInstallerPackage;
1379    final @NonNull String mRequiredUninstallerPackage;
1380    final @Nullable String mSetupWizardPackage;
1381    final @Nullable String mStorageManagerPackage;
1382    final @NonNull String mServicesSystemSharedLibraryPackageName;
1383    final @NonNull String mSharedSystemSharedLibraryPackageName;
1384
1385    private final PackageUsage mPackageUsage = new PackageUsage();
1386    private final CompilerStats mCompilerStats = new CompilerStats();
1387
1388    class PackageHandler extends Handler {
1389        private boolean mBound = false;
1390        final ArrayList<HandlerParams> mPendingInstalls =
1391            new ArrayList<HandlerParams>();
1392
1393        private boolean connectToService() {
1394            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1395                    " DefaultContainerService");
1396            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1397            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1398            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1399                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1400                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1401                mBound = true;
1402                return true;
1403            }
1404            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1405            return false;
1406        }
1407
1408        private void disconnectService() {
1409            mContainerService = null;
1410            mBound = false;
1411            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1412            mContext.unbindService(mDefContainerConn);
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414        }
1415
1416        PackageHandler(Looper looper) {
1417            super(looper);
1418        }
1419
1420        public void handleMessage(Message msg) {
1421            try {
1422                doHandleMessage(msg);
1423            } finally {
1424                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425            }
1426        }
1427
1428        void doHandleMessage(Message msg) {
1429            switch (msg.what) {
1430                case INIT_COPY: {
1431                    HandlerParams params = (HandlerParams) msg.obj;
1432                    int idx = mPendingInstalls.size();
1433                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1434                    // If a bind was already initiated we dont really
1435                    // need to do anything. The pending install
1436                    // will be processed later on.
1437                    if (!mBound) {
1438                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1439                                System.identityHashCode(mHandler));
1440                        // If this is the only one pending we might
1441                        // have to bind to the service again.
1442                        if (!connectToService()) {
1443                            Slog.e(TAG, "Failed to bind to media container service");
1444                            params.serviceError();
1445                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1446                                    System.identityHashCode(mHandler));
1447                            if (params.traceMethod != null) {
1448                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1449                                        params.traceCookie);
1450                            }
1451                            return;
1452                        } else {
1453                            // Once we bind to the service, the first
1454                            // pending request will be processed.
1455                            mPendingInstalls.add(idx, params);
1456                        }
1457                    } else {
1458                        mPendingInstalls.add(idx, params);
1459                        // Already bound to the service. Just make
1460                        // sure we trigger off processing the first request.
1461                        if (idx == 0) {
1462                            mHandler.sendEmptyMessage(MCS_BOUND);
1463                        }
1464                    }
1465                    break;
1466                }
1467                case MCS_BOUND: {
1468                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1469                    if (msg.obj != null) {
1470                        mContainerService = (IMediaContainerService) msg.obj;
1471                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1472                                System.identityHashCode(mHandler));
1473                    }
1474                    if (mContainerService == null) {
1475                        if (!mBound) {
1476                            // Something seriously wrong since we are not bound and we are not
1477                            // waiting for connection. Bail out.
1478                            Slog.e(TAG, "Cannot bind to media container service");
1479                            for (HandlerParams params : mPendingInstalls) {
1480                                // Indicate service bind error
1481                                params.serviceError();
1482                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1483                                        System.identityHashCode(params));
1484                                if (params.traceMethod != null) {
1485                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1486                                            params.traceMethod, params.traceCookie);
1487                                }
1488                                return;
1489                            }
1490                            mPendingInstalls.clear();
1491                        } else {
1492                            Slog.w(TAG, "Waiting to connect to media container service");
1493                        }
1494                    } else if (mPendingInstalls.size() > 0) {
1495                        HandlerParams params = mPendingInstalls.get(0);
1496                        if (params != null) {
1497                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1498                                    System.identityHashCode(params));
1499                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1500                            if (params.startCopy()) {
1501                                // We are done...  look for more work or to
1502                                // go idle.
1503                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1504                                        "Checking for more work or unbind...");
1505                                // Delete pending install
1506                                if (mPendingInstalls.size() > 0) {
1507                                    mPendingInstalls.remove(0);
1508                                }
1509                                if (mPendingInstalls.size() == 0) {
1510                                    if (mBound) {
1511                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                                "Posting delayed MCS_UNBIND");
1513                                        removeMessages(MCS_UNBIND);
1514                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1515                                        // Unbind after a little delay, to avoid
1516                                        // continual thrashing.
1517                                        sendMessageDelayed(ubmsg, 10000);
1518                                    }
1519                                } else {
1520                                    // There are more pending requests in queue.
1521                                    // Just post MCS_BOUND message to trigger processing
1522                                    // of next pending install.
1523                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1524                                            "Posting MCS_BOUND for next work");
1525                                    mHandler.sendEmptyMessage(MCS_BOUND);
1526                                }
1527                            }
1528                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1529                        }
1530                    } else {
1531                        // Should never happen ideally.
1532                        Slog.w(TAG, "Empty queue");
1533                    }
1534                    break;
1535                }
1536                case MCS_RECONNECT: {
1537                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1538                    if (mPendingInstalls.size() > 0) {
1539                        if (mBound) {
1540                            disconnectService();
1541                        }
1542                        if (!connectToService()) {
1543                            Slog.e(TAG, "Failed to bind to media container service");
1544                            for (HandlerParams params : mPendingInstalls) {
1545                                // Indicate service bind error
1546                                params.serviceError();
1547                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1548                                        System.identityHashCode(params));
1549                            }
1550                            mPendingInstalls.clear();
1551                        }
1552                    }
1553                    break;
1554                }
1555                case MCS_UNBIND: {
1556                    // If there is no actual work left, then time to unbind.
1557                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1558
1559                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1560                        if (mBound) {
1561                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1562
1563                            disconnectService();
1564                        }
1565                    } else if (mPendingInstalls.size() > 0) {
1566                        // There are more pending requests in queue.
1567                        // Just post MCS_BOUND message to trigger processing
1568                        // of next pending install.
1569                        mHandler.sendEmptyMessage(MCS_BOUND);
1570                    }
1571
1572                    break;
1573                }
1574                case MCS_GIVE_UP: {
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1576                    HandlerParams params = mPendingInstalls.remove(0);
1577                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1578                            System.identityHashCode(params));
1579                    break;
1580                }
1581                case SEND_PENDING_BROADCAST: {
1582                    String packages[];
1583                    ArrayList<String> components[];
1584                    int size = 0;
1585                    int uids[];
1586                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1587                    synchronized (mPackages) {
1588                        if (mPendingBroadcasts == null) {
1589                            return;
1590                        }
1591                        size = mPendingBroadcasts.size();
1592                        if (size <= 0) {
1593                            // Nothing to be done. Just return
1594                            return;
1595                        }
1596                        packages = new String[size];
1597                        components = new ArrayList[size];
1598                        uids = new int[size];
1599                        int i = 0;  // filling out the above arrays
1600
1601                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1602                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1603                            Iterator<Map.Entry<String, ArrayList<String>>> it
1604                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1605                                            .entrySet().iterator();
1606                            while (it.hasNext() && i < size) {
1607                                Map.Entry<String, ArrayList<String>> ent = it.next();
1608                                packages[i] = ent.getKey();
1609                                components[i] = ent.getValue();
1610                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1611                                uids[i] = (ps != null)
1612                                        ? UserHandle.getUid(packageUserId, ps.appId)
1613                                        : -1;
1614                                i++;
1615                            }
1616                        }
1617                        size = i;
1618                        mPendingBroadcasts.clear();
1619                    }
1620                    // Send broadcasts
1621                    for (int i = 0; i < size; i++) {
1622                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1623                    }
1624                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1625                    break;
1626                }
1627                case START_CLEANING_PACKAGE: {
1628                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1629                    final String packageName = (String)msg.obj;
1630                    final int userId = msg.arg1;
1631                    final boolean andCode = msg.arg2 != 0;
1632                    synchronized (mPackages) {
1633                        if (userId == UserHandle.USER_ALL) {
1634                            int[] users = sUserManager.getUserIds();
1635                            for (int user : users) {
1636                                mSettings.addPackageToCleanLPw(
1637                                        new PackageCleanItem(user, packageName, andCode));
1638                            }
1639                        } else {
1640                            mSettings.addPackageToCleanLPw(
1641                                    new PackageCleanItem(userId, packageName, andCode));
1642                        }
1643                    }
1644                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1645                    startCleaningPackages();
1646                } break;
1647                case POST_INSTALL: {
1648                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1649
1650                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1651                    final boolean didRestore = (msg.arg2 != 0);
1652                    mRunningInstalls.delete(msg.arg1);
1653
1654                    if (data != null) {
1655                        InstallArgs args = data.args;
1656                        PackageInstalledInfo parentRes = data.res;
1657
1658                        final boolean grantPermissions = (args.installFlags
1659                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1660                        final boolean killApp = (args.installFlags
1661                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1662                        final boolean virtualPreload = ((args.installFlags
1663                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1664                        final String[] grantedPermissions = args.installGrantPermissions;
1665
1666                        // Handle the parent package
1667                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1668                                virtualPreload, grantedPermissions, didRestore,
1669                                args.installerPackageName, args.observer);
1670
1671                        // Handle the child packages
1672                        final int childCount = (parentRes.addedChildPackages != null)
1673                                ? parentRes.addedChildPackages.size() : 0;
1674                        for (int i = 0; i < childCount; i++) {
1675                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1676                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1677                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1678                                    args.installerPackageName, args.observer);
1679                        }
1680
1681                        // Log tracing if needed
1682                        if (args.traceMethod != null) {
1683                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1684                                    args.traceCookie);
1685                        }
1686                    } else {
1687                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1688                    }
1689
1690                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1691                } break;
1692                case WRITE_SETTINGS: {
1693                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1694                    synchronized (mPackages) {
1695                        removeMessages(WRITE_SETTINGS);
1696                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1697                        mSettings.writeLPr();
1698                        mDirtyUsers.clear();
1699                    }
1700                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1701                } break;
1702                case WRITE_PACKAGE_RESTRICTIONS: {
1703                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1704                    synchronized (mPackages) {
1705                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1706                        for (int userId : mDirtyUsers) {
1707                            mSettings.writePackageRestrictionsLPr(userId);
1708                        }
1709                        mDirtyUsers.clear();
1710                    }
1711                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1712                } break;
1713                case WRITE_PACKAGE_LIST: {
1714                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1715                    synchronized (mPackages) {
1716                        removeMessages(WRITE_PACKAGE_LIST);
1717                        mSettings.writePackageListLPr(msg.arg1);
1718                    }
1719                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1720                } break;
1721                case CHECK_PENDING_VERIFICATION: {
1722                    final int verificationId = msg.arg1;
1723                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1724
1725                    if ((state != null) && !state.timeoutExtended()) {
1726                        final InstallArgs args = state.getInstallArgs();
1727                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1728
1729                        Slog.i(TAG, "Verification timed out for " + originUri);
1730                        mPendingVerification.remove(verificationId);
1731
1732                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1733
1734                        final UserHandle user = args.getUser();
1735                        if (getDefaultVerificationResponse(user)
1736                                == PackageManager.VERIFICATION_ALLOW) {
1737                            Slog.i(TAG, "Continuing with installation of " + originUri);
1738                            state.setVerifierResponse(Binder.getCallingUid(),
1739                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1740                            broadcastPackageVerified(verificationId, originUri,
1741                                    PackageManager.VERIFICATION_ALLOW, user);
1742                            try {
1743                                ret = args.copyApk(mContainerService, true);
1744                            } catch (RemoteException e) {
1745                                Slog.e(TAG, "Could not contact the ContainerService");
1746                            }
1747                        } else {
1748                            broadcastPackageVerified(verificationId, originUri,
1749                                    PackageManager.VERIFICATION_REJECT, user);
1750                        }
1751
1752                        Trace.asyncTraceEnd(
1753                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1754
1755                        processPendingInstall(args, ret);
1756                        mHandler.sendEmptyMessage(MCS_UNBIND);
1757                    }
1758                    break;
1759                }
1760                case PACKAGE_VERIFIED: {
1761                    final int verificationId = msg.arg1;
1762
1763                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1764                    if (state == null) {
1765                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1766                        break;
1767                    }
1768
1769                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1770
1771                    state.setVerifierResponse(response.callerUid, response.code);
1772
1773                    if (state.isVerificationComplete()) {
1774                        mPendingVerification.remove(verificationId);
1775
1776                        final InstallArgs args = state.getInstallArgs();
1777                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1778
1779                        int ret;
1780                        if (state.isInstallAllowed()) {
1781                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1782                            broadcastPackageVerified(verificationId, originUri,
1783                                    response.code, state.getInstallArgs().getUser());
1784                            try {
1785                                ret = args.copyApk(mContainerService, true);
1786                            } catch (RemoteException e) {
1787                                Slog.e(TAG, "Could not contact the ContainerService");
1788                            }
1789                        } else {
1790                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1791                        }
1792
1793                        Trace.asyncTraceEnd(
1794                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1795
1796                        processPendingInstall(args, ret);
1797                        mHandler.sendEmptyMessage(MCS_UNBIND);
1798                    }
1799
1800                    break;
1801                }
1802                case START_INTENT_FILTER_VERIFICATIONS: {
1803                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1804                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1805                            params.replacing, params.pkg);
1806                    break;
1807                }
1808                case INTENT_FILTER_VERIFIED: {
1809                    final int verificationId = msg.arg1;
1810
1811                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1812                            verificationId);
1813                    if (state == null) {
1814                        Slog.w(TAG, "Invalid IntentFilter verification token "
1815                                + verificationId + " received");
1816                        break;
1817                    }
1818
1819                    final int userId = state.getUserId();
1820
1821                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1822                            "Processing IntentFilter verification with token:"
1823                            + verificationId + " and userId:" + userId);
1824
1825                    final IntentFilterVerificationResponse response =
1826                            (IntentFilterVerificationResponse) msg.obj;
1827
1828                    state.setVerifierResponse(response.callerUid, response.code);
1829
1830                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1831                            "IntentFilter verification with token:" + verificationId
1832                            + " and userId:" + userId
1833                            + " is settings verifier response with response code:"
1834                            + response.code);
1835
1836                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1837                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1838                                + response.getFailedDomainsString());
1839                    }
1840
1841                    if (state.isVerificationComplete()) {
1842                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1843                    } else {
1844                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1845                                "IntentFilter verification with token:" + verificationId
1846                                + " was not said to be complete");
1847                    }
1848
1849                    break;
1850                }
1851                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1852                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1853                            mInstantAppResolverConnection,
1854                            (InstantAppRequest) msg.obj,
1855                            mInstantAppInstallerActivity,
1856                            mHandler);
1857                }
1858            }
1859        }
1860    }
1861
1862    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1863        @Override
1864        public void onGidsChanged(int appId, int userId) {
1865            mHandler.post(new Runnable() {
1866                @Override
1867                public void run() {
1868                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1869                }
1870            });
1871        }
1872        @Override
1873        public void onPermissionGranted(int uid, int userId) {
1874            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1875
1876            // Not critical; if this is lost, the application has to request again.
1877            synchronized (mPackages) {
1878                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1879            }
1880        }
1881        @Override
1882        public void onInstallPermissionGranted() {
1883            synchronized (mPackages) {
1884                scheduleWriteSettingsLocked();
1885            }
1886        }
1887        @Override
1888        public void onPermissionRevoked(int uid, int userId) {
1889            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1890
1891            synchronized (mPackages) {
1892                // Critical; after this call the application should never have the permission
1893                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1894            }
1895
1896            final int appId = UserHandle.getAppId(uid);
1897            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1898        }
1899        @Override
1900        public void onInstallPermissionRevoked() {
1901            synchronized (mPackages) {
1902                scheduleWriteSettingsLocked();
1903            }
1904        }
1905        @Override
1906        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1907            synchronized (mPackages) {
1908                for (int userId : updatedUserIds) {
1909                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1910                }
1911            }
1912        }
1913        @Override
1914        public void onInstallPermissionUpdated() {
1915            synchronized (mPackages) {
1916                scheduleWriteSettingsLocked();
1917            }
1918        }
1919        @Override
1920        public void onPermissionRemoved() {
1921            synchronized (mPackages) {
1922                mSettings.writeLPr();
1923            }
1924        }
1925    };
1926
1927    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1928            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1929            boolean launchedForRestore, String installerPackage,
1930            IPackageInstallObserver2 installObserver) {
1931        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1932            // Send the removed broadcasts
1933            if (res.removedInfo != null) {
1934                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1935            }
1936
1937            // Now that we successfully installed the package, grant runtime
1938            // permissions if requested before broadcasting the install. Also
1939            // for legacy apps in permission review mode we clear the permission
1940            // review flag which is used to emulate runtime permissions for
1941            // legacy apps.
1942            if (grantPermissions) {
1943                final int callingUid = Binder.getCallingUid();
1944                mPermissionManager.grantRequestedRuntimePermissions(
1945                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1946                        mPermissionCallback);
1947            }
1948
1949            final boolean update = res.removedInfo != null
1950                    && res.removedInfo.removedPackage != null;
1951            final String installerPackageName =
1952                    res.installerPackageName != null
1953                            ? res.installerPackageName
1954                            : res.removedInfo != null
1955                                    ? res.removedInfo.installerPackageName
1956                                    : null;
1957
1958            // If this is the first time we have child packages for a disabled privileged
1959            // app that had no children, we grant requested runtime permissions to the new
1960            // children if the parent on the system image had them already granted.
1961            if (res.pkg.parentPackage != null) {
1962                final int callingUid = Binder.getCallingUid();
1963                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1964                        res.pkg, callingUid, mPermissionCallback);
1965            }
1966
1967            synchronized (mPackages) {
1968                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1969            }
1970
1971            final String packageName = res.pkg.applicationInfo.packageName;
1972
1973            // Determine the set of users who are adding this package for
1974            // the first time vs. those who are seeing an update.
1975            int[] firstUsers = EMPTY_INT_ARRAY;
1976            int[] updateUsers = EMPTY_INT_ARRAY;
1977            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1978            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1979            for (int newUser : res.newUsers) {
1980                if (ps.getInstantApp(newUser)) {
1981                    continue;
1982                }
1983                if (allNewUsers) {
1984                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1985                    continue;
1986                }
1987                boolean isNew = true;
1988                for (int origUser : res.origUsers) {
1989                    if (origUser == newUser) {
1990                        isNew = false;
1991                        break;
1992                    }
1993                }
1994                if (isNew) {
1995                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1996                } else {
1997                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1998                }
1999            }
2000
2001            // Send installed broadcasts if the package is not a static shared lib.
2002            if (res.pkg.staticSharedLibName == null) {
2003                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2004
2005                // Send added for users that see the package for the first time
2006                // sendPackageAddedForNewUsers also deals with system apps
2007                int appId = UserHandle.getAppId(res.uid);
2008                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2009                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2010                        virtualPreload /*startReceiver*/, appId, firstUsers);
2011
2012                // Send added for users that don't see the package for the first time
2013                Bundle extras = new Bundle(1);
2014                extras.putInt(Intent.EXTRA_UID, res.uid);
2015                if (update) {
2016                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2017                }
2018                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2019                        extras, 0 /*flags*/,
2020                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2021                if (installerPackageName != null) {
2022                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2023                            extras, 0 /*flags*/,
2024                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2025                }
2026
2027                // Send replaced for users that don't see the package for the first time
2028                if (update) {
2029                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2030                            packageName, extras, 0 /*flags*/,
2031                            null /*targetPackage*/, null /*finishedReceiver*/,
2032                            updateUsers);
2033                    if (installerPackageName != null) {
2034                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2035                                extras, 0 /*flags*/,
2036                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2037                    }
2038                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2039                            null /*package*/, null /*extras*/, 0 /*flags*/,
2040                            packageName /*targetPackage*/,
2041                            null /*finishedReceiver*/, updateUsers);
2042                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2043                    // First-install and we did a restore, so we're responsible for the
2044                    // first-launch broadcast.
2045                    if (DEBUG_BACKUP) {
2046                        Slog.i(TAG, "Post-restore of " + packageName
2047                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2048                    }
2049                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2050                }
2051
2052                // Send broadcast package appeared if forward locked/external for all users
2053                // treat asec-hosted packages like removable media on upgrade
2054                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2055                    if (DEBUG_INSTALL) {
2056                        Slog.i(TAG, "upgrading pkg " + res.pkg
2057                                + " is ASEC-hosted -> AVAILABLE");
2058                    }
2059                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2060                    ArrayList<String> pkgList = new ArrayList<>(1);
2061                    pkgList.add(packageName);
2062                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2063                }
2064            }
2065
2066            // Work that needs to happen on first install within each user
2067            if (firstUsers != null && firstUsers.length > 0) {
2068                synchronized (mPackages) {
2069                    for (int userId : firstUsers) {
2070                        // If this app is a browser and it's newly-installed for some
2071                        // users, clear any default-browser state in those users. The
2072                        // app's nature doesn't depend on the user, so we can just check
2073                        // its browser nature in any user and generalize.
2074                        if (packageIsBrowser(packageName, userId)) {
2075                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2076                        }
2077
2078                        // We may also need to apply pending (restored) runtime
2079                        // permission grants within these users.
2080                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2081                    }
2082                }
2083            }
2084
2085            // Log current value of "unknown sources" setting
2086            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2087                    getUnknownSourcesSettings());
2088
2089            // Remove the replaced package's older resources safely now
2090            // We delete after a gc for applications  on sdcard.
2091            if (res.removedInfo != null && res.removedInfo.args != null) {
2092                Runtime.getRuntime().gc();
2093                synchronized (mInstallLock) {
2094                    res.removedInfo.args.doPostDeleteLI(true);
2095                }
2096            } else {
2097                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2098                // and not block here.
2099                VMRuntime.getRuntime().requestConcurrentGC();
2100            }
2101
2102            // Notify DexManager that the package was installed for new users.
2103            // The updated users should already be indexed and the package code paths
2104            // should not change.
2105            // Don't notify the manager for ephemeral apps as they are not expected to
2106            // survive long enough to benefit of background optimizations.
2107            for (int userId : firstUsers) {
2108                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2109                // There's a race currently where some install events may interleave with an uninstall.
2110                // This can lead to package info being null (b/36642664).
2111                if (info != null) {
2112                    mDexManager.notifyPackageInstalled(info, userId);
2113                }
2114            }
2115        }
2116
2117        // If someone is watching installs - notify them
2118        if (installObserver != null) {
2119            try {
2120                Bundle extras = extrasForInstallResult(res);
2121                installObserver.onPackageInstalled(res.name, res.returnCode,
2122                        res.returnMsg, extras);
2123            } catch (RemoteException e) {
2124                Slog.i(TAG, "Observer no longer exists.");
2125            }
2126        }
2127    }
2128
2129    private StorageEventListener mStorageListener = new StorageEventListener() {
2130        @Override
2131        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2132            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2133                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2134                    final String volumeUuid = vol.getFsUuid();
2135
2136                    // Clean up any users or apps that were removed or recreated
2137                    // while this volume was missing
2138                    sUserManager.reconcileUsers(volumeUuid);
2139                    reconcileApps(volumeUuid);
2140
2141                    // Clean up any install sessions that expired or were
2142                    // cancelled while this volume was missing
2143                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2144
2145                    loadPrivatePackages(vol);
2146
2147                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2148                    unloadPrivatePackages(vol);
2149                }
2150            }
2151        }
2152
2153        @Override
2154        public void onVolumeForgotten(String fsUuid) {
2155            if (TextUtils.isEmpty(fsUuid)) {
2156                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2157                return;
2158            }
2159
2160            // Remove any apps installed on the forgotten volume
2161            synchronized (mPackages) {
2162                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2163                for (PackageSetting ps : packages) {
2164                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2165                    deletePackageVersioned(new VersionedPackage(ps.name,
2166                            PackageManager.VERSION_CODE_HIGHEST),
2167                            new LegacyPackageDeleteObserver(null).getBinder(),
2168                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2169                    // Try very hard to release any references to this package
2170                    // so we don't risk the system server being killed due to
2171                    // open FDs
2172                    AttributeCache.instance().removePackage(ps.name);
2173                }
2174
2175                mSettings.onVolumeForgotten(fsUuid);
2176                mSettings.writeLPr();
2177            }
2178        }
2179    };
2180
2181    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2182        Bundle extras = null;
2183        switch (res.returnCode) {
2184            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2185                extras = new Bundle();
2186                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2187                        res.origPermission);
2188                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2189                        res.origPackage);
2190                break;
2191            }
2192            case PackageManager.INSTALL_SUCCEEDED: {
2193                extras = new Bundle();
2194                extras.putBoolean(Intent.EXTRA_REPLACING,
2195                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2196                break;
2197            }
2198        }
2199        return extras;
2200    }
2201
2202    void scheduleWriteSettingsLocked() {
2203        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2204            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2205        }
2206    }
2207
2208    void scheduleWritePackageListLocked(int userId) {
2209        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2210            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2211            msg.arg1 = userId;
2212            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2213        }
2214    }
2215
2216    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2217        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2218        scheduleWritePackageRestrictionsLocked(userId);
2219    }
2220
2221    void scheduleWritePackageRestrictionsLocked(int userId) {
2222        final int[] userIds = (userId == UserHandle.USER_ALL)
2223                ? sUserManager.getUserIds() : new int[]{userId};
2224        for (int nextUserId : userIds) {
2225            if (!sUserManager.exists(nextUserId)) return;
2226            mDirtyUsers.add(nextUserId);
2227            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2228                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2229            }
2230        }
2231    }
2232
2233    public static PackageManagerService main(Context context, Installer installer,
2234            boolean factoryTest, boolean onlyCore) {
2235        // Self-check for initial settings.
2236        PackageManagerServiceCompilerMapping.checkProperties();
2237
2238        PackageManagerService m = new PackageManagerService(context, installer,
2239                factoryTest, onlyCore);
2240        m.enableSystemUserPackages();
2241        ServiceManager.addService("package", m);
2242        final PackageManagerNative pmn = m.new PackageManagerNative();
2243        ServiceManager.addService("package_native", pmn);
2244        return m;
2245    }
2246
2247    private void enableSystemUserPackages() {
2248        if (!UserManager.isSplitSystemUser()) {
2249            return;
2250        }
2251        // For system user, enable apps based on the following conditions:
2252        // - app is whitelisted or belong to one of these groups:
2253        //   -- system app which has no launcher icons
2254        //   -- system app which has INTERACT_ACROSS_USERS permission
2255        //   -- system IME app
2256        // - app is not in the blacklist
2257        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2258        Set<String> enableApps = new ArraySet<>();
2259        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2260                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2261                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2262        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2263        enableApps.addAll(wlApps);
2264        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2265                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2266        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2267        enableApps.removeAll(blApps);
2268        Log.i(TAG, "Applications installed for system user: " + enableApps);
2269        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2270                UserHandle.SYSTEM);
2271        final int allAppsSize = allAps.size();
2272        synchronized (mPackages) {
2273            for (int i = 0; i < allAppsSize; i++) {
2274                String pName = allAps.get(i);
2275                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2276                // Should not happen, but we shouldn't be failing if it does
2277                if (pkgSetting == null) {
2278                    continue;
2279                }
2280                boolean install = enableApps.contains(pName);
2281                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2282                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2283                            + " for system user");
2284                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2285                }
2286            }
2287            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2288        }
2289    }
2290
2291    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2292        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2293                Context.DISPLAY_SERVICE);
2294        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2295    }
2296
2297    /**
2298     * Requests that files preopted on a secondary system partition be copied to the data partition
2299     * if possible.  Note that the actual copying of the files is accomplished by init for security
2300     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2301     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2302     */
2303    private static void requestCopyPreoptedFiles() {
2304        final int WAIT_TIME_MS = 100;
2305        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2306        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2307            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2308            // We will wait for up to 100 seconds.
2309            final long timeStart = SystemClock.uptimeMillis();
2310            final long timeEnd = timeStart + 100 * 1000;
2311            long timeNow = timeStart;
2312            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2313                try {
2314                    Thread.sleep(WAIT_TIME_MS);
2315                } catch (InterruptedException e) {
2316                    // Do nothing
2317                }
2318                timeNow = SystemClock.uptimeMillis();
2319                if (timeNow > timeEnd) {
2320                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2321                    Slog.wtf(TAG, "cppreopt did not finish!");
2322                    break;
2323                }
2324            }
2325
2326            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2327        }
2328    }
2329
2330    public PackageManagerService(Context context, Installer installer,
2331            boolean factoryTest, boolean onlyCore) {
2332        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2333        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2334        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2335                SystemClock.uptimeMillis());
2336
2337        if (mSdkVersion <= 0) {
2338            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2339        }
2340
2341        mContext = context;
2342
2343        mFactoryTest = factoryTest;
2344        mOnlyCore = onlyCore;
2345        mMetrics = new DisplayMetrics();
2346        mInstaller = installer;
2347
2348        // Create sub-components that provide services / data. Order here is important.
2349        synchronized (mInstallLock) {
2350        synchronized (mPackages) {
2351            // Expose private service for system components to use.
2352            LocalServices.addService(
2353                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2354            sUserManager = new UserManagerService(context, this,
2355                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2356            mPermissionManager = PermissionManagerService.create(context,
2357                    new DefaultPermissionGrantedCallback() {
2358                        @Override
2359                        public void onDefaultRuntimePermissionsGranted(int userId) {
2360                            synchronized(mPackages) {
2361                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2362                            }
2363                        }
2364                    }, mPackages /*externalLock*/);
2365            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2366            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2367        }
2368        }
2369        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2370                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2371        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2372                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2373        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2374                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2375        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2376                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2377        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2378                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2379        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2380                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2381
2382        String separateProcesses = SystemProperties.get("debug.separate_processes");
2383        if (separateProcesses != null && separateProcesses.length() > 0) {
2384            if ("*".equals(separateProcesses)) {
2385                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2386                mSeparateProcesses = null;
2387                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2388            } else {
2389                mDefParseFlags = 0;
2390                mSeparateProcesses = separateProcesses.split(",");
2391                Slog.w(TAG, "Running with debug.separate_processes: "
2392                        + separateProcesses);
2393            }
2394        } else {
2395            mDefParseFlags = 0;
2396            mSeparateProcesses = null;
2397        }
2398
2399        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2400                "*dexopt*");
2401        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2402        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2403
2404        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2405                FgThread.get().getLooper());
2406
2407        getDefaultDisplayMetrics(context, mMetrics);
2408
2409        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2410        SystemConfig systemConfig = SystemConfig.getInstance();
2411        mAvailableFeatures = systemConfig.getAvailableFeatures();
2412        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2413
2414        mProtectedPackages = new ProtectedPackages(mContext);
2415
2416        synchronized (mInstallLock) {
2417        // writer
2418        synchronized (mPackages) {
2419            mHandlerThread = new ServiceThread(TAG,
2420                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2421            mHandlerThread.start();
2422            mHandler = new PackageHandler(mHandlerThread.getLooper());
2423            mProcessLoggingHandler = new ProcessLoggingHandler();
2424            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2425            mInstantAppRegistry = new InstantAppRegistry(this);
2426
2427            File dataDir = Environment.getDataDirectory();
2428            mAppInstallDir = new File(dataDir, "app");
2429            mAppLib32InstallDir = new File(dataDir, "app-lib");
2430            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2431
2432            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2433            final int builtInLibCount = libConfig.size();
2434            for (int i = 0; i < builtInLibCount; i++) {
2435                String name = libConfig.keyAt(i);
2436                String path = libConfig.valueAt(i);
2437                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2438                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2439            }
2440
2441            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2442
2443            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2444            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2445            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2446
2447            // Clean up orphaned packages for which the code path doesn't exist
2448            // and they are an update to a system app - caused by bug/32321269
2449            final int packageSettingCount = mSettings.mPackages.size();
2450            for (int i = packageSettingCount - 1; i >= 0; i--) {
2451                PackageSetting ps = mSettings.mPackages.valueAt(i);
2452                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2453                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2454                    mSettings.mPackages.removeAt(i);
2455                    mSettings.enableSystemPackageLPw(ps.name);
2456                }
2457            }
2458
2459            if (mFirstBoot) {
2460                requestCopyPreoptedFiles();
2461            }
2462
2463            String customResolverActivity = Resources.getSystem().getString(
2464                    R.string.config_customResolverActivity);
2465            if (TextUtils.isEmpty(customResolverActivity)) {
2466                customResolverActivity = null;
2467            } else {
2468                mCustomResolverComponentName = ComponentName.unflattenFromString(
2469                        customResolverActivity);
2470            }
2471
2472            long startTime = SystemClock.uptimeMillis();
2473
2474            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2475                    startTime);
2476
2477            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2478            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2479
2480            if (bootClassPath == null) {
2481                Slog.w(TAG, "No BOOTCLASSPATH found!");
2482            }
2483
2484            if (systemServerClassPath == null) {
2485                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2486            }
2487
2488            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2489
2490            final VersionInfo ver = mSettings.getInternalVersion();
2491            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2492            if (mIsUpgrade) {
2493                logCriticalInfo(Log.INFO,
2494                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2495            }
2496
2497            // when upgrading from pre-M, promote system app permissions from install to runtime
2498            mPromoteSystemApps =
2499                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2500
2501            // When upgrading from pre-N, we need to handle package extraction like first boot,
2502            // as there is no profiling data available.
2503            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2504
2505            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2506
2507            // save off the names of pre-existing system packages prior to scanning; we don't
2508            // want to automatically grant runtime permissions for new system apps
2509            if (mPromoteSystemApps) {
2510                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2511                while (pkgSettingIter.hasNext()) {
2512                    PackageSetting ps = pkgSettingIter.next();
2513                    if (isSystemApp(ps)) {
2514                        mExistingSystemPackages.add(ps.name);
2515                    }
2516                }
2517            }
2518
2519            mCacheDir = preparePackageParserCache(mIsUpgrade);
2520
2521            // Set flag to monitor and not change apk file paths when
2522            // scanning install directories.
2523            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2524
2525            if (mIsUpgrade || mFirstBoot) {
2526                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2527            }
2528
2529            // Collect vendor overlay packages. (Do this before scanning any apps.)
2530            // For security and version matching reason, only consider
2531            // overlay packages if they reside in the right directory.
2532            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2533                    mDefParseFlags
2534                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2535                    scanFlags
2536                    | SCAN_AS_SYSTEM
2537                    | SCAN_TRUSTED_OVERLAY,
2538                    0);
2539
2540            mParallelPackageParserCallback.findStaticOverlayPackages();
2541
2542            // Find base frameworks (resource packages without code).
2543            scanDirTracedLI(frameworkDir,
2544                    mDefParseFlags
2545                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2546                    scanFlags
2547                    | SCAN_NO_DEX
2548                    | SCAN_AS_SYSTEM
2549                    | SCAN_AS_PRIVILEGED,
2550                    0);
2551
2552            // Collected privileged system packages.
2553            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2554            scanDirTracedLI(privilegedAppDir,
2555                    mDefParseFlags
2556                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2557                    scanFlags
2558                    | SCAN_AS_SYSTEM
2559                    | SCAN_AS_PRIVILEGED,
2560                    0);
2561
2562            // Collect ordinary system packages.
2563            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2564            scanDirTracedLI(systemAppDir,
2565                    mDefParseFlags
2566                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2567                    scanFlags
2568                    | SCAN_AS_SYSTEM,
2569                    0);
2570
2571            // Collect all vendor packages.
2572            File vendorAppDir = new File("/vendor/app");
2573            try {
2574                vendorAppDir = vendorAppDir.getCanonicalFile();
2575            } catch (IOException e) {
2576                // failed to look up canonical path, continue with original one
2577            }
2578            scanDirTracedLI(vendorAppDir,
2579                    mDefParseFlags
2580                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2581                    scanFlags
2582                    | SCAN_AS_SYSTEM,
2583                    0);
2584
2585            // Collect all OEM packages.
2586            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2587            scanDirTracedLI(oemAppDir,
2588                    mDefParseFlags
2589                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2590                    scanFlags
2591                    | SCAN_AS_SYSTEM
2592                    | SCAN_AS_OEM,
2593                    0);
2594
2595            // Prune any system packages that no longer exist.
2596            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2597            // Stub packages must either be replaced with full versions in the /data
2598            // partition or be disabled.
2599            final List<String> stubSystemApps = new ArrayList<>();
2600            if (!mOnlyCore) {
2601                // do this first before mucking with mPackages for the "expecting better" case
2602                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2603                while (pkgIterator.hasNext()) {
2604                    final PackageParser.Package pkg = pkgIterator.next();
2605                    if (pkg.isStub) {
2606                        stubSystemApps.add(pkg.packageName);
2607                    }
2608                }
2609
2610                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2611                while (psit.hasNext()) {
2612                    PackageSetting ps = psit.next();
2613
2614                    /*
2615                     * If this is not a system app, it can't be a
2616                     * disable system app.
2617                     */
2618                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2619                        continue;
2620                    }
2621
2622                    /*
2623                     * If the package is scanned, it's not erased.
2624                     */
2625                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2626                    if (scannedPkg != null) {
2627                        /*
2628                         * If the system app is both scanned and in the
2629                         * disabled packages list, then it must have been
2630                         * added via OTA. Remove it from the currently
2631                         * scanned package so the previously user-installed
2632                         * application can be scanned.
2633                         */
2634                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2635                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2636                                    + ps.name + "; removing system app.  Last known codePath="
2637                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2638                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2639                                    + scannedPkg.mVersionCode);
2640                            removePackageLI(scannedPkg, true);
2641                            mExpectingBetter.put(ps.name, ps.codePath);
2642                        }
2643
2644                        continue;
2645                    }
2646
2647                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2648                        psit.remove();
2649                        logCriticalInfo(Log.WARN, "System package " + ps.name
2650                                + " no longer exists; it's data will be wiped");
2651                        // Actual deletion of code and data will be handled by later
2652                        // reconciliation step
2653                    } else {
2654                        // we still have a disabled system package, but, it still might have
2655                        // been removed. check the code path still exists and check there's
2656                        // still a package. the latter can happen if an OTA keeps the same
2657                        // code path, but, changes the package name.
2658                        final PackageSetting disabledPs =
2659                                mSettings.getDisabledSystemPkgLPr(ps.name);
2660                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2661                                || disabledPs.pkg == null) {
2662                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2663                        }
2664                    }
2665                }
2666            }
2667
2668            //look for any incomplete package installations
2669            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2670            for (int i = 0; i < deletePkgsList.size(); i++) {
2671                // Actual deletion of code and data will be handled by later
2672                // reconciliation step
2673                final String packageName = deletePkgsList.get(i).name;
2674                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2675                synchronized (mPackages) {
2676                    mSettings.removePackageLPw(packageName);
2677                }
2678            }
2679
2680            //delete tmp files
2681            deleteTempPackageFiles();
2682
2683            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2684
2685            // Remove any shared userIDs that have no associated packages
2686            mSettings.pruneSharedUsersLPw();
2687            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2688            final int systemPackagesCount = mPackages.size();
2689            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2690                    + " ms, packageCount: " + systemPackagesCount
2691                    + " , timePerPackage: "
2692                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2693                    + " , cached: " + cachedSystemApps);
2694            if (mIsUpgrade && systemPackagesCount > 0) {
2695                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2696                        ((int) systemScanTime) / systemPackagesCount);
2697            }
2698            if (!mOnlyCore) {
2699                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2700                        SystemClock.uptimeMillis());
2701                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2702
2703                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2704                        | PackageParser.PARSE_FORWARD_LOCK,
2705                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2706
2707                // Remove disable package settings for updated system apps that were
2708                // removed via an OTA. If the update is no longer present, remove the
2709                // app completely. Otherwise, revoke their system privileges.
2710                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2711                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2712                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2713
2714                    final String msg;
2715                    if (deletedPkg == null) {
2716                        // should have found an update, but, we didn't; remove everything
2717                        msg = "Updated system package " + deletedAppName
2718                                + " no longer exists; removing its data";
2719                        // Actual deletion of code and data will be handled by later
2720                        // reconciliation step
2721                    } else {
2722                        // found an update; revoke system privileges
2723                        msg = "Updated system package + " + deletedAppName
2724                                + " no longer exists; revoking system privileges";
2725
2726                        // Don't do anything if a stub is removed from the system image. If
2727                        // we were to remove the uncompressed version from the /data partition,
2728                        // this is where it'd be done.
2729
2730                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2731                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2732                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2733                    }
2734                    logCriticalInfo(Log.WARN, msg);
2735                }
2736
2737                /*
2738                 * Make sure all system apps that we expected to appear on
2739                 * the userdata partition actually showed up. If they never
2740                 * appeared, crawl back and revive the system version.
2741                 */
2742                for (int i = 0; i < mExpectingBetter.size(); i++) {
2743                    final String packageName = mExpectingBetter.keyAt(i);
2744                    if (!mPackages.containsKey(packageName)) {
2745                        final File scanFile = mExpectingBetter.valueAt(i);
2746
2747                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2748                                + " but never showed up; reverting to system");
2749
2750                        final @ParseFlags int reparseFlags;
2751                        final @ScanFlags int rescanFlags;
2752                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2753                            reparseFlags =
2754                                    mDefParseFlags |
2755                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2756                            rescanFlags =
2757                                    scanFlags
2758                                    | SCAN_AS_SYSTEM
2759                                    | SCAN_AS_PRIVILEGED;
2760                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2761                            reparseFlags =
2762                                    mDefParseFlags |
2763                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2764                            rescanFlags =
2765                                    scanFlags
2766                                    | SCAN_AS_SYSTEM;
2767                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2768                            reparseFlags =
2769                                    mDefParseFlags |
2770                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2771                            rescanFlags =
2772                                    scanFlags
2773                                    | SCAN_AS_SYSTEM;
2774                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2775                            reparseFlags =
2776                                    mDefParseFlags |
2777                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2778                            rescanFlags =
2779                                    scanFlags
2780                                    | SCAN_AS_SYSTEM
2781                                    | SCAN_AS_OEM;
2782                        } else {
2783                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2784                            continue;
2785                        }
2786
2787                        mSettings.enableSystemPackageLPw(packageName);
2788
2789                        try {
2790                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2791                        } catch (PackageManagerException e) {
2792                            Slog.e(TAG, "Failed to parse original system package: "
2793                                    + e.getMessage());
2794                        }
2795                    }
2796                }
2797
2798                // Uncompress and install any stubbed system applications.
2799                // This must be done last to ensure all stubs are replaced or disabled.
2800                decompressSystemApplications(stubSystemApps, scanFlags);
2801
2802                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2803                                - cachedSystemApps;
2804
2805                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2806                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2807                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2808                        + " ms, packageCount: " + dataPackagesCount
2809                        + " , timePerPackage: "
2810                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2811                        + " , cached: " + cachedNonSystemApps);
2812                if (mIsUpgrade && dataPackagesCount > 0) {
2813                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2814                            ((int) dataScanTime) / dataPackagesCount);
2815                }
2816            }
2817            mExpectingBetter.clear();
2818
2819            // Resolve the storage manager.
2820            mStorageManagerPackage = getStorageManagerPackageName();
2821
2822            // Resolve protected action filters. Only the setup wizard is allowed to
2823            // have a high priority filter for these actions.
2824            mSetupWizardPackage = getSetupWizardPackageName();
2825            if (mProtectedFilters.size() > 0) {
2826                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2827                    Slog.i(TAG, "No setup wizard;"
2828                        + " All protected intents capped to priority 0");
2829                }
2830                for (ActivityIntentInfo filter : mProtectedFilters) {
2831                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2832                        if (DEBUG_FILTERS) {
2833                            Slog.i(TAG, "Found setup wizard;"
2834                                + " allow priority " + filter.getPriority() + ";"
2835                                + " package: " + filter.activity.info.packageName
2836                                + " activity: " + filter.activity.className
2837                                + " priority: " + filter.getPriority());
2838                        }
2839                        // skip setup wizard; allow it to keep the high priority filter
2840                        continue;
2841                    }
2842                    if (DEBUG_FILTERS) {
2843                        Slog.i(TAG, "Protected action; cap priority to 0;"
2844                                + " package: " + filter.activity.info.packageName
2845                                + " activity: " + filter.activity.className
2846                                + " origPrio: " + filter.getPriority());
2847                    }
2848                    filter.setPriority(0);
2849                }
2850            }
2851            mDeferProtectedFilters = false;
2852            mProtectedFilters.clear();
2853
2854            // Now that we know all of the shared libraries, update all clients to have
2855            // the correct library paths.
2856            updateAllSharedLibrariesLPw(null);
2857
2858            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2859                // NOTE: We ignore potential failures here during a system scan (like
2860                // the rest of the commands above) because there's precious little we
2861                // can do about it. A settings error is reported, though.
2862                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2863            }
2864
2865            // Now that we know all the packages we are keeping,
2866            // read and update their last usage times.
2867            mPackageUsage.read(mPackages);
2868            mCompilerStats.read();
2869
2870            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2871                    SystemClock.uptimeMillis());
2872            Slog.i(TAG, "Time to scan packages: "
2873                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2874                    + " seconds");
2875
2876            // If the platform SDK has changed since the last time we booted,
2877            // we need to re-grant app permission to catch any new ones that
2878            // appear.  This is really a hack, and means that apps can in some
2879            // cases get permissions that the user didn't initially explicitly
2880            // allow...  it would be nice to have some better way to handle
2881            // this situation.
2882            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
2883            if (sdkUpdated) {
2884                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2885                        + mSdkVersion + "; regranting permissions for internal storage");
2886            }
2887            mPermissionManager.updateAllPermissions(
2888                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
2889                    mPermissionCallback);
2890            ver.sdkVersion = mSdkVersion;
2891
2892            // If this is the first boot or an update from pre-M, and it is a normal
2893            // boot, then we need to initialize the default preferred apps across
2894            // all defined users.
2895            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2896                for (UserInfo user : sUserManager.getUsers(true)) {
2897                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2898                    applyFactoryDefaultBrowserLPw(user.id);
2899                    primeDomainVerificationsLPw(user.id);
2900                }
2901            }
2902
2903            // Prepare storage for system user really early during boot,
2904            // since core system apps like SettingsProvider and SystemUI
2905            // can't wait for user to start
2906            final int storageFlags;
2907            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2908                storageFlags = StorageManager.FLAG_STORAGE_DE;
2909            } else {
2910                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2911            }
2912            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2913                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2914                    true /* onlyCoreApps */);
2915            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2916                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2917                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2918                traceLog.traceBegin("AppDataFixup");
2919                try {
2920                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2921                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2922                } catch (InstallerException e) {
2923                    Slog.w(TAG, "Trouble fixing GIDs", e);
2924                }
2925                traceLog.traceEnd();
2926
2927                traceLog.traceBegin("AppDataPrepare");
2928                if (deferPackages == null || deferPackages.isEmpty()) {
2929                    return;
2930                }
2931                int count = 0;
2932                for (String pkgName : deferPackages) {
2933                    PackageParser.Package pkg = null;
2934                    synchronized (mPackages) {
2935                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2936                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2937                            pkg = ps.pkg;
2938                        }
2939                    }
2940                    if (pkg != null) {
2941                        synchronized (mInstallLock) {
2942                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2943                                    true /* maybeMigrateAppData */);
2944                        }
2945                        count++;
2946                    }
2947                }
2948                traceLog.traceEnd();
2949                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2950            }, "prepareAppData");
2951
2952            // If this is first boot after an OTA, and a normal boot, then
2953            // we need to clear code cache directories.
2954            // Note that we do *not* clear the application profiles. These remain valid
2955            // across OTAs and are used to drive profile verification (post OTA) and
2956            // profile compilation (without waiting to collect a fresh set of profiles).
2957            if (mIsUpgrade && !onlyCore) {
2958                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2959                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2960                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2961                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2962                        // No apps are running this early, so no need to freeze
2963                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2964                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2965                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2966                    }
2967                }
2968                ver.fingerprint = Build.FINGERPRINT;
2969            }
2970
2971            checkDefaultBrowser();
2972
2973            // clear only after permissions and other defaults have been updated
2974            mExistingSystemPackages.clear();
2975            mPromoteSystemApps = false;
2976
2977            // All the changes are done during package scanning.
2978            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2979
2980            // can downgrade to reader
2981            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2982            mSettings.writeLPr();
2983            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2984            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2985                    SystemClock.uptimeMillis());
2986
2987            if (!mOnlyCore) {
2988                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2989                mRequiredInstallerPackage = getRequiredInstallerLPr();
2990                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2991                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2992                if (mIntentFilterVerifierComponent != null) {
2993                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2994                            mIntentFilterVerifierComponent);
2995                } else {
2996                    mIntentFilterVerifier = null;
2997                }
2998                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2999                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3000                        SharedLibraryInfo.VERSION_UNDEFINED);
3001                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3002                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3003                        SharedLibraryInfo.VERSION_UNDEFINED);
3004            } else {
3005                mRequiredVerifierPackage = null;
3006                mRequiredInstallerPackage = null;
3007                mRequiredUninstallerPackage = null;
3008                mIntentFilterVerifierComponent = null;
3009                mIntentFilterVerifier = null;
3010                mServicesSystemSharedLibraryPackageName = null;
3011                mSharedSystemSharedLibraryPackageName = null;
3012            }
3013
3014            mInstallerService = new PackageInstallerService(context, this);
3015            final Pair<ComponentName, String> instantAppResolverComponent =
3016                    getInstantAppResolverLPr();
3017            if (instantAppResolverComponent != null) {
3018                if (DEBUG_EPHEMERAL) {
3019                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3020                }
3021                mInstantAppResolverConnection = new EphemeralResolverConnection(
3022                        mContext, instantAppResolverComponent.first,
3023                        instantAppResolverComponent.second);
3024                mInstantAppResolverSettingsComponent =
3025                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3026            } else {
3027                mInstantAppResolverConnection = null;
3028                mInstantAppResolverSettingsComponent = null;
3029            }
3030            updateInstantAppInstallerLocked(null);
3031
3032            // Read and update the usage of dex files.
3033            // Do this at the end of PM init so that all the packages have their
3034            // data directory reconciled.
3035            // At this point we know the code paths of the packages, so we can validate
3036            // the disk file and build the internal cache.
3037            // The usage file is expected to be small so loading and verifying it
3038            // should take a fairly small time compare to the other activities (e.g. package
3039            // scanning).
3040            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3041            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3042            for (int userId : currentUserIds) {
3043                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3044            }
3045            mDexManager.load(userPackages);
3046            if (mIsUpgrade) {
3047                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3048                        (int) (SystemClock.uptimeMillis() - startTime));
3049            }
3050        } // synchronized (mPackages)
3051        } // synchronized (mInstallLock)
3052
3053        // Now after opening every single application zip, make sure they
3054        // are all flushed.  Not really needed, but keeps things nice and
3055        // tidy.
3056        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3057        Runtime.getRuntime().gc();
3058        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3059
3060        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3061        FallbackCategoryProvider.loadFallbacks();
3062        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3063
3064        // The initial scanning above does many calls into installd while
3065        // holding the mPackages lock, but we're mostly interested in yelling
3066        // once we have a booted system.
3067        mInstaller.setWarnIfHeld(mPackages);
3068
3069        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3070    }
3071
3072    /**
3073     * Uncompress and install stub applications.
3074     * <p>In order to save space on the system partition, some applications are shipped in a
3075     * compressed form. In addition the compressed bits for the full application, the
3076     * system image contains a tiny stub comprised of only the Android manifest.
3077     * <p>During the first boot, attempt to uncompress and install the full application. If
3078     * the application can't be installed for any reason, disable the stub and prevent
3079     * uncompressing the full application during future boots.
3080     * <p>In order to forcefully attempt an installation of a full application, go to app
3081     * settings and enable the application.
3082     */
3083    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3084        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3085            final String pkgName = stubSystemApps.get(i);
3086            // skip if the system package is already disabled
3087            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3088                stubSystemApps.remove(i);
3089                continue;
3090            }
3091            // skip if the package isn't installed (?!); this should never happen
3092            final PackageParser.Package pkg = mPackages.get(pkgName);
3093            if (pkg == null) {
3094                stubSystemApps.remove(i);
3095                continue;
3096            }
3097            // skip if the package has been disabled by the user
3098            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3099            if (ps != null) {
3100                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3101                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3102                    stubSystemApps.remove(i);
3103                    continue;
3104                }
3105            }
3106
3107            if (DEBUG_COMPRESSION) {
3108                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3109            }
3110
3111            // uncompress the binary to its eventual destination on /data
3112            final File scanFile = decompressPackage(pkg);
3113            if (scanFile == null) {
3114                continue;
3115            }
3116
3117            // install the package to replace the stub on /system
3118            try {
3119                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3120                removePackageLI(pkg, true /*chatty*/);
3121                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3122                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3123                        UserHandle.USER_SYSTEM, "android");
3124                stubSystemApps.remove(i);
3125                continue;
3126            } catch (PackageManagerException e) {
3127                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3128            }
3129
3130            // any failed attempt to install the package will be cleaned up later
3131        }
3132
3133        // disable any stub still left; these failed to install the full application
3134        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3135            final String pkgName = stubSystemApps.get(i);
3136            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3137            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3138                    UserHandle.USER_SYSTEM, "android");
3139            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3140        }
3141    }
3142
3143    /**
3144     * Decompresses the given package on the system image onto
3145     * the /data partition.
3146     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3147     */
3148    private File decompressPackage(PackageParser.Package pkg) {
3149        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3150        if (compressedFiles == null || compressedFiles.length == 0) {
3151            if (DEBUG_COMPRESSION) {
3152                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3153            }
3154            return null;
3155        }
3156        final File dstCodePath =
3157                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3158        int ret = PackageManager.INSTALL_SUCCEEDED;
3159        try {
3160            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3161            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3162            for (File srcFile : compressedFiles) {
3163                final String srcFileName = srcFile.getName();
3164                final String dstFileName = srcFileName.substring(
3165                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3166                final File dstFile = new File(dstCodePath, dstFileName);
3167                ret = decompressFile(srcFile, dstFile);
3168                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3169                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3170                            + "; pkg: " + pkg.packageName
3171                            + ", file: " + dstFileName);
3172                    break;
3173                }
3174            }
3175        } catch (ErrnoException e) {
3176            logCriticalInfo(Log.ERROR, "Failed to decompress"
3177                    + "; pkg: " + pkg.packageName
3178                    + ", err: " + e.errno);
3179        }
3180        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3181            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3182            NativeLibraryHelper.Handle handle = null;
3183            try {
3184                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3185                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3186                        null /*abiOverride*/);
3187            } catch (IOException e) {
3188                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3189                        + "; pkg: " + pkg.packageName);
3190                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3191            } finally {
3192                IoUtils.closeQuietly(handle);
3193            }
3194        }
3195        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3196            if (dstCodePath == null || !dstCodePath.exists()) {
3197                return null;
3198            }
3199            removeCodePathLI(dstCodePath);
3200            return null;
3201        }
3202
3203        return dstCodePath;
3204    }
3205
3206    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3207        // we're only interested in updating the installer appliction when 1) it's not
3208        // already set or 2) the modified package is the installer
3209        if (mInstantAppInstallerActivity != null
3210                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3211                        .equals(modifiedPackage)) {
3212            return;
3213        }
3214        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3215    }
3216
3217    private static File preparePackageParserCache(boolean isUpgrade) {
3218        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3219            return null;
3220        }
3221
3222        // Disable package parsing on eng builds to allow for faster incremental development.
3223        if (Build.IS_ENG) {
3224            return null;
3225        }
3226
3227        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3228            Slog.i(TAG, "Disabling package parser cache due to system property.");
3229            return null;
3230        }
3231
3232        // The base directory for the package parser cache lives under /data/system/.
3233        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3234                "package_cache");
3235        if (cacheBaseDir == null) {
3236            return null;
3237        }
3238
3239        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3240        // This also serves to "GC" unused entries when the package cache version changes (which
3241        // can only happen during upgrades).
3242        if (isUpgrade) {
3243            FileUtils.deleteContents(cacheBaseDir);
3244        }
3245
3246
3247        // Return the versioned package cache directory. This is something like
3248        // "/data/system/package_cache/1"
3249        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3250
3251        // The following is a workaround to aid development on non-numbered userdebug
3252        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3253        // the system partition is newer.
3254        //
3255        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3256        // that starts with "eng." to signify that this is an engineering build and not
3257        // destined for release.
3258        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3259            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3260
3261            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3262            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3263            // in general and should not be used for production changes. In this specific case,
3264            // we know that they will work.
3265            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3266            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3267                FileUtils.deleteContents(cacheBaseDir);
3268                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3269            }
3270        }
3271
3272        return cacheDir;
3273    }
3274
3275    @Override
3276    public boolean isFirstBoot() {
3277        // allow instant applications
3278        return mFirstBoot;
3279    }
3280
3281    @Override
3282    public boolean isOnlyCoreApps() {
3283        // allow instant applications
3284        return mOnlyCore;
3285    }
3286
3287    @Override
3288    public boolean isUpgrade() {
3289        // allow instant applications
3290        // The system property allows testing ota flow when upgraded to the same image.
3291        return mIsUpgrade || SystemProperties.getBoolean(
3292                "persist.pm.mock-upgrade", false /* default */);
3293    }
3294
3295    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3296        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3297
3298        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3299                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3300                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3301        if (matches.size() == 1) {
3302            return matches.get(0).getComponentInfo().packageName;
3303        } else if (matches.size() == 0) {
3304            Log.e(TAG, "There should probably be a verifier, but, none were found");
3305            return null;
3306        }
3307        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3308    }
3309
3310    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3311        synchronized (mPackages) {
3312            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3313            if (libraryEntry == null) {
3314                throw new IllegalStateException("Missing required shared library:" + name);
3315            }
3316            return libraryEntry.apk;
3317        }
3318    }
3319
3320    private @NonNull String getRequiredInstallerLPr() {
3321        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3322        intent.addCategory(Intent.CATEGORY_DEFAULT);
3323        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3324
3325        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3326                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3327                UserHandle.USER_SYSTEM);
3328        if (matches.size() == 1) {
3329            ResolveInfo resolveInfo = matches.get(0);
3330            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3331                throw new RuntimeException("The installer must be a privileged app");
3332            }
3333            return matches.get(0).getComponentInfo().packageName;
3334        } else {
3335            throw new RuntimeException("There must be exactly one installer; found " + matches);
3336        }
3337    }
3338
3339    private @NonNull String getRequiredUninstallerLPr() {
3340        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3341        intent.addCategory(Intent.CATEGORY_DEFAULT);
3342        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3343
3344        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3345                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3346                UserHandle.USER_SYSTEM);
3347        if (resolveInfo == null ||
3348                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3349            throw new RuntimeException("There must be exactly one uninstaller; found "
3350                    + resolveInfo);
3351        }
3352        return resolveInfo.getComponentInfo().packageName;
3353    }
3354
3355    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3356        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3357
3358        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3359                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3360                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3361        ResolveInfo best = null;
3362        final int N = matches.size();
3363        for (int i = 0; i < N; i++) {
3364            final ResolveInfo cur = matches.get(i);
3365            final String packageName = cur.getComponentInfo().packageName;
3366            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3367                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3368                continue;
3369            }
3370
3371            if (best == null || cur.priority > best.priority) {
3372                best = cur;
3373            }
3374        }
3375
3376        if (best != null) {
3377            return best.getComponentInfo().getComponentName();
3378        }
3379        Slog.w(TAG, "Intent filter verifier not found");
3380        return null;
3381    }
3382
3383    @Override
3384    public @Nullable ComponentName getInstantAppResolverComponent() {
3385        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3386            return null;
3387        }
3388        synchronized (mPackages) {
3389            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3390            if (instantAppResolver == null) {
3391                return null;
3392            }
3393            return instantAppResolver.first;
3394        }
3395    }
3396
3397    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3398        final String[] packageArray =
3399                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3400        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3401            if (DEBUG_EPHEMERAL) {
3402                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3403            }
3404            return null;
3405        }
3406
3407        final int callingUid = Binder.getCallingUid();
3408        final int resolveFlags =
3409                MATCH_DIRECT_BOOT_AWARE
3410                | MATCH_DIRECT_BOOT_UNAWARE
3411                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3412        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3413        final Intent resolverIntent = new Intent(actionName);
3414        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3415                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3416        // temporarily look for the old action
3417        if (resolvers.size() == 0) {
3418            if (DEBUG_EPHEMERAL) {
3419                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3420            }
3421            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3422            resolverIntent.setAction(actionName);
3423            resolvers = queryIntentServicesInternal(resolverIntent, null,
3424                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3425        }
3426        final int N = resolvers.size();
3427        if (N == 0) {
3428            if (DEBUG_EPHEMERAL) {
3429                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3430            }
3431            return null;
3432        }
3433
3434        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3435        for (int i = 0; i < N; i++) {
3436            final ResolveInfo info = resolvers.get(i);
3437
3438            if (info.serviceInfo == null) {
3439                continue;
3440            }
3441
3442            final String packageName = info.serviceInfo.packageName;
3443            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3444                if (DEBUG_EPHEMERAL) {
3445                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3446                            + " pkg: " + packageName + ", info:" + info);
3447                }
3448                continue;
3449            }
3450
3451            if (DEBUG_EPHEMERAL) {
3452                Slog.v(TAG, "Ephemeral resolver found;"
3453                        + " pkg: " + packageName + ", info:" + info);
3454            }
3455            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3456        }
3457        if (DEBUG_EPHEMERAL) {
3458            Slog.v(TAG, "Ephemeral resolver NOT found");
3459        }
3460        return null;
3461    }
3462
3463    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3464        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3465        intent.addCategory(Intent.CATEGORY_DEFAULT);
3466        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3467
3468        final int resolveFlags =
3469                MATCH_DIRECT_BOOT_AWARE
3470                | MATCH_DIRECT_BOOT_UNAWARE
3471                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3472        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3473                resolveFlags, UserHandle.USER_SYSTEM);
3474        // temporarily look for the old action
3475        if (matches.isEmpty()) {
3476            if (DEBUG_EPHEMERAL) {
3477                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3478            }
3479            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3480            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3481                    resolveFlags, UserHandle.USER_SYSTEM);
3482        }
3483        Iterator<ResolveInfo> iter = matches.iterator();
3484        while (iter.hasNext()) {
3485            final ResolveInfo rInfo = iter.next();
3486            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3487            if (ps != null) {
3488                final PermissionsState permissionsState = ps.getPermissionsState();
3489                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3490                    continue;
3491                }
3492            }
3493            iter.remove();
3494        }
3495        if (matches.size() == 0) {
3496            return null;
3497        } else if (matches.size() == 1) {
3498            return (ActivityInfo) matches.get(0).getComponentInfo();
3499        } else {
3500            throw new RuntimeException(
3501                    "There must be at most one ephemeral installer; found " + matches);
3502        }
3503    }
3504
3505    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3506            @NonNull ComponentName resolver) {
3507        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3508                .addCategory(Intent.CATEGORY_DEFAULT)
3509                .setPackage(resolver.getPackageName());
3510        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3511        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3512                UserHandle.USER_SYSTEM);
3513        // temporarily look for the old action
3514        if (matches.isEmpty()) {
3515            if (DEBUG_EPHEMERAL) {
3516                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3517            }
3518            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3519            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3520                    UserHandle.USER_SYSTEM);
3521        }
3522        if (matches.isEmpty()) {
3523            return null;
3524        }
3525        return matches.get(0).getComponentInfo().getComponentName();
3526    }
3527
3528    private void primeDomainVerificationsLPw(int userId) {
3529        if (DEBUG_DOMAIN_VERIFICATION) {
3530            Slog.d(TAG, "Priming domain verifications in user " + userId);
3531        }
3532
3533        SystemConfig systemConfig = SystemConfig.getInstance();
3534        ArraySet<String> packages = systemConfig.getLinkedApps();
3535
3536        for (String packageName : packages) {
3537            PackageParser.Package pkg = mPackages.get(packageName);
3538            if (pkg != null) {
3539                if (!pkg.isSystem()) {
3540                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3541                    continue;
3542                }
3543
3544                ArraySet<String> domains = null;
3545                for (PackageParser.Activity a : pkg.activities) {
3546                    for (ActivityIntentInfo filter : a.intents) {
3547                        if (hasValidDomains(filter)) {
3548                            if (domains == null) {
3549                                domains = new ArraySet<String>();
3550                            }
3551                            domains.addAll(filter.getHostsList());
3552                        }
3553                    }
3554                }
3555
3556                if (domains != null && domains.size() > 0) {
3557                    if (DEBUG_DOMAIN_VERIFICATION) {
3558                        Slog.v(TAG, "      + " + packageName);
3559                    }
3560                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3561                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3562                    // and then 'always' in the per-user state actually used for intent resolution.
3563                    final IntentFilterVerificationInfo ivi;
3564                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3565                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3566                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3567                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3568                } else {
3569                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3570                            + "' does not handle web links");
3571                }
3572            } else {
3573                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3574            }
3575        }
3576
3577        scheduleWritePackageRestrictionsLocked(userId);
3578        scheduleWriteSettingsLocked();
3579    }
3580
3581    private void applyFactoryDefaultBrowserLPw(int userId) {
3582        // The default browser app's package name is stored in a string resource,
3583        // with a product-specific overlay used for vendor customization.
3584        String browserPkg = mContext.getResources().getString(
3585                com.android.internal.R.string.default_browser);
3586        if (!TextUtils.isEmpty(browserPkg)) {
3587            // non-empty string => required to be a known package
3588            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3589            if (ps == null) {
3590                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3591                browserPkg = null;
3592            } else {
3593                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3594            }
3595        }
3596
3597        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3598        // default.  If there's more than one, just leave everything alone.
3599        if (browserPkg == null) {
3600            calculateDefaultBrowserLPw(userId);
3601        }
3602    }
3603
3604    private void calculateDefaultBrowserLPw(int userId) {
3605        List<String> allBrowsers = resolveAllBrowserApps(userId);
3606        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3607        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3608    }
3609
3610    private List<String> resolveAllBrowserApps(int userId) {
3611        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3612        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3613                PackageManager.MATCH_ALL, userId);
3614
3615        final int count = list.size();
3616        List<String> result = new ArrayList<String>(count);
3617        for (int i=0; i<count; i++) {
3618            ResolveInfo info = list.get(i);
3619            if (info.activityInfo == null
3620                    || !info.handleAllWebDataURI
3621                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3622                    || result.contains(info.activityInfo.packageName)) {
3623                continue;
3624            }
3625            result.add(info.activityInfo.packageName);
3626        }
3627
3628        return result;
3629    }
3630
3631    private boolean packageIsBrowser(String packageName, int userId) {
3632        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3633                PackageManager.MATCH_ALL, userId);
3634        final int N = list.size();
3635        for (int i = 0; i < N; i++) {
3636            ResolveInfo info = list.get(i);
3637            if (packageName.equals(info.activityInfo.packageName)) {
3638                return true;
3639            }
3640        }
3641        return false;
3642    }
3643
3644    private void checkDefaultBrowser() {
3645        final int myUserId = UserHandle.myUserId();
3646        final String packageName = getDefaultBrowserPackageName(myUserId);
3647        if (packageName != null) {
3648            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3649            if (info == null) {
3650                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3651                synchronized (mPackages) {
3652                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3653                }
3654            }
3655        }
3656    }
3657
3658    @Override
3659    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3660            throws RemoteException {
3661        try {
3662            return super.onTransact(code, data, reply, flags);
3663        } catch (RuntimeException e) {
3664            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3665                Slog.wtf(TAG, "Package Manager Crash", e);
3666            }
3667            throw e;
3668        }
3669    }
3670
3671    static int[] appendInts(int[] cur, int[] add) {
3672        if (add == null) return cur;
3673        if (cur == null) return add;
3674        final int N = add.length;
3675        for (int i=0; i<N; i++) {
3676            cur = appendInt(cur, add[i]);
3677        }
3678        return cur;
3679    }
3680
3681    /**
3682     * Returns whether or not a full application can see an instant application.
3683     * <p>
3684     * Currently, there are three cases in which this can occur:
3685     * <ol>
3686     * <li>The calling application is a "special" process. Special processes
3687     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3688     * <li>The calling application has the permission
3689     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3690     * <li>The calling application is the default launcher on the
3691     *     system partition.</li>
3692     * </ol>
3693     */
3694    private boolean canViewInstantApps(int callingUid, int userId) {
3695        if (callingUid < Process.FIRST_APPLICATION_UID) {
3696            return true;
3697        }
3698        if (mContext.checkCallingOrSelfPermission(
3699                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3700            return true;
3701        }
3702        if (mContext.checkCallingOrSelfPermission(
3703                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3704            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3705            if (homeComponent != null
3706                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3707                return true;
3708            }
3709        }
3710        return false;
3711    }
3712
3713    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3714        if (!sUserManager.exists(userId)) return null;
3715        if (ps == null) {
3716            return null;
3717        }
3718        PackageParser.Package p = ps.pkg;
3719        if (p == null) {
3720            return null;
3721        }
3722        final int callingUid = Binder.getCallingUid();
3723        // Filter out ephemeral app metadata:
3724        //   * The system/shell/root can see metadata for any app
3725        //   * An installed app can see metadata for 1) other installed apps
3726        //     and 2) ephemeral apps that have explicitly interacted with it
3727        //   * Ephemeral apps can only see their own data and exposed installed apps
3728        //   * Holding a signature permission allows seeing instant apps
3729        if (filterAppAccessLPr(ps, callingUid, userId)) {
3730            return null;
3731        }
3732
3733        final PermissionsState permissionsState = ps.getPermissionsState();
3734
3735        // Compute GIDs only if requested
3736        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3737                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3738        // Compute granted permissions only if package has requested permissions
3739        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3740                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3741        final PackageUserState state = ps.readUserState(userId);
3742
3743        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3744                && ps.isSystem()) {
3745            flags |= MATCH_ANY_USER;
3746        }
3747
3748        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3749                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3750
3751        if (packageInfo == null) {
3752            return null;
3753        }
3754
3755        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3756                resolveExternalPackageNameLPr(p);
3757
3758        return packageInfo;
3759    }
3760
3761    @Override
3762    public void checkPackageStartable(String packageName, int userId) {
3763        final int callingUid = Binder.getCallingUid();
3764        if (getInstantAppPackageName(callingUid) != null) {
3765            throw new SecurityException("Instant applications don't have access to this method");
3766        }
3767        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3768        synchronized (mPackages) {
3769            final PackageSetting ps = mSettings.mPackages.get(packageName);
3770            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3771                throw new SecurityException("Package " + packageName + " was not found!");
3772            }
3773
3774            if (!ps.getInstalled(userId)) {
3775                throw new SecurityException(
3776                        "Package " + packageName + " was not installed for user " + userId + "!");
3777            }
3778
3779            if (mSafeMode && !ps.isSystem()) {
3780                throw new SecurityException("Package " + packageName + " not a system app!");
3781            }
3782
3783            if (mFrozenPackages.contains(packageName)) {
3784                throw new SecurityException("Package " + packageName + " is currently frozen!");
3785            }
3786
3787            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3788                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3789            }
3790        }
3791    }
3792
3793    @Override
3794    public boolean isPackageAvailable(String packageName, int userId) {
3795        if (!sUserManager.exists(userId)) return false;
3796        final int callingUid = Binder.getCallingUid();
3797        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3798                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3799        synchronized (mPackages) {
3800            PackageParser.Package p = mPackages.get(packageName);
3801            if (p != null) {
3802                final PackageSetting ps = (PackageSetting) p.mExtras;
3803                if (filterAppAccessLPr(ps, callingUid, userId)) {
3804                    return false;
3805                }
3806                if (ps != null) {
3807                    final PackageUserState state = ps.readUserState(userId);
3808                    if (state != null) {
3809                        return PackageParser.isAvailable(state);
3810                    }
3811                }
3812            }
3813        }
3814        return false;
3815    }
3816
3817    @Override
3818    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3819        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3820                flags, Binder.getCallingUid(), userId);
3821    }
3822
3823    @Override
3824    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3825            int flags, int userId) {
3826        return getPackageInfoInternal(versionedPackage.getPackageName(),
3827                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3828    }
3829
3830    /**
3831     * Important: The provided filterCallingUid is used exclusively to filter out packages
3832     * that can be seen based on user state. It's typically the original caller uid prior
3833     * to clearing. Because it can only be provided by trusted code, it's value can be
3834     * trusted and will be used as-is; unlike userId which will be validated by this method.
3835     */
3836    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3837            int flags, int filterCallingUid, int userId) {
3838        if (!sUserManager.exists(userId)) return null;
3839        flags = updateFlagsForPackage(flags, userId, packageName);
3840        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3841                false /* requireFullPermission */, false /* checkShell */, "get package info");
3842
3843        // reader
3844        synchronized (mPackages) {
3845            // Normalize package name to handle renamed packages and static libs
3846            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3847
3848            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3849            if (matchFactoryOnly) {
3850                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3851                if (ps != null) {
3852                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3853                        return null;
3854                    }
3855                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3856                        return null;
3857                    }
3858                    return generatePackageInfo(ps, flags, userId);
3859                }
3860            }
3861
3862            PackageParser.Package p = mPackages.get(packageName);
3863            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3864                return null;
3865            }
3866            if (DEBUG_PACKAGE_INFO)
3867                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3868            if (p != null) {
3869                final PackageSetting ps = (PackageSetting) p.mExtras;
3870                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3871                    return null;
3872                }
3873                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3874                    return null;
3875                }
3876                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3877            }
3878            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3879                final PackageSetting ps = mSettings.mPackages.get(packageName);
3880                if (ps == null) return null;
3881                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3882                    return null;
3883                }
3884                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3885                    return null;
3886                }
3887                return generatePackageInfo(ps, flags, userId);
3888            }
3889        }
3890        return null;
3891    }
3892
3893    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3894        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3895            return true;
3896        }
3897        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3898            return true;
3899        }
3900        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3901            return true;
3902        }
3903        return false;
3904    }
3905
3906    private boolean isComponentVisibleToInstantApp(
3907            @Nullable ComponentName component, @ComponentType int type) {
3908        if (type == TYPE_ACTIVITY) {
3909            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3910            return activity != null
3911                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3912                    : false;
3913        } else if (type == TYPE_RECEIVER) {
3914            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3915            return activity != null
3916                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3917                    : false;
3918        } else if (type == TYPE_SERVICE) {
3919            final PackageParser.Service service = mServices.mServices.get(component);
3920            return service != null
3921                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3922                    : false;
3923        } else if (type == TYPE_PROVIDER) {
3924            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3925            return provider != null
3926                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3927                    : false;
3928        } else if (type == TYPE_UNKNOWN) {
3929            return isComponentVisibleToInstantApp(component);
3930        }
3931        return false;
3932    }
3933
3934    /**
3935     * Returns whether or not access to the application should be filtered.
3936     * <p>
3937     * Access may be limited based upon whether the calling or target applications
3938     * are instant applications.
3939     *
3940     * @see #canAccessInstantApps(int)
3941     */
3942    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3943            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3944        // if we're in an isolated process, get the real calling UID
3945        if (Process.isIsolated(callingUid)) {
3946            callingUid = mIsolatedOwners.get(callingUid);
3947        }
3948        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3949        final boolean callerIsInstantApp = instantAppPkgName != null;
3950        if (ps == null) {
3951            if (callerIsInstantApp) {
3952                // pretend the application exists, but, needs to be filtered
3953                return true;
3954            }
3955            return false;
3956        }
3957        // if the target and caller are the same application, don't filter
3958        if (isCallerSameApp(ps.name, callingUid)) {
3959            return false;
3960        }
3961        if (callerIsInstantApp) {
3962            // request for a specific component; if it hasn't been explicitly exposed, filter
3963            if (component != null) {
3964                return !isComponentVisibleToInstantApp(component, componentType);
3965            }
3966            // request for application; if no components have been explicitly exposed, filter
3967            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3968        }
3969        if (ps.getInstantApp(userId)) {
3970            // caller can see all components of all instant applications, don't filter
3971            if (canViewInstantApps(callingUid, userId)) {
3972                return false;
3973            }
3974            // request for a specific instant application component, filter
3975            if (component != null) {
3976                return true;
3977            }
3978            // request for an instant application; if the caller hasn't been granted access, filter
3979            return !mInstantAppRegistry.isInstantAccessGranted(
3980                    userId, UserHandle.getAppId(callingUid), ps.appId);
3981        }
3982        return false;
3983    }
3984
3985    /**
3986     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3987     */
3988    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3989        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3990    }
3991
3992    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3993            int flags) {
3994        // Callers can access only the libs they depend on, otherwise they need to explicitly
3995        // ask for the shared libraries given the caller is allowed to access all static libs.
3996        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3997            // System/shell/root get to see all static libs
3998            final int appId = UserHandle.getAppId(uid);
3999            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4000                    || appId == Process.ROOT_UID) {
4001                return false;
4002            }
4003        }
4004
4005        // No package means no static lib as it is always on internal storage
4006        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4007            return false;
4008        }
4009
4010        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4011                ps.pkg.staticSharedLibVersion);
4012        if (libEntry == null) {
4013            return false;
4014        }
4015
4016        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4017        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4018        if (uidPackageNames == null) {
4019            return true;
4020        }
4021
4022        for (String uidPackageName : uidPackageNames) {
4023            if (ps.name.equals(uidPackageName)) {
4024                return false;
4025            }
4026            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4027            if (uidPs != null) {
4028                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4029                        libEntry.info.getName());
4030                if (index < 0) {
4031                    continue;
4032                }
4033                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4034                    return false;
4035                }
4036            }
4037        }
4038        return true;
4039    }
4040
4041    @Override
4042    public String[] currentToCanonicalPackageNames(String[] names) {
4043        final int callingUid = Binder.getCallingUid();
4044        if (getInstantAppPackageName(callingUid) != null) {
4045            return names;
4046        }
4047        final String[] out = new String[names.length];
4048        // reader
4049        synchronized (mPackages) {
4050            final int callingUserId = UserHandle.getUserId(callingUid);
4051            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4052            for (int i=names.length-1; i>=0; i--) {
4053                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4054                boolean translateName = false;
4055                if (ps != null && ps.realName != null) {
4056                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4057                    translateName = !targetIsInstantApp
4058                            || canViewInstantApps
4059                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4060                                    UserHandle.getAppId(callingUid), ps.appId);
4061                }
4062                out[i] = translateName ? ps.realName : names[i];
4063            }
4064        }
4065        return out;
4066    }
4067
4068    @Override
4069    public String[] canonicalToCurrentPackageNames(String[] names) {
4070        final int callingUid = Binder.getCallingUid();
4071        if (getInstantAppPackageName(callingUid) != null) {
4072            return names;
4073        }
4074        final String[] out = new String[names.length];
4075        // reader
4076        synchronized (mPackages) {
4077            final int callingUserId = UserHandle.getUserId(callingUid);
4078            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4079            for (int i=names.length-1; i>=0; i--) {
4080                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4081                boolean translateName = false;
4082                if (cur != null) {
4083                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4084                    final boolean targetIsInstantApp =
4085                            ps != null && ps.getInstantApp(callingUserId);
4086                    translateName = !targetIsInstantApp
4087                            || canViewInstantApps
4088                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4089                                    UserHandle.getAppId(callingUid), ps.appId);
4090                }
4091                out[i] = translateName ? cur : names[i];
4092            }
4093        }
4094        return out;
4095    }
4096
4097    @Override
4098    public int getPackageUid(String packageName, int flags, int userId) {
4099        if (!sUserManager.exists(userId)) return -1;
4100        final int callingUid = Binder.getCallingUid();
4101        flags = updateFlagsForPackage(flags, userId, packageName);
4102        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4103                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4104
4105        // reader
4106        synchronized (mPackages) {
4107            final PackageParser.Package p = mPackages.get(packageName);
4108            if (p != null && p.isMatch(flags)) {
4109                PackageSetting ps = (PackageSetting) p.mExtras;
4110                if (filterAppAccessLPr(ps, callingUid, userId)) {
4111                    return -1;
4112                }
4113                return UserHandle.getUid(userId, p.applicationInfo.uid);
4114            }
4115            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4116                final PackageSetting ps = mSettings.mPackages.get(packageName);
4117                if (ps != null && ps.isMatch(flags)
4118                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4119                    return UserHandle.getUid(userId, ps.appId);
4120                }
4121            }
4122        }
4123
4124        return -1;
4125    }
4126
4127    @Override
4128    public int[] getPackageGids(String packageName, int flags, int userId) {
4129        if (!sUserManager.exists(userId)) return null;
4130        final int callingUid = Binder.getCallingUid();
4131        flags = updateFlagsForPackage(flags, userId, packageName);
4132        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4133                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4134
4135        // reader
4136        synchronized (mPackages) {
4137            final PackageParser.Package p = mPackages.get(packageName);
4138            if (p != null && p.isMatch(flags)) {
4139                PackageSetting ps = (PackageSetting) p.mExtras;
4140                if (filterAppAccessLPr(ps, callingUid, userId)) {
4141                    return null;
4142                }
4143                // TODO: Shouldn't this be checking for package installed state for userId and
4144                // return null?
4145                return ps.getPermissionsState().computeGids(userId);
4146            }
4147            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4148                final PackageSetting ps = mSettings.mPackages.get(packageName);
4149                if (ps != null && ps.isMatch(flags)
4150                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4151                    return ps.getPermissionsState().computeGids(userId);
4152                }
4153            }
4154        }
4155
4156        return null;
4157    }
4158
4159    @Override
4160    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4161        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4162    }
4163
4164    @Override
4165    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4166            int flags) {
4167        final List<PermissionInfo> permissionList =
4168                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4169        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4170    }
4171
4172    @Override
4173    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4174        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4175    }
4176
4177    @Override
4178    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4179        final List<PermissionGroupInfo> permissionList =
4180                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4181        return (permissionList == null)
4182                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4183    }
4184
4185    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4186            int filterCallingUid, int userId) {
4187        if (!sUserManager.exists(userId)) return null;
4188        PackageSetting ps = mSettings.mPackages.get(packageName);
4189        if (ps != null) {
4190            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4191                return null;
4192            }
4193            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4194                return null;
4195            }
4196            if (ps.pkg == null) {
4197                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4198                if (pInfo != null) {
4199                    return pInfo.applicationInfo;
4200                }
4201                return null;
4202            }
4203            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4204                    ps.readUserState(userId), userId);
4205            if (ai != null) {
4206                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4207            }
4208            return ai;
4209        }
4210        return null;
4211    }
4212
4213    @Override
4214    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4215        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4216    }
4217
4218    /**
4219     * Important: The provided filterCallingUid is used exclusively to filter out applications
4220     * that can be seen based on user state. It's typically the original caller uid prior
4221     * to clearing. Because it can only be provided by trusted code, it's value can be
4222     * trusted and will be used as-is; unlike userId which will be validated by this method.
4223     */
4224    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4225            int filterCallingUid, int userId) {
4226        if (!sUserManager.exists(userId)) return null;
4227        flags = updateFlagsForApplication(flags, userId, packageName);
4228        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4229                false /* requireFullPermission */, false /* checkShell */, "get application info");
4230
4231        // writer
4232        synchronized (mPackages) {
4233            // Normalize package name to handle renamed packages and static libs
4234            packageName = resolveInternalPackageNameLPr(packageName,
4235                    PackageManager.VERSION_CODE_HIGHEST);
4236
4237            PackageParser.Package p = mPackages.get(packageName);
4238            if (DEBUG_PACKAGE_INFO) Log.v(
4239                    TAG, "getApplicationInfo " + packageName
4240                    + ": " + p);
4241            if (p != null) {
4242                PackageSetting ps = mSettings.mPackages.get(packageName);
4243                if (ps == null) return null;
4244                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4245                    return null;
4246                }
4247                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4248                    return null;
4249                }
4250                // Note: isEnabledLP() does not apply here - always return info
4251                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4252                        p, flags, ps.readUserState(userId), userId);
4253                if (ai != null) {
4254                    ai.packageName = resolveExternalPackageNameLPr(p);
4255                }
4256                return ai;
4257            }
4258            if ("android".equals(packageName)||"system".equals(packageName)) {
4259                return mAndroidApplication;
4260            }
4261            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4262                // Already generates the external package name
4263                return generateApplicationInfoFromSettingsLPw(packageName,
4264                        flags, filterCallingUid, userId);
4265            }
4266        }
4267        return null;
4268    }
4269
4270    private String normalizePackageNameLPr(String packageName) {
4271        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4272        return normalizedPackageName != null ? normalizedPackageName : packageName;
4273    }
4274
4275    @Override
4276    public void deletePreloadsFileCache() {
4277        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4278            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4279        }
4280        File dir = Environment.getDataPreloadsFileCacheDirectory();
4281        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4282        FileUtils.deleteContents(dir);
4283    }
4284
4285    @Override
4286    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4287            final int storageFlags, final IPackageDataObserver observer) {
4288        mContext.enforceCallingOrSelfPermission(
4289                android.Manifest.permission.CLEAR_APP_CACHE, null);
4290        mHandler.post(() -> {
4291            boolean success = false;
4292            try {
4293                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4294                success = true;
4295            } catch (IOException e) {
4296                Slog.w(TAG, e);
4297            }
4298            if (observer != null) {
4299                try {
4300                    observer.onRemoveCompleted(null, success);
4301                } catch (RemoteException e) {
4302                    Slog.w(TAG, e);
4303                }
4304            }
4305        });
4306    }
4307
4308    @Override
4309    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4310            final int storageFlags, final IntentSender pi) {
4311        mContext.enforceCallingOrSelfPermission(
4312                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4313        mHandler.post(() -> {
4314            boolean success = false;
4315            try {
4316                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4317                success = true;
4318            } catch (IOException e) {
4319                Slog.w(TAG, e);
4320            }
4321            if (pi != null) {
4322                try {
4323                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4324                } catch (SendIntentException e) {
4325                    Slog.w(TAG, e);
4326                }
4327            }
4328        });
4329    }
4330
4331    /**
4332     * Blocking call to clear various types of cached data across the system
4333     * until the requested bytes are available.
4334     */
4335    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4336        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4337        final File file = storage.findPathForUuid(volumeUuid);
4338        if (file.getUsableSpace() >= bytes) return;
4339
4340        if (ENABLE_FREE_CACHE_V2) {
4341            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4342                    volumeUuid);
4343            final boolean aggressive = (storageFlags
4344                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4345            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4346
4347            // 1. Pre-flight to determine if we have any chance to succeed
4348            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4349            if (internalVolume && (aggressive || SystemProperties
4350                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4351                deletePreloadsFileCache();
4352                if (file.getUsableSpace() >= bytes) return;
4353            }
4354
4355            // 3. Consider parsed APK data (aggressive only)
4356            if (internalVolume && aggressive) {
4357                FileUtils.deleteContents(mCacheDir);
4358                if (file.getUsableSpace() >= bytes) return;
4359            }
4360
4361            // 4. Consider cached app data (above quotas)
4362            try {
4363                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4364                        Installer.FLAG_FREE_CACHE_V2);
4365            } catch (InstallerException ignored) {
4366            }
4367            if (file.getUsableSpace() >= bytes) return;
4368
4369            // 5. Consider shared libraries with refcount=0 and age>min cache period
4370            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4371                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4372                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4373                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4374                return;
4375            }
4376
4377            // 6. Consider dexopt output (aggressive only)
4378            // TODO: Implement
4379
4380            // 7. Consider installed instant apps unused longer than min cache period
4381            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4382                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4383                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4384                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4385                return;
4386            }
4387
4388            // 8. Consider cached app data (below quotas)
4389            try {
4390                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4391                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4392            } catch (InstallerException ignored) {
4393            }
4394            if (file.getUsableSpace() >= bytes) return;
4395
4396            // 9. Consider DropBox entries
4397            // TODO: Implement
4398
4399            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4400            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4401                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4402                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4403                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4404                return;
4405            }
4406        } else {
4407            try {
4408                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4409            } catch (InstallerException ignored) {
4410            }
4411            if (file.getUsableSpace() >= bytes) return;
4412        }
4413
4414        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4415    }
4416
4417    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4418            throws IOException {
4419        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4420        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4421
4422        List<VersionedPackage> packagesToDelete = null;
4423        final long now = System.currentTimeMillis();
4424
4425        synchronized (mPackages) {
4426            final int[] allUsers = sUserManager.getUserIds();
4427            final int libCount = mSharedLibraries.size();
4428            for (int i = 0; i < libCount; i++) {
4429                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4430                if (versionedLib == null) {
4431                    continue;
4432                }
4433                final int versionCount = versionedLib.size();
4434                for (int j = 0; j < versionCount; j++) {
4435                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4436                    // Skip packages that are not static shared libs.
4437                    if (!libInfo.isStatic()) {
4438                        break;
4439                    }
4440                    // Important: We skip static shared libs used for some user since
4441                    // in such a case we need to keep the APK on the device. The check for
4442                    // a lib being used for any user is performed by the uninstall call.
4443                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4444                    // Resolve the package name - we use synthetic package names internally
4445                    final String internalPackageName = resolveInternalPackageNameLPr(
4446                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4447                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4448                    // Skip unused static shared libs cached less than the min period
4449                    // to prevent pruning a lib needed by a subsequently installed package.
4450                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4451                        continue;
4452                    }
4453                    if (packagesToDelete == null) {
4454                        packagesToDelete = new ArrayList<>();
4455                    }
4456                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4457                            declaringPackage.getVersionCode()));
4458                }
4459            }
4460        }
4461
4462        if (packagesToDelete != null) {
4463            final int packageCount = packagesToDelete.size();
4464            for (int i = 0; i < packageCount; i++) {
4465                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4466                // Delete the package synchronously (will fail of the lib used for any user).
4467                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4468                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4469                                == PackageManager.DELETE_SUCCEEDED) {
4470                    if (volume.getUsableSpace() >= neededSpace) {
4471                        return true;
4472                    }
4473                }
4474            }
4475        }
4476
4477        return false;
4478    }
4479
4480    /**
4481     * Update given flags based on encryption status of current user.
4482     */
4483    private int updateFlags(int flags, int userId) {
4484        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4485                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4486            // Caller expressed an explicit opinion about what encryption
4487            // aware/unaware components they want to see, so fall through and
4488            // give them what they want
4489        } else {
4490            // Caller expressed no opinion, so match based on user state
4491            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4492                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4493            } else {
4494                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4495            }
4496        }
4497        return flags;
4498    }
4499
4500    private UserManagerInternal getUserManagerInternal() {
4501        if (mUserManagerInternal == null) {
4502            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4503        }
4504        return mUserManagerInternal;
4505    }
4506
4507    private DeviceIdleController.LocalService getDeviceIdleController() {
4508        if (mDeviceIdleController == null) {
4509            mDeviceIdleController =
4510                    LocalServices.getService(DeviceIdleController.LocalService.class);
4511        }
4512        return mDeviceIdleController;
4513    }
4514
4515    /**
4516     * Update given flags when being used to request {@link PackageInfo}.
4517     */
4518    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4519        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4520        boolean triaged = true;
4521        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4522                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4523            // Caller is asking for component details, so they'd better be
4524            // asking for specific encryption matching behavior, or be triaged
4525            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4526                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4527                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4528                triaged = false;
4529            }
4530        }
4531        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4532                | PackageManager.MATCH_SYSTEM_ONLY
4533                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4534            triaged = false;
4535        }
4536        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4537            mPermissionManager.enforceCrossUserPermission(
4538                    Binder.getCallingUid(), userId, false, false,
4539                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4540                    + Debug.getCallers(5));
4541        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4542                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4543            // If the caller wants all packages and has a restricted profile associated with it,
4544            // then match all users. This is to make sure that launchers that need to access work
4545            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4546            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4547            flags |= PackageManager.MATCH_ANY_USER;
4548        }
4549        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4550            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4551                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4552        }
4553        return updateFlags(flags, userId);
4554    }
4555
4556    /**
4557     * Update given flags when being used to request {@link ApplicationInfo}.
4558     */
4559    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4560        return updateFlagsForPackage(flags, userId, cookie);
4561    }
4562
4563    /**
4564     * Update given flags when being used to request {@link ComponentInfo}.
4565     */
4566    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4567        if (cookie instanceof Intent) {
4568            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4569                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4570            }
4571        }
4572
4573        boolean triaged = true;
4574        // Caller is asking for component details, so they'd better be
4575        // asking for specific encryption matching behavior, or be triaged
4576        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4577                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4578                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4579            triaged = false;
4580        }
4581        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4582            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4583                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4584        }
4585
4586        return updateFlags(flags, userId);
4587    }
4588
4589    /**
4590     * Update given intent when being used to request {@link ResolveInfo}.
4591     */
4592    private Intent updateIntentForResolve(Intent intent) {
4593        if (intent.getSelector() != null) {
4594            intent = intent.getSelector();
4595        }
4596        if (DEBUG_PREFERRED) {
4597            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4598        }
4599        return intent;
4600    }
4601
4602    /**
4603     * Update given flags when being used to request {@link ResolveInfo}.
4604     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4605     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4606     * flag set. However, this flag is only honoured in three circumstances:
4607     * <ul>
4608     * <li>when called from a system process</li>
4609     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4610     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4611     * action and a {@code android.intent.category.BROWSABLE} category</li>
4612     * </ul>
4613     */
4614    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4615        return updateFlagsForResolve(flags, userId, intent, callingUid,
4616                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4617    }
4618    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4619            boolean wantInstantApps) {
4620        return updateFlagsForResolve(flags, userId, intent, callingUid,
4621                wantInstantApps, false /*onlyExposedExplicitly*/);
4622    }
4623    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4624            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4625        // Safe mode means we shouldn't match any third-party components
4626        if (mSafeMode) {
4627            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4628        }
4629        if (getInstantAppPackageName(callingUid) != null) {
4630            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4631            if (onlyExposedExplicitly) {
4632                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4633            }
4634            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4635            flags |= PackageManager.MATCH_INSTANT;
4636        } else {
4637            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4638            final boolean allowMatchInstant =
4639                    (wantInstantApps
4640                            && Intent.ACTION_VIEW.equals(intent.getAction())
4641                            && hasWebURI(intent))
4642                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4643            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4644                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4645            if (!allowMatchInstant) {
4646                flags &= ~PackageManager.MATCH_INSTANT;
4647            }
4648        }
4649        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4650    }
4651
4652    @Override
4653    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4654        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4655    }
4656
4657    /**
4658     * Important: The provided filterCallingUid is used exclusively to filter out activities
4659     * that can be seen based on user state. It's typically the original caller uid prior
4660     * to clearing. Because it can only be provided by trusted code, it's value can be
4661     * trusted and will be used as-is; unlike userId which will be validated by this method.
4662     */
4663    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4664            int filterCallingUid, int userId) {
4665        if (!sUserManager.exists(userId)) return null;
4666        flags = updateFlagsForComponent(flags, userId, component);
4667        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4668                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4669        synchronized (mPackages) {
4670            PackageParser.Activity a = mActivities.mActivities.get(component);
4671
4672            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4673            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4674                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4675                if (ps == null) return null;
4676                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4677                    return null;
4678                }
4679                return PackageParser.generateActivityInfo(
4680                        a, flags, ps.readUserState(userId), userId);
4681            }
4682            if (mResolveComponentName.equals(component)) {
4683                return PackageParser.generateActivityInfo(
4684                        mResolveActivity, flags, new PackageUserState(), userId);
4685            }
4686        }
4687        return null;
4688    }
4689
4690    @Override
4691    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4692            String resolvedType) {
4693        synchronized (mPackages) {
4694            if (component.equals(mResolveComponentName)) {
4695                // The resolver supports EVERYTHING!
4696                return true;
4697            }
4698            final int callingUid = Binder.getCallingUid();
4699            final int callingUserId = UserHandle.getUserId(callingUid);
4700            PackageParser.Activity a = mActivities.mActivities.get(component);
4701            if (a == null) {
4702                return false;
4703            }
4704            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4705            if (ps == null) {
4706                return false;
4707            }
4708            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4709                return false;
4710            }
4711            for (int i=0; i<a.intents.size(); i++) {
4712                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4713                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4714                    return true;
4715                }
4716            }
4717            return false;
4718        }
4719    }
4720
4721    @Override
4722    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4723        if (!sUserManager.exists(userId)) return null;
4724        final int callingUid = Binder.getCallingUid();
4725        flags = updateFlagsForComponent(flags, userId, component);
4726        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4727                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4728        synchronized (mPackages) {
4729            PackageParser.Activity a = mReceivers.mActivities.get(component);
4730            if (DEBUG_PACKAGE_INFO) Log.v(
4731                TAG, "getReceiverInfo " + component + ": " + a);
4732            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4733                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4734                if (ps == null) return null;
4735                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4736                    return null;
4737                }
4738                return PackageParser.generateActivityInfo(
4739                        a, flags, ps.readUserState(userId), userId);
4740            }
4741        }
4742        return null;
4743    }
4744
4745    @Override
4746    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4747            int flags, int userId) {
4748        if (!sUserManager.exists(userId)) return null;
4749        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4750        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4751            return null;
4752        }
4753
4754        flags = updateFlagsForPackage(flags, userId, null);
4755
4756        final boolean canSeeStaticLibraries =
4757                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4758                        == PERMISSION_GRANTED
4759                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4760                        == PERMISSION_GRANTED
4761                || canRequestPackageInstallsInternal(packageName,
4762                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4763                        false  /* throwIfPermNotDeclared*/)
4764                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4765                        == PERMISSION_GRANTED;
4766
4767        synchronized (mPackages) {
4768            List<SharedLibraryInfo> result = null;
4769
4770            final int libCount = mSharedLibraries.size();
4771            for (int i = 0; i < libCount; i++) {
4772                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4773                if (versionedLib == null) {
4774                    continue;
4775                }
4776
4777                final int versionCount = versionedLib.size();
4778                for (int j = 0; j < versionCount; j++) {
4779                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4780                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4781                        break;
4782                    }
4783                    final long identity = Binder.clearCallingIdentity();
4784                    try {
4785                        PackageInfo packageInfo = getPackageInfoVersioned(
4786                                libInfo.getDeclaringPackage(), flags
4787                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4788                        if (packageInfo == null) {
4789                            continue;
4790                        }
4791                    } finally {
4792                        Binder.restoreCallingIdentity(identity);
4793                    }
4794
4795                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4796                            libInfo.getVersion(), libInfo.getType(),
4797                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4798                            flags, userId));
4799
4800                    if (result == null) {
4801                        result = new ArrayList<>();
4802                    }
4803                    result.add(resLibInfo);
4804                }
4805            }
4806
4807            return result != null ? new ParceledListSlice<>(result) : null;
4808        }
4809    }
4810
4811    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4812            SharedLibraryInfo libInfo, int flags, int userId) {
4813        List<VersionedPackage> versionedPackages = null;
4814        final int packageCount = mSettings.mPackages.size();
4815        for (int i = 0; i < packageCount; i++) {
4816            PackageSetting ps = mSettings.mPackages.valueAt(i);
4817
4818            if (ps == null) {
4819                continue;
4820            }
4821
4822            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4823                continue;
4824            }
4825
4826            final String libName = libInfo.getName();
4827            if (libInfo.isStatic()) {
4828                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4829                if (libIdx < 0) {
4830                    continue;
4831                }
4832                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4833                    continue;
4834                }
4835                if (versionedPackages == null) {
4836                    versionedPackages = new ArrayList<>();
4837                }
4838                // If the dependent is a static shared lib, use the public package name
4839                String dependentPackageName = ps.name;
4840                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4841                    dependentPackageName = ps.pkg.manifestPackageName;
4842                }
4843                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4844            } else if (ps.pkg != null) {
4845                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4846                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4847                    if (versionedPackages == null) {
4848                        versionedPackages = new ArrayList<>();
4849                    }
4850                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4851                }
4852            }
4853        }
4854
4855        return versionedPackages;
4856    }
4857
4858    @Override
4859    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4860        if (!sUserManager.exists(userId)) return null;
4861        final int callingUid = Binder.getCallingUid();
4862        flags = updateFlagsForComponent(flags, userId, component);
4863        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4864                false /* requireFullPermission */, false /* checkShell */, "get service info");
4865        synchronized (mPackages) {
4866            PackageParser.Service s = mServices.mServices.get(component);
4867            if (DEBUG_PACKAGE_INFO) Log.v(
4868                TAG, "getServiceInfo " + component + ": " + s);
4869            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4870                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4871                if (ps == null) return null;
4872                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4873                    return null;
4874                }
4875                return PackageParser.generateServiceInfo(
4876                        s, flags, ps.readUserState(userId), userId);
4877            }
4878        }
4879        return null;
4880    }
4881
4882    @Override
4883    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4884        if (!sUserManager.exists(userId)) return null;
4885        final int callingUid = Binder.getCallingUid();
4886        flags = updateFlagsForComponent(flags, userId, component);
4887        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4888                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4889        synchronized (mPackages) {
4890            PackageParser.Provider p = mProviders.mProviders.get(component);
4891            if (DEBUG_PACKAGE_INFO) Log.v(
4892                TAG, "getProviderInfo " + component + ": " + p);
4893            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4894                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4895                if (ps == null) return null;
4896                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4897                    return null;
4898                }
4899                return PackageParser.generateProviderInfo(
4900                        p, flags, ps.readUserState(userId), userId);
4901            }
4902        }
4903        return null;
4904    }
4905
4906    @Override
4907    public String[] getSystemSharedLibraryNames() {
4908        // allow instant applications
4909        synchronized (mPackages) {
4910            Set<String> libs = null;
4911            final int libCount = mSharedLibraries.size();
4912            for (int i = 0; i < libCount; i++) {
4913                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4914                if (versionedLib == null) {
4915                    continue;
4916                }
4917                final int versionCount = versionedLib.size();
4918                for (int j = 0; j < versionCount; j++) {
4919                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4920                    if (!libEntry.info.isStatic()) {
4921                        if (libs == null) {
4922                            libs = new ArraySet<>();
4923                        }
4924                        libs.add(libEntry.info.getName());
4925                        break;
4926                    }
4927                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4928                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4929                            UserHandle.getUserId(Binder.getCallingUid()),
4930                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4931                        if (libs == null) {
4932                            libs = new ArraySet<>();
4933                        }
4934                        libs.add(libEntry.info.getName());
4935                        break;
4936                    }
4937                }
4938            }
4939
4940            if (libs != null) {
4941                String[] libsArray = new String[libs.size()];
4942                libs.toArray(libsArray);
4943                return libsArray;
4944            }
4945
4946            return null;
4947        }
4948    }
4949
4950    @Override
4951    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4952        // allow instant applications
4953        synchronized (mPackages) {
4954            return mServicesSystemSharedLibraryPackageName;
4955        }
4956    }
4957
4958    @Override
4959    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4960        // allow instant applications
4961        synchronized (mPackages) {
4962            return mSharedSystemSharedLibraryPackageName;
4963        }
4964    }
4965
4966    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4967        for (int i = userList.length - 1; i >= 0; --i) {
4968            final int userId = userList[i];
4969            // don't add instant app to the list of updates
4970            if (pkgSetting.getInstantApp(userId)) {
4971                continue;
4972            }
4973            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4974            if (changedPackages == null) {
4975                changedPackages = new SparseArray<>();
4976                mChangedPackages.put(userId, changedPackages);
4977            }
4978            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4979            if (sequenceNumbers == null) {
4980                sequenceNumbers = new HashMap<>();
4981                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4982            }
4983            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4984            if (sequenceNumber != null) {
4985                changedPackages.remove(sequenceNumber);
4986            }
4987            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4988            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4989        }
4990        mChangedPackagesSequenceNumber++;
4991    }
4992
4993    @Override
4994    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4995        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4996            return null;
4997        }
4998        synchronized (mPackages) {
4999            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5000                return null;
5001            }
5002            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5003            if (changedPackages == null) {
5004                return null;
5005            }
5006            final List<String> packageNames =
5007                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5008            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5009                final String packageName = changedPackages.get(i);
5010                if (packageName != null) {
5011                    packageNames.add(packageName);
5012                }
5013            }
5014            return packageNames.isEmpty()
5015                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5016        }
5017    }
5018
5019    @Override
5020    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5021        // allow instant applications
5022        ArrayList<FeatureInfo> res;
5023        synchronized (mAvailableFeatures) {
5024            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5025            res.addAll(mAvailableFeatures.values());
5026        }
5027        final FeatureInfo fi = new FeatureInfo();
5028        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5029                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5030        res.add(fi);
5031
5032        return new ParceledListSlice<>(res);
5033    }
5034
5035    @Override
5036    public boolean hasSystemFeature(String name, int version) {
5037        // allow instant applications
5038        synchronized (mAvailableFeatures) {
5039            final FeatureInfo feat = mAvailableFeatures.get(name);
5040            if (feat == null) {
5041                return false;
5042            } else {
5043                return feat.version >= version;
5044            }
5045        }
5046    }
5047
5048    @Override
5049    public int checkPermission(String permName, String pkgName, int userId) {
5050        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5051    }
5052
5053    @Override
5054    public int checkUidPermission(String permName, int uid) {
5055        return mPermissionManager.checkUidPermission(permName, uid, getCallingUid());
5056    }
5057
5058    @Override
5059    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5060        if (UserHandle.getCallingUserId() != userId) {
5061            mContext.enforceCallingPermission(
5062                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5063                    "isPermissionRevokedByPolicy for user " + userId);
5064        }
5065
5066        if (checkPermission(permission, packageName, userId)
5067                == PackageManager.PERMISSION_GRANTED) {
5068            return false;
5069        }
5070
5071        final int callingUid = Binder.getCallingUid();
5072        if (getInstantAppPackageName(callingUid) != null) {
5073            if (!isCallerSameApp(packageName, callingUid)) {
5074                return false;
5075            }
5076        } else {
5077            if (isInstantApp(packageName, userId)) {
5078                return false;
5079            }
5080        }
5081
5082        final long identity = Binder.clearCallingIdentity();
5083        try {
5084            final int flags = getPermissionFlags(permission, packageName, userId);
5085            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5086        } finally {
5087            Binder.restoreCallingIdentity(identity);
5088        }
5089    }
5090
5091    @Override
5092    public String getPermissionControllerPackageName() {
5093        synchronized (mPackages) {
5094            return mRequiredInstallerPackage;
5095        }
5096    }
5097
5098    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5099        return mPermissionManager.addDynamicPermission(
5100                info, async, getCallingUid(), new PermissionCallback() {
5101                    @Override
5102                    public void onPermissionChanged() {
5103                        if (!async) {
5104                            mSettings.writeLPr();
5105                        } else {
5106                            scheduleWriteSettingsLocked();
5107                        }
5108                    }
5109                });
5110    }
5111
5112    @Override
5113    public boolean addPermission(PermissionInfo info) {
5114        synchronized (mPackages) {
5115            return addDynamicPermission(info, false);
5116        }
5117    }
5118
5119    @Override
5120    public boolean addPermissionAsync(PermissionInfo info) {
5121        synchronized (mPackages) {
5122            return addDynamicPermission(info, true);
5123        }
5124    }
5125
5126    @Override
5127    public void removePermission(String permName) {
5128        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5129    }
5130
5131    @Override
5132    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5133        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5134                getCallingUid(), userId, mPermissionCallback);
5135    }
5136
5137    @Override
5138    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5139        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5140                getCallingUid(), userId, mPermissionCallback);
5141    }
5142
5143    @Override
5144    public void resetRuntimePermissions() {
5145        mContext.enforceCallingOrSelfPermission(
5146                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5147                "revokeRuntimePermission");
5148
5149        int callingUid = Binder.getCallingUid();
5150        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5151            mContext.enforceCallingOrSelfPermission(
5152                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5153                    "resetRuntimePermissions");
5154        }
5155
5156        synchronized (mPackages) {
5157            mPermissionManager.updateAllPermissions(
5158                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5159                    mPermissionCallback);
5160            for (int userId : UserManagerService.getInstance().getUserIds()) {
5161                final int packageCount = mPackages.size();
5162                for (int i = 0; i < packageCount; i++) {
5163                    PackageParser.Package pkg = mPackages.valueAt(i);
5164                    if (!(pkg.mExtras instanceof PackageSetting)) {
5165                        continue;
5166                    }
5167                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5168                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5169                }
5170            }
5171        }
5172    }
5173
5174    @Override
5175    public int getPermissionFlags(String permName, String packageName, int userId) {
5176        return mPermissionManager.getPermissionFlags(
5177                permName, packageName, getCallingUid(), userId);
5178    }
5179
5180    @Override
5181    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5182            int flagValues, int userId) {
5183        mPermissionManager.updatePermissionFlags(
5184                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5185                mPermissionCallback);
5186    }
5187
5188    /**
5189     * Update the permission flags for all packages and runtime permissions of a user in order
5190     * to allow device or profile owner to remove POLICY_FIXED.
5191     */
5192    @Override
5193    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5194        synchronized (mPackages) {
5195            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5196                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5197                    mPermissionCallback);
5198            if (changed) {
5199                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5200            }
5201        }
5202    }
5203
5204    @Override
5205    public boolean shouldShowRequestPermissionRationale(String permissionName,
5206            String packageName, int userId) {
5207        if (UserHandle.getCallingUserId() != userId) {
5208            mContext.enforceCallingPermission(
5209                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5210                    "canShowRequestPermissionRationale for user " + userId);
5211        }
5212
5213        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5214        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5215            return false;
5216        }
5217
5218        if (checkPermission(permissionName, packageName, userId)
5219                == PackageManager.PERMISSION_GRANTED) {
5220            return false;
5221        }
5222
5223        final int flags;
5224
5225        final long identity = Binder.clearCallingIdentity();
5226        try {
5227            flags = getPermissionFlags(permissionName,
5228                    packageName, userId);
5229        } finally {
5230            Binder.restoreCallingIdentity(identity);
5231        }
5232
5233        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5234                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5235                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5236
5237        if ((flags & fixedFlags) != 0) {
5238            return false;
5239        }
5240
5241        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5242    }
5243
5244    @Override
5245    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5246        mContext.enforceCallingOrSelfPermission(
5247                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5248                "addOnPermissionsChangeListener");
5249
5250        synchronized (mPackages) {
5251            mOnPermissionChangeListeners.addListenerLocked(listener);
5252        }
5253    }
5254
5255    @Override
5256    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5257        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5258            throw new SecurityException("Instant applications don't have access to this method");
5259        }
5260        synchronized (mPackages) {
5261            mOnPermissionChangeListeners.removeListenerLocked(listener);
5262        }
5263    }
5264
5265    @Override
5266    public boolean isProtectedBroadcast(String actionName) {
5267        // allow instant applications
5268        synchronized (mProtectedBroadcasts) {
5269            if (mProtectedBroadcasts.contains(actionName)) {
5270                return true;
5271            } else if (actionName != null) {
5272                // TODO: remove these terrible hacks
5273                if (actionName.startsWith("android.net.netmon.lingerExpired")
5274                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5275                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5276                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5277                    return true;
5278                }
5279            }
5280        }
5281        return false;
5282    }
5283
5284    @Override
5285    public int checkSignatures(String pkg1, String pkg2) {
5286        synchronized (mPackages) {
5287            final PackageParser.Package p1 = mPackages.get(pkg1);
5288            final PackageParser.Package p2 = mPackages.get(pkg2);
5289            if (p1 == null || p1.mExtras == null
5290                    || p2 == null || p2.mExtras == null) {
5291                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5292            }
5293            final int callingUid = Binder.getCallingUid();
5294            final int callingUserId = UserHandle.getUserId(callingUid);
5295            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5296            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5297            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5298                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5299                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5300            }
5301            return compareSignatures(p1.mSignatures, p2.mSignatures);
5302        }
5303    }
5304
5305    @Override
5306    public int checkUidSignatures(int uid1, int uid2) {
5307        final int callingUid = Binder.getCallingUid();
5308        final int callingUserId = UserHandle.getUserId(callingUid);
5309        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5310        // Map to base uids.
5311        uid1 = UserHandle.getAppId(uid1);
5312        uid2 = UserHandle.getAppId(uid2);
5313        // reader
5314        synchronized (mPackages) {
5315            Signature[] s1;
5316            Signature[] s2;
5317            Object obj = mSettings.getUserIdLPr(uid1);
5318            if (obj != null) {
5319                if (obj instanceof SharedUserSetting) {
5320                    if (isCallerInstantApp) {
5321                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5322                    }
5323                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5324                } else if (obj instanceof PackageSetting) {
5325                    final PackageSetting ps = (PackageSetting) obj;
5326                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5327                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5328                    }
5329                    s1 = ps.signatures.mSignatures;
5330                } else {
5331                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5332                }
5333            } else {
5334                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5335            }
5336            obj = mSettings.getUserIdLPr(uid2);
5337            if (obj != null) {
5338                if (obj instanceof SharedUserSetting) {
5339                    if (isCallerInstantApp) {
5340                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5341                    }
5342                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5343                } else if (obj instanceof PackageSetting) {
5344                    final PackageSetting ps = (PackageSetting) obj;
5345                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5346                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5347                    }
5348                    s2 = ps.signatures.mSignatures;
5349                } else {
5350                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5351                }
5352            } else {
5353                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5354            }
5355            return compareSignatures(s1, s2);
5356        }
5357    }
5358
5359    /**
5360     * This method should typically only be used when granting or revoking
5361     * permissions, since the app may immediately restart after this call.
5362     * <p>
5363     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5364     * guard your work against the app being relaunched.
5365     */
5366    private void killUid(int appId, int userId, String reason) {
5367        final long identity = Binder.clearCallingIdentity();
5368        try {
5369            IActivityManager am = ActivityManager.getService();
5370            if (am != null) {
5371                try {
5372                    am.killUid(appId, userId, reason);
5373                } catch (RemoteException e) {
5374                    /* ignore - same process */
5375                }
5376            }
5377        } finally {
5378            Binder.restoreCallingIdentity(identity);
5379        }
5380    }
5381
5382    /**
5383     * If the database version for this type of package (internal storage or
5384     * external storage) is less than the version where package signatures
5385     * were updated, return true.
5386     */
5387    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5388        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5389        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5390    }
5391
5392    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5393        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5394        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5395    }
5396
5397    @Override
5398    public List<String> getAllPackages() {
5399        final int callingUid = Binder.getCallingUid();
5400        final int callingUserId = UserHandle.getUserId(callingUid);
5401        synchronized (mPackages) {
5402            if (canViewInstantApps(callingUid, callingUserId)) {
5403                return new ArrayList<String>(mPackages.keySet());
5404            }
5405            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5406            final List<String> result = new ArrayList<>();
5407            if (instantAppPkgName != null) {
5408                // caller is an instant application; filter unexposed applications
5409                for (PackageParser.Package pkg : mPackages.values()) {
5410                    if (!pkg.visibleToInstantApps) {
5411                        continue;
5412                    }
5413                    result.add(pkg.packageName);
5414                }
5415            } else {
5416                // caller is a normal application; filter instant applications
5417                for (PackageParser.Package pkg : mPackages.values()) {
5418                    final PackageSetting ps =
5419                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5420                    if (ps != null
5421                            && ps.getInstantApp(callingUserId)
5422                            && !mInstantAppRegistry.isInstantAccessGranted(
5423                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5424                        continue;
5425                    }
5426                    result.add(pkg.packageName);
5427                }
5428            }
5429            return result;
5430        }
5431    }
5432
5433    @Override
5434    public String[] getPackagesForUid(int uid) {
5435        final int callingUid = Binder.getCallingUid();
5436        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5437        final int userId = UserHandle.getUserId(uid);
5438        uid = UserHandle.getAppId(uid);
5439        // reader
5440        synchronized (mPackages) {
5441            Object obj = mSettings.getUserIdLPr(uid);
5442            if (obj instanceof SharedUserSetting) {
5443                if (isCallerInstantApp) {
5444                    return null;
5445                }
5446                final SharedUserSetting sus = (SharedUserSetting) obj;
5447                final int N = sus.packages.size();
5448                String[] res = new String[N];
5449                final Iterator<PackageSetting> it = sus.packages.iterator();
5450                int i = 0;
5451                while (it.hasNext()) {
5452                    PackageSetting ps = it.next();
5453                    if (ps.getInstalled(userId)) {
5454                        res[i++] = ps.name;
5455                    } else {
5456                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5457                    }
5458                }
5459                return res;
5460            } else if (obj instanceof PackageSetting) {
5461                final PackageSetting ps = (PackageSetting) obj;
5462                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5463                    return new String[]{ps.name};
5464                }
5465            }
5466        }
5467        return null;
5468    }
5469
5470    @Override
5471    public String getNameForUid(int uid) {
5472        final int callingUid = Binder.getCallingUid();
5473        if (getInstantAppPackageName(callingUid) != null) {
5474            return null;
5475        }
5476        synchronized (mPackages) {
5477            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5478            if (obj instanceof SharedUserSetting) {
5479                final SharedUserSetting sus = (SharedUserSetting) obj;
5480                return sus.name + ":" + sus.userId;
5481            } else if (obj instanceof PackageSetting) {
5482                final PackageSetting ps = (PackageSetting) obj;
5483                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5484                    return null;
5485                }
5486                return ps.name;
5487            }
5488            return null;
5489        }
5490    }
5491
5492    @Override
5493    public String[] getNamesForUids(int[] uids) {
5494        if (uids == null || uids.length == 0) {
5495            return null;
5496        }
5497        final int callingUid = Binder.getCallingUid();
5498        if (getInstantAppPackageName(callingUid) != null) {
5499            return null;
5500        }
5501        final String[] names = new String[uids.length];
5502        synchronized (mPackages) {
5503            for (int i = uids.length - 1; i >= 0; i--) {
5504                final int uid = uids[i];
5505                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5506                if (obj instanceof SharedUserSetting) {
5507                    final SharedUserSetting sus = (SharedUserSetting) obj;
5508                    names[i] = "shared:" + sus.name;
5509                } else if (obj instanceof PackageSetting) {
5510                    final PackageSetting ps = (PackageSetting) obj;
5511                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5512                        names[i] = null;
5513                    } else {
5514                        names[i] = ps.name;
5515                    }
5516                } else {
5517                    names[i] = null;
5518                }
5519            }
5520        }
5521        return names;
5522    }
5523
5524    @Override
5525    public int getUidForSharedUser(String sharedUserName) {
5526        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5527            return -1;
5528        }
5529        if (sharedUserName == null) {
5530            return -1;
5531        }
5532        // reader
5533        synchronized (mPackages) {
5534            SharedUserSetting suid;
5535            try {
5536                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5537                if (suid != null) {
5538                    return suid.userId;
5539                }
5540            } catch (PackageManagerException ignore) {
5541                // can't happen, but, still need to catch it
5542            }
5543            return -1;
5544        }
5545    }
5546
5547    @Override
5548    public int getFlagsForUid(int uid) {
5549        final int callingUid = Binder.getCallingUid();
5550        if (getInstantAppPackageName(callingUid) != null) {
5551            return 0;
5552        }
5553        synchronized (mPackages) {
5554            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5555            if (obj instanceof SharedUserSetting) {
5556                final SharedUserSetting sus = (SharedUserSetting) obj;
5557                return sus.pkgFlags;
5558            } else if (obj instanceof PackageSetting) {
5559                final PackageSetting ps = (PackageSetting) obj;
5560                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5561                    return 0;
5562                }
5563                return ps.pkgFlags;
5564            }
5565        }
5566        return 0;
5567    }
5568
5569    @Override
5570    public int getPrivateFlagsForUid(int uid) {
5571        final int callingUid = Binder.getCallingUid();
5572        if (getInstantAppPackageName(callingUid) != null) {
5573            return 0;
5574        }
5575        synchronized (mPackages) {
5576            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5577            if (obj instanceof SharedUserSetting) {
5578                final SharedUserSetting sus = (SharedUserSetting) obj;
5579                return sus.pkgPrivateFlags;
5580            } else if (obj instanceof PackageSetting) {
5581                final PackageSetting ps = (PackageSetting) obj;
5582                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5583                    return 0;
5584                }
5585                return ps.pkgPrivateFlags;
5586            }
5587        }
5588        return 0;
5589    }
5590
5591    @Override
5592    public boolean isUidPrivileged(int uid) {
5593        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5594            return false;
5595        }
5596        uid = UserHandle.getAppId(uid);
5597        // reader
5598        synchronized (mPackages) {
5599            Object obj = mSettings.getUserIdLPr(uid);
5600            if (obj instanceof SharedUserSetting) {
5601                final SharedUserSetting sus = (SharedUserSetting) obj;
5602                final Iterator<PackageSetting> it = sus.packages.iterator();
5603                while (it.hasNext()) {
5604                    if (it.next().isPrivileged()) {
5605                        return true;
5606                    }
5607                }
5608            } else if (obj instanceof PackageSetting) {
5609                final PackageSetting ps = (PackageSetting) obj;
5610                return ps.isPrivileged();
5611            }
5612        }
5613        return false;
5614    }
5615
5616    @Override
5617    public String[] getAppOpPermissionPackages(String permName) {
5618        return mPermissionManager.getAppOpPermissionPackages(permName);
5619    }
5620
5621    @Override
5622    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5623            int flags, int userId) {
5624        return resolveIntentInternal(
5625                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5626    }
5627
5628    /**
5629     * Normally instant apps can only be resolved when they're visible to the caller.
5630     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5631     * since we need to allow the system to start any installed application.
5632     */
5633    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5634            int flags, int userId, boolean resolveForStart) {
5635        try {
5636            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5637
5638            if (!sUserManager.exists(userId)) return null;
5639            final int callingUid = Binder.getCallingUid();
5640            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5641            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5642                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5643
5644            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5645            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5646                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5647            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5648
5649            final ResolveInfo bestChoice =
5650                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5651            return bestChoice;
5652        } finally {
5653            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5654        }
5655    }
5656
5657    @Override
5658    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5659        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5660            throw new SecurityException(
5661                    "findPersistentPreferredActivity can only be run by the system");
5662        }
5663        if (!sUserManager.exists(userId)) {
5664            return null;
5665        }
5666        final int callingUid = Binder.getCallingUid();
5667        intent = updateIntentForResolve(intent);
5668        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5669        final int flags = updateFlagsForResolve(
5670                0, userId, intent, callingUid, false /*includeInstantApps*/);
5671        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5672                userId);
5673        synchronized (mPackages) {
5674            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5675                    userId);
5676        }
5677    }
5678
5679    @Override
5680    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5681            IntentFilter filter, int match, ComponentName activity) {
5682        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5683            return;
5684        }
5685        final int userId = UserHandle.getCallingUserId();
5686        if (DEBUG_PREFERRED) {
5687            Log.v(TAG, "setLastChosenActivity intent=" + intent
5688                + " resolvedType=" + resolvedType
5689                + " flags=" + flags
5690                + " filter=" + filter
5691                + " match=" + match
5692                + " activity=" + activity);
5693            filter.dump(new PrintStreamPrinter(System.out), "    ");
5694        }
5695        intent.setComponent(null);
5696        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5697                userId);
5698        // Find any earlier preferred or last chosen entries and nuke them
5699        findPreferredActivity(intent, resolvedType,
5700                flags, query, 0, false, true, false, userId);
5701        // Add the new activity as the last chosen for this filter
5702        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5703                "Setting last chosen");
5704    }
5705
5706    @Override
5707    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5708        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5709            return null;
5710        }
5711        final int userId = UserHandle.getCallingUserId();
5712        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5713        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5714                userId);
5715        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5716                false, false, false, userId);
5717    }
5718
5719    /**
5720     * Returns whether or not instant apps have been disabled remotely.
5721     */
5722    private boolean isEphemeralDisabled() {
5723        return mEphemeralAppsDisabled;
5724    }
5725
5726    private boolean isInstantAppAllowed(
5727            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5728            boolean skipPackageCheck) {
5729        if (mInstantAppResolverConnection == null) {
5730            return false;
5731        }
5732        if (mInstantAppInstallerActivity == null) {
5733            return false;
5734        }
5735        if (intent.getComponent() != null) {
5736            return false;
5737        }
5738        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5739            return false;
5740        }
5741        if (!skipPackageCheck && intent.getPackage() != null) {
5742            return false;
5743        }
5744        final boolean isWebUri = hasWebURI(intent);
5745        if (!isWebUri || intent.getData().getHost() == null) {
5746            return false;
5747        }
5748        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5749        // Or if there's already an ephemeral app installed that handles the action
5750        synchronized (mPackages) {
5751            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5752            for (int n = 0; n < count; n++) {
5753                final ResolveInfo info = resolvedActivities.get(n);
5754                final String packageName = info.activityInfo.packageName;
5755                final PackageSetting ps = mSettings.mPackages.get(packageName);
5756                if (ps != null) {
5757                    // only check domain verification status if the app is not a browser
5758                    if (!info.handleAllWebDataURI) {
5759                        // Try to get the status from User settings first
5760                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5761                        final int status = (int) (packedStatus >> 32);
5762                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5763                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5764                            if (DEBUG_EPHEMERAL) {
5765                                Slog.v(TAG, "DENY instant app;"
5766                                    + " pkg: " + packageName + ", status: " + status);
5767                            }
5768                            return false;
5769                        }
5770                    }
5771                    if (ps.getInstantApp(userId)) {
5772                        if (DEBUG_EPHEMERAL) {
5773                            Slog.v(TAG, "DENY instant app installed;"
5774                                    + " pkg: " + packageName);
5775                        }
5776                        return false;
5777                    }
5778                }
5779            }
5780        }
5781        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5782        return true;
5783    }
5784
5785    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5786            Intent origIntent, String resolvedType, String callingPackage,
5787            Bundle verificationBundle, int userId) {
5788        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5789                new InstantAppRequest(responseObj, origIntent, resolvedType,
5790                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
5791        mHandler.sendMessage(msg);
5792    }
5793
5794    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5795            int flags, List<ResolveInfo> query, int userId) {
5796        if (query != null) {
5797            final int N = query.size();
5798            if (N == 1) {
5799                return query.get(0);
5800            } else if (N > 1) {
5801                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5802                // If there is more than one activity with the same priority,
5803                // then let the user decide between them.
5804                ResolveInfo r0 = query.get(0);
5805                ResolveInfo r1 = query.get(1);
5806                if (DEBUG_INTENT_MATCHING || debug) {
5807                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5808                            + r1.activityInfo.name + "=" + r1.priority);
5809                }
5810                // If the first activity has a higher priority, or a different
5811                // default, then it is always desirable to pick it.
5812                if (r0.priority != r1.priority
5813                        || r0.preferredOrder != r1.preferredOrder
5814                        || r0.isDefault != r1.isDefault) {
5815                    return query.get(0);
5816                }
5817                // If we have saved a preference for a preferred activity for
5818                // this Intent, use that.
5819                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5820                        flags, query, r0.priority, true, false, debug, userId);
5821                if (ri != null) {
5822                    return ri;
5823                }
5824                // If we have an ephemeral app, use it
5825                for (int i = 0; i < N; i++) {
5826                    ri = query.get(i);
5827                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5828                        final String packageName = ri.activityInfo.packageName;
5829                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5830                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5831                        final int status = (int)(packedStatus >> 32);
5832                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5833                            return ri;
5834                        }
5835                    }
5836                }
5837                ri = new ResolveInfo(mResolveInfo);
5838                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5839                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5840                // If all of the options come from the same package, show the application's
5841                // label and icon instead of the generic resolver's.
5842                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5843                // and then throw away the ResolveInfo itself, meaning that the caller loses
5844                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5845                // a fallback for this case; we only set the target package's resources on
5846                // the ResolveInfo, not the ActivityInfo.
5847                final String intentPackage = intent.getPackage();
5848                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5849                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5850                    ri.resolvePackageName = intentPackage;
5851                    if (userNeedsBadging(userId)) {
5852                        ri.noResourceId = true;
5853                    } else {
5854                        ri.icon = appi.icon;
5855                    }
5856                    ri.iconResourceId = appi.icon;
5857                    ri.labelRes = appi.labelRes;
5858                }
5859                ri.activityInfo.applicationInfo = new ApplicationInfo(
5860                        ri.activityInfo.applicationInfo);
5861                if (userId != 0) {
5862                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5863                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5864                }
5865                // Make sure that the resolver is displayable in car mode
5866                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5867                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5868                return ri;
5869            }
5870        }
5871        return null;
5872    }
5873
5874    /**
5875     * Return true if the given list is not empty and all of its contents have
5876     * an activityInfo with the given package name.
5877     */
5878    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5879        if (ArrayUtils.isEmpty(list)) {
5880            return false;
5881        }
5882        for (int i = 0, N = list.size(); i < N; i++) {
5883            final ResolveInfo ri = list.get(i);
5884            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5885            if (ai == null || !packageName.equals(ai.packageName)) {
5886                return false;
5887            }
5888        }
5889        return true;
5890    }
5891
5892    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5893            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5894        final int N = query.size();
5895        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5896                .get(userId);
5897        // Get the list of persistent preferred activities that handle the intent
5898        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5899        List<PersistentPreferredActivity> pprefs = ppir != null
5900                ? ppir.queryIntent(intent, resolvedType,
5901                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5902                        userId)
5903                : null;
5904        if (pprefs != null && pprefs.size() > 0) {
5905            final int M = pprefs.size();
5906            for (int i=0; i<M; i++) {
5907                final PersistentPreferredActivity ppa = pprefs.get(i);
5908                if (DEBUG_PREFERRED || debug) {
5909                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5910                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5911                            + "\n  component=" + ppa.mComponent);
5912                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5913                }
5914                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5915                        flags | MATCH_DISABLED_COMPONENTS, userId);
5916                if (DEBUG_PREFERRED || debug) {
5917                    Slog.v(TAG, "Found persistent preferred activity:");
5918                    if (ai != null) {
5919                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5920                    } else {
5921                        Slog.v(TAG, "  null");
5922                    }
5923                }
5924                if (ai == null) {
5925                    // This previously registered persistent preferred activity
5926                    // component is no longer known. Ignore it and do NOT remove it.
5927                    continue;
5928                }
5929                for (int j=0; j<N; j++) {
5930                    final ResolveInfo ri = query.get(j);
5931                    if (!ri.activityInfo.applicationInfo.packageName
5932                            .equals(ai.applicationInfo.packageName)) {
5933                        continue;
5934                    }
5935                    if (!ri.activityInfo.name.equals(ai.name)) {
5936                        continue;
5937                    }
5938                    //  Found a persistent preference that can handle the intent.
5939                    if (DEBUG_PREFERRED || debug) {
5940                        Slog.v(TAG, "Returning persistent preferred activity: " +
5941                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5942                    }
5943                    return ri;
5944                }
5945            }
5946        }
5947        return null;
5948    }
5949
5950    // TODO: handle preferred activities missing while user has amnesia
5951    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5952            List<ResolveInfo> query, int priority, boolean always,
5953            boolean removeMatches, boolean debug, int userId) {
5954        if (!sUserManager.exists(userId)) return null;
5955        final int callingUid = Binder.getCallingUid();
5956        flags = updateFlagsForResolve(
5957                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5958        intent = updateIntentForResolve(intent);
5959        // writer
5960        synchronized (mPackages) {
5961            // Try to find a matching persistent preferred activity.
5962            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5963                    debug, userId);
5964
5965            // If a persistent preferred activity matched, use it.
5966            if (pri != null) {
5967                return pri;
5968            }
5969
5970            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5971            // Get the list of preferred activities that handle the intent
5972            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5973            List<PreferredActivity> prefs = pir != null
5974                    ? pir.queryIntent(intent, resolvedType,
5975                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5976                            userId)
5977                    : null;
5978            if (prefs != null && prefs.size() > 0) {
5979                boolean changed = false;
5980                try {
5981                    // First figure out how good the original match set is.
5982                    // We will only allow preferred activities that came
5983                    // from the same match quality.
5984                    int match = 0;
5985
5986                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5987
5988                    final int N = query.size();
5989                    for (int j=0; j<N; j++) {
5990                        final ResolveInfo ri = query.get(j);
5991                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5992                                + ": 0x" + Integer.toHexString(match));
5993                        if (ri.match > match) {
5994                            match = ri.match;
5995                        }
5996                    }
5997
5998                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5999                            + Integer.toHexString(match));
6000
6001                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6002                    final int M = prefs.size();
6003                    for (int i=0; i<M; i++) {
6004                        final PreferredActivity pa = prefs.get(i);
6005                        if (DEBUG_PREFERRED || debug) {
6006                            Slog.v(TAG, "Checking PreferredActivity ds="
6007                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6008                                    + "\n  component=" + pa.mPref.mComponent);
6009                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6010                        }
6011                        if (pa.mPref.mMatch != match) {
6012                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6013                                    + Integer.toHexString(pa.mPref.mMatch));
6014                            continue;
6015                        }
6016                        // If it's not an "always" type preferred activity and that's what we're
6017                        // looking for, skip it.
6018                        if (always && !pa.mPref.mAlways) {
6019                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6020                            continue;
6021                        }
6022                        final ActivityInfo ai = getActivityInfo(
6023                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6024                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6025                                userId);
6026                        if (DEBUG_PREFERRED || debug) {
6027                            Slog.v(TAG, "Found preferred activity:");
6028                            if (ai != null) {
6029                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6030                            } else {
6031                                Slog.v(TAG, "  null");
6032                            }
6033                        }
6034                        if (ai == null) {
6035                            // This previously registered preferred activity
6036                            // component is no longer known.  Most likely an update
6037                            // to the app was installed and in the new version this
6038                            // component no longer exists.  Clean it up by removing
6039                            // it from the preferred activities list, and skip it.
6040                            Slog.w(TAG, "Removing dangling preferred activity: "
6041                                    + pa.mPref.mComponent);
6042                            pir.removeFilter(pa);
6043                            changed = true;
6044                            continue;
6045                        }
6046                        for (int j=0; j<N; j++) {
6047                            final ResolveInfo ri = query.get(j);
6048                            if (!ri.activityInfo.applicationInfo.packageName
6049                                    .equals(ai.applicationInfo.packageName)) {
6050                                continue;
6051                            }
6052                            if (!ri.activityInfo.name.equals(ai.name)) {
6053                                continue;
6054                            }
6055
6056                            if (removeMatches) {
6057                                pir.removeFilter(pa);
6058                                changed = true;
6059                                if (DEBUG_PREFERRED) {
6060                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6061                                }
6062                                break;
6063                            }
6064
6065                            // Okay we found a previously set preferred or last chosen app.
6066                            // If the result set is different from when this
6067                            // was created, and is not a subset of the preferred set, we need to
6068                            // clear it and re-ask the user their preference, if we're looking for
6069                            // an "always" type entry.
6070                            if (always && !pa.mPref.sameSet(query)) {
6071                                if (pa.mPref.isSuperset(query)) {
6072                                    // some components of the set are no longer present in
6073                                    // the query, but the preferred activity can still be reused
6074                                    if (DEBUG_PREFERRED) {
6075                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6076                                                + " still valid as only non-preferred components"
6077                                                + " were removed for " + intent + " type "
6078                                                + resolvedType);
6079                                    }
6080                                    // remove obsolete components and re-add the up-to-date filter
6081                                    PreferredActivity freshPa = new PreferredActivity(pa,
6082                                            pa.mPref.mMatch,
6083                                            pa.mPref.discardObsoleteComponents(query),
6084                                            pa.mPref.mComponent,
6085                                            pa.mPref.mAlways);
6086                                    pir.removeFilter(pa);
6087                                    pir.addFilter(freshPa);
6088                                    changed = true;
6089                                } else {
6090                                    Slog.i(TAG,
6091                                            "Result set changed, dropping preferred activity for "
6092                                                    + intent + " type " + resolvedType);
6093                                    if (DEBUG_PREFERRED) {
6094                                        Slog.v(TAG, "Removing preferred activity since set changed "
6095                                                + pa.mPref.mComponent);
6096                                    }
6097                                    pir.removeFilter(pa);
6098                                    // Re-add the filter as a "last chosen" entry (!always)
6099                                    PreferredActivity lastChosen = new PreferredActivity(
6100                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6101                                    pir.addFilter(lastChosen);
6102                                    changed = true;
6103                                    return null;
6104                                }
6105                            }
6106
6107                            // Yay! Either the set matched or we're looking for the last chosen
6108                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6109                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6110                            return ri;
6111                        }
6112                    }
6113                } finally {
6114                    if (changed) {
6115                        if (DEBUG_PREFERRED) {
6116                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6117                        }
6118                        scheduleWritePackageRestrictionsLocked(userId);
6119                    }
6120                }
6121            }
6122        }
6123        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6124        return null;
6125    }
6126
6127    /*
6128     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6129     */
6130    @Override
6131    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6132            int targetUserId) {
6133        mContext.enforceCallingOrSelfPermission(
6134                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6135        List<CrossProfileIntentFilter> matches =
6136                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6137        if (matches != null) {
6138            int size = matches.size();
6139            for (int i = 0; i < size; i++) {
6140                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6141            }
6142        }
6143        if (hasWebURI(intent)) {
6144            // cross-profile app linking works only towards the parent.
6145            final int callingUid = Binder.getCallingUid();
6146            final UserInfo parent = getProfileParent(sourceUserId);
6147            synchronized(mPackages) {
6148                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6149                        false /*includeInstantApps*/);
6150                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6151                        intent, resolvedType, flags, sourceUserId, parent.id);
6152                return xpDomainInfo != null;
6153            }
6154        }
6155        return false;
6156    }
6157
6158    private UserInfo getProfileParent(int userId) {
6159        final long identity = Binder.clearCallingIdentity();
6160        try {
6161            return sUserManager.getProfileParent(userId);
6162        } finally {
6163            Binder.restoreCallingIdentity(identity);
6164        }
6165    }
6166
6167    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6168            String resolvedType, int userId) {
6169        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6170        if (resolver != null) {
6171            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6172        }
6173        return null;
6174    }
6175
6176    @Override
6177    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6178            String resolvedType, int flags, int userId) {
6179        try {
6180            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6181
6182            return new ParceledListSlice<>(
6183                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6184        } finally {
6185            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6186        }
6187    }
6188
6189    /**
6190     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6191     * instant, returns {@code null}.
6192     */
6193    private String getInstantAppPackageName(int callingUid) {
6194        synchronized (mPackages) {
6195            // If the caller is an isolated app use the owner's uid for the lookup.
6196            if (Process.isIsolated(callingUid)) {
6197                callingUid = mIsolatedOwners.get(callingUid);
6198            }
6199            final int appId = UserHandle.getAppId(callingUid);
6200            final Object obj = mSettings.getUserIdLPr(appId);
6201            if (obj instanceof PackageSetting) {
6202                final PackageSetting ps = (PackageSetting) obj;
6203                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6204                return isInstantApp ? ps.pkg.packageName : null;
6205            }
6206        }
6207        return null;
6208    }
6209
6210    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6211            String resolvedType, int flags, int userId) {
6212        return queryIntentActivitiesInternal(
6213                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6214                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6215    }
6216
6217    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6218            String resolvedType, int flags, int filterCallingUid, int userId,
6219            boolean resolveForStart, boolean allowDynamicSplits) {
6220        if (!sUserManager.exists(userId)) return Collections.emptyList();
6221        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6222        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6223                false /* requireFullPermission */, false /* checkShell */,
6224                "query intent activities");
6225        final String pkgName = intent.getPackage();
6226        ComponentName comp = intent.getComponent();
6227        if (comp == null) {
6228            if (intent.getSelector() != null) {
6229                intent = intent.getSelector();
6230                comp = intent.getComponent();
6231            }
6232        }
6233
6234        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6235                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6236        if (comp != null) {
6237            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6238            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6239            if (ai != null) {
6240                // When specifying an explicit component, we prevent the activity from being
6241                // used when either 1) the calling package is normal and the activity is within
6242                // an ephemeral application or 2) the calling package is ephemeral and the
6243                // activity is not visible to ephemeral applications.
6244                final boolean matchInstantApp =
6245                        (flags & PackageManager.MATCH_INSTANT) != 0;
6246                final boolean matchVisibleToInstantAppOnly =
6247                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6248                final boolean matchExplicitlyVisibleOnly =
6249                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6250                final boolean isCallerInstantApp =
6251                        instantAppPkgName != null;
6252                final boolean isTargetSameInstantApp =
6253                        comp.getPackageName().equals(instantAppPkgName);
6254                final boolean isTargetInstantApp =
6255                        (ai.applicationInfo.privateFlags
6256                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6257                final boolean isTargetVisibleToInstantApp =
6258                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6259                final boolean isTargetExplicitlyVisibleToInstantApp =
6260                        isTargetVisibleToInstantApp
6261                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6262                final boolean isTargetHiddenFromInstantApp =
6263                        !isTargetVisibleToInstantApp
6264                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6265                final boolean blockResolution =
6266                        !isTargetSameInstantApp
6267                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6268                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6269                                        && isTargetHiddenFromInstantApp));
6270                if (!blockResolution) {
6271                    final ResolveInfo ri = new ResolveInfo();
6272                    ri.activityInfo = ai;
6273                    list.add(ri);
6274                }
6275            }
6276            return applyPostResolutionFilter(
6277                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6278        }
6279
6280        // reader
6281        boolean sortResult = false;
6282        boolean addEphemeral = false;
6283        List<ResolveInfo> result;
6284        final boolean ephemeralDisabled = isEphemeralDisabled();
6285        synchronized (mPackages) {
6286            if (pkgName == null) {
6287                List<CrossProfileIntentFilter> matchingFilters =
6288                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6289                // Check for results that need to skip the current profile.
6290                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6291                        resolvedType, flags, userId);
6292                if (xpResolveInfo != null) {
6293                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6294                    xpResult.add(xpResolveInfo);
6295                    return applyPostResolutionFilter(
6296                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6297                            allowDynamicSplits, filterCallingUid, userId);
6298                }
6299
6300                // Check for results in the current profile.
6301                result = filterIfNotSystemUser(mActivities.queryIntent(
6302                        intent, resolvedType, flags, userId), userId);
6303                addEphemeral = !ephemeralDisabled
6304                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6305                // Check for cross profile results.
6306                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6307                xpResolveInfo = queryCrossProfileIntents(
6308                        matchingFilters, intent, resolvedType, flags, userId,
6309                        hasNonNegativePriorityResult);
6310                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6311                    boolean isVisibleToUser = filterIfNotSystemUser(
6312                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6313                    if (isVisibleToUser) {
6314                        result.add(xpResolveInfo);
6315                        sortResult = true;
6316                    }
6317                }
6318                if (hasWebURI(intent)) {
6319                    CrossProfileDomainInfo xpDomainInfo = null;
6320                    final UserInfo parent = getProfileParent(userId);
6321                    if (parent != null) {
6322                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6323                                flags, userId, parent.id);
6324                    }
6325                    if (xpDomainInfo != null) {
6326                        if (xpResolveInfo != null) {
6327                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6328                            // in the result.
6329                            result.remove(xpResolveInfo);
6330                        }
6331                        if (result.size() == 0 && !addEphemeral) {
6332                            // No result in current profile, but found candidate in parent user.
6333                            // And we are not going to add emphemeral app, so we can return the
6334                            // result straight away.
6335                            result.add(xpDomainInfo.resolveInfo);
6336                            return applyPostResolutionFilter(result, instantAppPkgName,
6337                                    allowDynamicSplits, filterCallingUid, userId);
6338                        }
6339                    } else if (result.size() <= 1 && !addEphemeral) {
6340                        // No result in parent user and <= 1 result in current profile, and we
6341                        // are not going to add emphemeral app, so we can return the result without
6342                        // further processing.
6343                        return applyPostResolutionFilter(result, instantAppPkgName,
6344                                allowDynamicSplits, filterCallingUid, userId);
6345                    }
6346                    // We have more than one candidate (combining results from current and parent
6347                    // profile), so we need filtering and sorting.
6348                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6349                            intent, flags, result, xpDomainInfo, userId);
6350                    sortResult = true;
6351                }
6352            } else {
6353                final PackageParser.Package pkg = mPackages.get(pkgName);
6354                result = null;
6355                if (pkg != null) {
6356                    result = filterIfNotSystemUser(
6357                            mActivities.queryIntentForPackage(
6358                                    intent, resolvedType, flags, pkg.activities, userId),
6359                            userId);
6360                }
6361                if (result == null || result.size() == 0) {
6362                    // the caller wants to resolve for a particular package; however, there
6363                    // were no installed results, so, try to find an ephemeral result
6364                    addEphemeral = !ephemeralDisabled
6365                            && isInstantAppAllowed(
6366                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6367                    if (result == null) {
6368                        result = new ArrayList<>();
6369                    }
6370                }
6371            }
6372        }
6373        if (addEphemeral) {
6374            result = maybeAddInstantAppInstaller(
6375                    result, intent, resolvedType, flags, userId, resolveForStart);
6376        }
6377        if (sortResult) {
6378            Collections.sort(result, mResolvePrioritySorter);
6379        }
6380        return applyPostResolutionFilter(
6381                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6382    }
6383
6384    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6385            String resolvedType, int flags, int userId, boolean resolveForStart) {
6386        // first, check to see if we've got an instant app already installed
6387        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6388        ResolveInfo localInstantApp = null;
6389        boolean blockResolution = false;
6390        if (!alreadyResolvedLocally) {
6391            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6392                    flags
6393                        | PackageManager.GET_RESOLVED_FILTER
6394                        | PackageManager.MATCH_INSTANT
6395                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6396                    userId);
6397            for (int i = instantApps.size() - 1; i >= 0; --i) {
6398                final ResolveInfo info = instantApps.get(i);
6399                final String packageName = info.activityInfo.packageName;
6400                final PackageSetting ps = mSettings.mPackages.get(packageName);
6401                if (ps.getInstantApp(userId)) {
6402                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6403                    final int status = (int)(packedStatus >> 32);
6404                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6405                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6406                        // there's a local instant application installed, but, the user has
6407                        // chosen to never use it; skip resolution and don't acknowledge
6408                        // an instant application is even available
6409                        if (DEBUG_EPHEMERAL) {
6410                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6411                        }
6412                        blockResolution = true;
6413                        break;
6414                    } else {
6415                        // we have a locally installed instant application; skip resolution
6416                        // but acknowledge there's an instant application available
6417                        if (DEBUG_EPHEMERAL) {
6418                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6419                        }
6420                        localInstantApp = info;
6421                        break;
6422                    }
6423                }
6424            }
6425        }
6426        // no app installed, let's see if one's available
6427        AuxiliaryResolveInfo auxiliaryResponse = null;
6428        if (!blockResolution) {
6429            if (localInstantApp == null) {
6430                // we don't have an instant app locally, resolve externally
6431                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6432                final InstantAppRequest requestObject = new InstantAppRequest(
6433                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6434                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6435                        resolveForStart);
6436                auxiliaryResponse =
6437                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6438                                mContext, mInstantAppResolverConnection, requestObject);
6439                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6440            } else {
6441                // we have an instant application locally, but, we can't admit that since
6442                // callers shouldn't be able to determine prior browsing. create a dummy
6443                // auxiliary response so the downstream code behaves as if there's an
6444                // instant application available externally. when it comes time to start
6445                // the instant application, we'll do the right thing.
6446                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6447                auxiliaryResponse = new AuxiliaryResolveInfo(
6448                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6449                        ai.versionCode, null /*failureIntent*/);
6450            }
6451        }
6452        if (auxiliaryResponse != null) {
6453            if (DEBUG_EPHEMERAL) {
6454                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6455            }
6456            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6457            final PackageSetting ps =
6458                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6459            if (ps != null) {
6460                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6461                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6462                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6463                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6464                // make sure this resolver is the default
6465                ephemeralInstaller.isDefault = true;
6466                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6467                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6468                // add a non-generic filter
6469                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6470                ephemeralInstaller.filter.addDataPath(
6471                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6472                ephemeralInstaller.isInstantAppAvailable = true;
6473                result.add(ephemeralInstaller);
6474            }
6475        }
6476        return result;
6477    }
6478
6479    private static class CrossProfileDomainInfo {
6480        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6481        ResolveInfo resolveInfo;
6482        /* Best domain verification status of the activities found in the other profile */
6483        int bestDomainVerificationStatus;
6484    }
6485
6486    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6487            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6488        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6489                sourceUserId)) {
6490            return null;
6491        }
6492        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6493                resolvedType, flags, parentUserId);
6494
6495        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6496            return null;
6497        }
6498        CrossProfileDomainInfo result = null;
6499        int size = resultTargetUser.size();
6500        for (int i = 0; i < size; i++) {
6501            ResolveInfo riTargetUser = resultTargetUser.get(i);
6502            // Intent filter verification is only for filters that specify a host. So don't return
6503            // those that handle all web uris.
6504            if (riTargetUser.handleAllWebDataURI) {
6505                continue;
6506            }
6507            String packageName = riTargetUser.activityInfo.packageName;
6508            PackageSetting ps = mSettings.mPackages.get(packageName);
6509            if (ps == null) {
6510                continue;
6511            }
6512            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6513            int status = (int)(verificationState >> 32);
6514            if (result == null) {
6515                result = new CrossProfileDomainInfo();
6516                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6517                        sourceUserId, parentUserId);
6518                result.bestDomainVerificationStatus = status;
6519            } else {
6520                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6521                        result.bestDomainVerificationStatus);
6522            }
6523        }
6524        // Don't consider matches with status NEVER across profiles.
6525        if (result != null && result.bestDomainVerificationStatus
6526                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6527            return null;
6528        }
6529        return result;
6530    }
6531
6532    /**
6533     * Verification statuses are ordered from the worse to the best, except for
6534     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6535     */
6536    private int bestDomainVerificationStatus(int status1, int status2) {
6537        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6538            return status2;
6539        }
6540        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6541            return status1;
6542        }
6543        return (int) MathUtils.max(status1, status2);
6544    }
6545
6546    private boolean isUserEnabled(int userId) {
6547        long callingId = Binder.clearCallingIdentity();
6548        try {
6549            UserInfo userInfo = sUserManager.getUserInfo(userId);
6550            return userInfo != null && userInfo.isEnabled();
6551        } finally {
6552            Binder.restoreCallingIdentity(callingId);
6553        }
6554    }
6555
6556    /**
6557     * Filter out activities with systemUserOnly flag set, when current user is not System.
6558     *
6559     * @return filtered list
6560     */
6561    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6562        if (userId == UserHandle.USER_SYSTEM) {
6563            return resolveInfos;
6564        }
6565        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6566            ResolveInfo info = resolveInfos.get(i);
6567            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6568                resolveInfos.remove(i);
6569            }
6570        }
6571        return resolveInfos;
6572    }
6573
6574    /**
6575     * Filters out ephemeral activities.
6576     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6577     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6578     *
6579     * @param resolveInfos The pre-filtered list of resolved activities
6580     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6581     *          is performed.
6582     * @return A filtered list of resolved activities.
6583     */
6584    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6585            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6586        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6587            final ResolveInfo info = resolveInfos.get(i);
6588            // allow activities that are defined in the provided package
6589            if (allowDynamicSplits
6590                    && info.activityInfo.splitName != null
6591                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6592                            info.activityInfo.splitName)) {
6593                if (mInstantAppInstallerInfo == null) {
6594                    if (DEBUG_INSTALL) {
6595                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6596                    }
6597                    resolveInfos.remove(i);
6598                    continue;
6599                }
6600                // requested activity is defined in a split that hasn't been installed yet.
6601                // add the installer to the resolve list
6602                if (DEBUG_INSTALL) {
6603                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6604                }
6605                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6606                final ComponentName installFailureActivity = findInstallFailureActivity(
6607                        info.activityInfo.packageName,  filterCallingUid, userId);
6608                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6609                        info.activityInfo.packageName, info.activityInfo.splitName,
6610                        installFailureActivity,
6611                        info.activityInfo.applicationInfo.versionCode,
6612                        null /*failureIntent*/);
6613                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6614                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6615                // add a non-generic filter
6616                installerInfo.filter = new IntentFilter();
6617
6618                // This resolve info may appear in the chooser UI, so let us make it
6619                // look as the one it replaces as far as the user is concerned which
6620                // requires loading the correct label and icon for the resolve info.
6621                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6622                installerInfo.labelRes = info.resolveLabelResId();
6623                installerInfo.icon = info.resolveIconResId();
6624
6625                // propagate priority/preferred order/default
6626                installerInfo.priority = info.priority;
6627                installerInfo.preferredOrder = info.preferredOrder;
6628                installerInfo.isDefault = info.isDefault;
6629                resolveInfos.set(i, installerInfo);
6630                continue;
6631            }
6632            // caller is a full app, don't need to apply any other filtering
6633            if (ephemeralPkgName == null) {
6634                continue;
6635            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6636                // caller is same app; don't need to apply any other filtering
6637                continue;
6638            }
6639            // allow activities that have been explicitly exposed to ephemeral apps
6640            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6641            if (!isEphemeralApp
6642                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6643                continue;
6644            }
6645            resolveInfos.remove(i);
6646        }
6647        return resolveInfos;
6648    }
6649
6650    /**
6651     * Returns the activity component that can handle install failures.
6652     * <p>By default, the instant application installer handles failures. However, an
6653     * application may want to handle failures on its own. Applications do this by
6654     * creating an activity with an intent filter that handles the action
6655     * {@link Intent#ACTION_INSTALL_FAILURE}.
6656     */
6657    private @Nullable ComponentName findInstallFailureActivity(
6658            String packageName, int filterCallingUid, int userId) {
6659        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6660        failureActivityIntent.setPackage(packageName);
6661        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6662        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6663                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6664                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6665        final int NR = result.size();
6666        if (NR > 0) {
6667            for (int i = 0; i < NR; i++) {
6668                final ResolveInfo info = result.get(i);
6669                if (info.activityInfo.splitName != null) {
6670                    continue;
6671                }
6672                return new ComponentName(packageName, info.activityInfo.name);
6673            }
6674        }
6675        return null;
6676    }
6677
6678    /**
6679     * @param resolveInfos list of resolve infos in descending priority order
6680     * @return if the list contains a resolve info with non-negative priority
6681     */
6682    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6683        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6684    }
6685
6686    private static boolean hasWebURI(Intent intent) {
6687        if (intent.getData() == null) {
6688            return false;
6689        }
6690        final String scheme = intent.getScheme();
6691        if (TextUtils.isEmpty(scheme)) {
6692            return false;
6693        }
6694        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6695    }
6696
6697    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6698            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6699            int userId) {
6700        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6701
6702        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6703            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6704                    candidates.size());
6705        }
6706
6707        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6708        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6709        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6710        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6711        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6712        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6713
6714        synchronized (mPackages) {
6715            final int count = candidates.size();
6716            // First, try to use linked apps. Partition the candidates into four lists:
6717            // one for the final results, one for the "do not use ever", one for "undefined status"
6718            // and finally one for "browser app type".
6719            for (int n=0; n<count; n++) {
6720                ResolveInfo info = candidates.get(n);
6721                String packageName = info.activityInfo.packageName;
6722                PackageSetting ps = mSettings.mPackages.get(packageName);
6723                if (ps != null) {
6724                    // Add to the special match all list (Browser use case)
6725                    if (info.handleAllWebDataURI) {
6726                        matchAllList.add(info);
6727                        continue;
6728                    }
6729                    // Try to get the status from User settings first
6730                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6731                    int status = (int)(packedStatus >> 32);
6732                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6733                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6734                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6735                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6736                                    + " : linkgen=" + linkGeneration);
6737                        }
6738                        // Use link-enabled generation as preferredOrder, i.e.
6739                        // prefer newly-enabled over earlier-enabled.
6740                        info.preferredOrder = linkGeneration;
6741                        alwaysList.add(info);
6742                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6743                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6744                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6745                        }
6746                        neverList.add(info);
6747                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6748                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6749                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6750                        }
6751                        alwaysAskList.add(info);
6752                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6753                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6754                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6755                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6756                        }
6757                        undefinedList.add(info);
6758                    }
6759                }
6760            }
6761
6762            // We'll want to include browser possibilities in a few cases
6763            boolean includeBrowser = false;
6764
6765            // First try to add the "always" resolution(s) for the current user, if any
6766            if (alwaysList.size() > 0) {
6767                result.addAll(alwaysList);
6768            } else {
6769                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6770                result.addAll(undefinedList);
6771                // Maybe add one for the other profile.
6772                if (xpDomainInfo != null && (
6773                        xpDomainInfo.bestDomainVerificationStatus
6774                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6775                    result.add(xpDomainInfo.resolveInfo);
6776                }
6777                includeBrowser = true;
6778            }
6779
6780            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6781            // If there were 'always' entries their preferred order has been set, so we also
6782            // back that off to make the alternatives equivalent
6783            if (alwaysAskList.size() > 0) {
6784                for (ResolveInfo i : result) {
6785                    i.preferredOrder = 0;
6786                }
6787                result.addAll(alwaysAskList);
6788                includeBrowser = true;
6789            }
6790
6791            if (includeBrowser) {
6792                // Also add browsers (all of them or only the default one)
6793                if (DEBUG_DOMAIN_VERIFICATION) {
6794                    Slog.v(TAG, "   ...including browsers in candidate set");
6795                }
6796                if ((matchFlags & MATCH_ALL) != 0) {
6797                    result.addAll(matchAllList);
6798                } else {
6799                    // Browser/generic handling case.  If there's a default browser, go straight
6800                    // to that (but only if there is no other higher-priority match).
6801                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6802                    int maxMatchPrio = 0;
6803                    ResolveInfo defaultBrowserMatch = null;
6804                    final int numCandidates = matchAllList.size();
6805                    for (int n = 0; n < numCandidates; n++) {
6806                        ResolveInfo info = matchAllList.get(n);
6807                        // track the highest overall match priority...
6808                        if (info.priority > maxMatchPrio) {
6809                            maxMatchPrio = info.priority;
6810                        }
6811                        // ...and the highest-priority default browser match
6812                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6813                            if (defaultBrowserMatch == null
6814                                    || (defaultBrowserMatch.priority < info.priority)) {
6815                                if (debug) {
6816                                    Slog.v(TAG, "Considering default browser match " + info);
6817                                }
6818                                defaultBrowserMatch = info;
6819                            }
6820                        }
6821                    }
6822                    if (defaultBrowserMatch != null
6823                            && defaultBrowserMatch.priority >= maxMatchPrio
6824                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6825                    {
6826                        if (debug) {
6827                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6828                        }
6829                        result.add(defaultBrowserMatch);
6830                    } else {
6831                        result.addAll(matchAllList);
6832                    }
6833                }
6834
6835                // If there is nothing selected, add all candidates and remove the ones that the user
6836                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6837                if (result.size() == 0) {
6838                    result.addAll(candidates);
6839                    result.removeAll(neverList);
6840                }
6841            }
6842        }
6843        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6844            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6845                    result.size());
6846            for (ResolveInfo info : result) {
6847                Slog.v(TAG, "  + " + info.activityInfo);
6848            }
6849        }
6850        return result;
6851    }
6852
6853    // Returns a packed value as a long:
6854    //
6855    // high 'int'-sized word: link status: undefined/ask/never/always.
6856    // low 'int'-sized word: relative priority among 'always' results.
6857    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6858        long result = ps.getDomainVerificationStatusForUser(userId);
6859        // if none available, get the master status
6860        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6861            if (ps.getIntentFilterVerificationInfo() != null) {
6862                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6863            }
6864        }
6865        return result;
6866    }
6867
6868    private ResolveInfo querySkipCurrentProfileIntents(
6869            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6870            int flags, int sourceUserId) {
6871        if (matchingFilters != null) {
6872            int size = matchingFilters.size();
6873            for (int i = 0; i < size; i ++) {
6874                CrossProfileIntentFilter filter = matchingFilters.get(i);
6875                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6876                    // Checking if there are activities in the target user that can handle the
6877                    // intent.
6878                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6879                            resolvedType, flags, sourceUserId);
6880                    if (resolveInfo != null) {
6881                        return resolveInfo;
6882                    }
6883                }
6884            }
6885        }
6886        return null;
6887    }
6888
6889    // Return matching ResolveInfo in target user if any.
6890    private ResolveInfo queryCrossProfileIntents(
6891            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6892            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6893        if (matchingFilters != null) {
6894            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6895            // match the same intent. For performance reasons, it is better not to
6896            // run queryIntent twice for the same userId
6897            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6898            int size = matchingFilters.size();
6899            for (int i = 0; i < size; i++) {
6900                CrossProfileIntentFilter filter = matchingFilters.get(i);
6901                int targetUserId = filter.getTargetUserId();
6902                boolean skipCurrentProfile =
6903                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6904                boolean skipCurrentProfileIfNoMatchFound =
6905                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6906                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6907                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6908                    // Checking if there are activities in the target user that can handle the
6909                    // intent.
6910                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6911                            resolvedType, flags, sourceUserId);
6912                    if (resolveInfo != null) return resolveInfo;
6913                    alreadyTriedUserIds.put(targetUserId, true);
6914                }
6915            }
6916        }
6917        return null;
6918    }
6919
6920    /**
6921     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6922     * will forward the intent to the filter's target user.
6923     * Otherwise, returns null.
6924     */
6925    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6926            String resolvedType, int flags, int sourceUserId) {
6927        int targetUserId = filter.getTargetUserId();
6928        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6929                resolvedType, flags, targetUserId);
6930        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6931            // If all the matches in the target profile are suspended, return null.
6932            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6933                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6934                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6935                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6936                            targetUserId);
6937                }
6938            }
6939        }
6940        return null;
6941    }
6942
6943    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6944            int sourceUserId, int targetUserId) {
6945        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6946        long ident = Binder.clearCallingIdentity();
6947        boolean targetIsProfile;
6948        try {
6949            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6950        } finally {
6951            Binder.restoreCallingIdentity(ident);
6952        }
6953        String className;
6954        if (targetIsProfile) {
6955            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6956        } else {
6957            className = FORWARD_INTENT_TO_PARENT;
6958        }
6959        ComponentName forwardingActivityComponentName = new ComponentName(
6960                mAndroidApplication.packageName, className);
6961        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6962                sourceUserId);
6963        if (!targetIsProfile) {
6964            forwardingActivityInfo.showUserIcon = targetUserId;
6965            forwardingResolveInfo.noResourceId = true;
6966        }
6967        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6968        forwardingResolveInfo.priority = 0;
6969        forwardingResolveInfo.preferredOrder = 0;
6970        forwardingResolveInfo.match = 0;
6971        forwardingResolveInfo.isDefault = true;
6972        forwardingResolveInfo.filter = filter;
6973        forwardingResolveInfo.targetUserId = targetUserId;
6974        return forwardingResolveInfo;
6975    }
6976
6977    @Override
6978    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6979            Intent[] specifics, String[] specificTypes, Intent intent,
6980            String resolvedType, int flags, int userId) {
6981        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6982                specificTypes, intent, resolvedType, flags, userId));
6983    }
6984
6985    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6986            Intent[] specifics, String[] specificTypes, Intent intent,
6987            String resolvedType, int flags, int userId) {
6988        if (!sUserManager.exists(userId)) return Collections.emptyList();
6989        final int callingUid = Binder.getCallingUid();
6990        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6991                false /*includeInstantApps*/);
6992        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
6993                false /*requireFullPermission*/, false /*checkShell*/,
6994                "query intent activity options");
6995        final String resultsAction = intent.getAction();
6996
6997        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6998                | PackageManager.GET_RESOLVED_FILTER, userId);
6999
7000        if (DEBUG_INTENT_MATCHING) {
7001            Log.v(TAG, "Query " + intent + ": " + results);
7002        }
7003
7004        int specificsPos = 0;
7005        int N;
7006
7007        // todo: note that the algorithm used here is O(N^2).  This
7008        // isn't a problem in our current environment, but if we start running
7009        // into situations where we have more than 5 or 10 matches then this
7010        // should probably be changed to something smarter...
7011
7012        // First we go through and resolve each of the specific items
7013        // that were supplied, taking care of removing any corresponding
7014        // duplicate items in the generic resolve list.
7015        if (specifics != null) {
7016            for (int i=0; i<specifics.length; i++) {
7017                final Intent sintent = specifics[i];
7018                if (sintent == null) {
7019                    continue;
7020                }
7021
7022                if (DEBUG_INTENT_MATCHING) {
7023                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7024                }
7025
7026                String action = sintent.getAction();
7027                if (resultsAction != null && resultsAction.equals(action)) {
7028                    // If this action was explicitly requested, then don't
7029                    // remove things that have it.
7030                    action = null;
7031                }
7032
7033                ResolveInfo ri = null;
7034                ActivityInfo ai = null;
7035
7036                ComponentName comp = sintent.getComponent();
7037                if (comp == null) {
7038                    ri = resolveIntent(
7039                        sintent,
7040                        specificTypes != null ? specificTypes[i] : null,
7041                            flags, userId);
7042                    if (ri == null) {
7043                        continue;
7044                    }
7045                    if (ri == mResolveInfo) {
7046                        // ACK!  Must do something better with this.
7047                    }
7048                    ai = ri.activityInfo;
7049                    comp = new ComponentName(ai.applicationInfo.packageName,
7050                            ai.name);
7051                } else {
7052                    ai = getActivityInfo(comp, flags, userId);
7053                    if (ai == null) {
7054                        continue;
7055                    }
7056                }
7057
7058                // Look for any generic query activities that are duplicates
7059                // of this specific one, and remove them from the results.
7060                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7061                N = results.size();
7062                int j;
7063                for (j=specificsPos; j<N; j++) {
7064                    ResolveInfo sri = results.get(j);
7065                    if ((sri.activityInfo.name.equals(comp.getClassName())
7066                            && sri.activityInfo.applicationInfo.packageName.equals(
7067                                    comp.getPackageName()))
7068                        || (action != null && sri.filter.matchAction(action))) {
7069                        results.remove(j);
7070                        if (DEBUG_INTENT_MATCHING) Log.v(
7071                            TAG, "Removing duplicate item from " + j
7072                            + " due to specific " + specificsPos);
7073                        if (ri == null) {
7074                            ri = sri;
7075                        }
7076                        j--;
7077                        N--;
7078                    }
7079                }
7080
7081                // Add this specific item to its proper place.
7082                if (ri == null) {
7083                    ri = new ResolveInfo();
7084                    ri.activityInfo = ai;
7085                }
7086                results.add(specificsPos, ri);
7087                ri.specificIndex = i;
7088                specificsPos++;
7089            }
7090        }
7091
7092        // Now we go through the remaining generic results and remove any
7093        // duplicate actions that are found here.
7094        N = results.size();
7095        for (int i=specificsPos; i<N-1; i++) {
7096            final ResolveInfo rii = results.get(i);
7097            if (rii.filter == null) {
7098                continue;
7099            }
7100
7101            // Iterate over all of the actions of this result's intent
7102            // filter...  typically this should be just one.
7103            final Iterator<String> it = rii.filter.actionsIterator();
7104            if (it == null) {
7105                continue;
7106            }
7107            while (it.hasNext()) {
7108                final String action = it.next();
7109                if (resultsAction != null && resultsAction.equals(action)) {
7110                    // If this action was explicitly requested, then don't
7111                    // remove things that have it.
7112                    continue;
7113                }
7114                for (int j=i+1; j<N; j++) {
7115                    final ResolveInfo rij = results.get(j);
7116                    if (rij.filter != null && rij.filter.hasAction(action)) {
7117                        results.remove(j);
7118                        if (DEBUG_INTENT_MATCHING) Log.v(
7119                            TAG, "Removing duplicate item from " + j
7120                            + " due to action " + action + " at " + i);
7121                        j--;
7122                        N--;
7123                    }
7124                }
7125            }
7126
7127            // If the caller didn't request filter information, drop it now
7128            // so we don't have to marshall/unmarshall it.
7129            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7130                rii.filter = null;
7131            }
7132        }
7133
7134        // Filter out the caller activity if so requested.
7135        if (caller != null) {
7136            N = results.size();
7137            for (int i=0; i<N; i++) {
7138                ActivityInfo ainfo = results.get(i).activityInfo;
7139                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7140                        && caller.getClassName().equals(ainfo.name)) {
7141                    results.remove(i);
7142                    break;
7143                }
7144            }
7145        }
7146
7147        // If the caller didn't request filter information,
7148        // drop them now so we don't have to
7149        // marshall/unmarshall it.
7150        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7151            N = results.size();
7152            for (int i=0; i<N; i++) {
7153                results.get(i).filter = null;
7154            }
7155        }
7156
7157        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7158        return results;
7159    }
7160
7161    @Override
7162    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7163            String resolvedType, int flags, int userId) {
7164        return new ParceledListSlice<>(
7165                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7166                        false /*allowDynamicSplits*/));
7167    }
7168
7169    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7170            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7171        if (!sUserManager.exists(userId)) return Collections.emptyList();
7172        final int callingUid = Binder.getCallingUid();
7173        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7174                false /*requireFullPermission*/, false /*checkShell*/,
7175                "query intent receivers");
7176        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7177        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7178                false /*includeInstantApps*/);
7179        ComponentName comp = intent.getComponent();
7180        if (comp == null) {
7181            if (intent.getSelector() != null) {
7182                intent = intent.getSelector();
7183                comp = intent.getComponent();
7184            }
7185        }
7186        if (comp != null) {
7187            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7188            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7189            if (ai != null) {
7190                // When specifying an explicit component, we prevent the activity from being
7191                // used when either 1) the calling package is normal and the activity is within
7192                // an instant application or 2) the calling package is ephemeral and the
7193                // activity is not visible to instant applications.
7194                final boolean matchInstantApp =
7195                        (flags & PackageManager.MATCH_INSTANT) != 0;
7196                final boolean matchVisibleToInstantAppOnly =
7197                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7198                final boolean matchExplicitlyVisibleOnly =
7199                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7200                final boolean isCallerInstantApp =
7201                        instantAppPkgName != null;
7202                final boolean isTargetSameInstantApp =
7203                        comp.getPackageName().equals(instantAppPkgName);
7204                final boolean isTargetInstantApp =
7205                        (ai.applicationInfo.privateFlags
7206                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7207                final boolean isTargetVisibleToInstantApp =
7208                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7209                final boolean isTargetExplicitlyVisibleToInstantApp =
7210                        isTargetVisibleToInstantApp
7211                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7212                final boolean isTargetHiddenFromInstantApp =
7213                        !isTargetVisibleToInstantApp
7214                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7215                final boolean blockResolution =
7216                        !isTargetSameInstantApp
7217                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7218                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7219                                        && isTargetHiddenFromInstantApp));
7220                if (!blockResolution) {
7221                    ResolveInfo ri = new ResolveInfo();
7222                    ri.activityInfo = ai;
7223                    list.add(ri);
7224                }
7225            }
7226            return applyPostResolutionFilter(
7227                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7228        }
7229
7230        // reader
7231        synchronized (mPackages) {
7232            String pkgName = intent.getPackage();
7233            if (pkgName == null) {
7234                final List<ResolveInfo> result =
7235                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7236                return applyPostResolutionFilter(
7237                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7238            }
7239            final PackageParser.Package pkg = mPackages.get(pkgName);
7240            if (pkg != null) {
7241                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7242                        intent, resolvedType, flags, pkg.receivers, userId);
7243                return applyPostResolutionFilter(
7244                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7245            }
7246            return Collections.emptyList();
7247        }
7248    }
7249
7250    @Override
7251    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7252        final int callingUid = Binder.getCallingUid();
7253        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7254    }
7255
7256    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7257            int userId, int callingUid) {
7258        if (!sUserManager.exists(userId)) return null;
7259        flags = updateFlagsForResolve(
7260                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7261        List<ResolveInfo> query = queryIntentServicesInternal(
7262                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7263        if (query != null) {
7264            if (query.size() >= 1) {
7265                // If there is more than one service with the same priority,
7266                // just arbitrarily pick the first one.
7267                return query.get(0);
7268            }
7269        }
7270        return null;
7271    }
7272
7273    @Override
7274    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7275            String resolvedType, int flags, int userId) {
7276        final int callingUid = Binder.getCallingUid();
7277        return new ParceledListSlice<>(queryIntentServicesInternal(
7278                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7279    }
7280
7281    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7282            String resolvedType, int flags, int userId, int callingUid,
7283            boolean includeInstantApps) {
7284        if (!sUserManager.exists(userId)) return Collections.emptyList();
7285        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7286                false /*requireFullPermission*/, false /*checkShell*/,
7287                "query intent receivers");
7288        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7289        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7290        ComponentName comp = intent.getComponent();
7291        if (comp == null) {
7292            if (intent.getSelector() != null) {
7293                intent = intent.getSelector();
7294                comp = intent.getComponent();
7295            }
7296        }
7297        if (comp != null) {
7298            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7299            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7300            if (si != null) {
7301                // When specifying an explicit component, we prevent the service from being
7302                // used when either 1) the service is in an instant application and the
7303                // caller is not the same instant application or 2) the calling package is
7304                // ephemeral and the activity is not visible to ephemeral applications.
7305                final boolean matchInstantApp =
7306                        (flags & PackageManager.MATCH_INSTANT) != 0;
7307                final boolean matchVisibleToInstantAppOnly =
7308                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7309                final boolean isCallerInstantApp =
7310                        instantAppPkgName != null;
7311                final boolean isTargetSameInstantApp =
7312                        comp.getPackageName().equals(instantAppPkgName);
7313                final boolean isTargetInstantApp =
7314                        (si.applicationInfo.privateFlags
7315                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7316                final boolean isTargetHiddenFromInstantApp =
7317                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7318                final boolean blockResolution =
7319                        !isTargetSameInstantApp
7320                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7321                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7322                                        && isTargetHiddenFromInstantApp));
7323                if (!blockResolution) {
7324                    final ResolveInfo ri = new ResolveInfo();
7325                    ri.serviceInfo = si;
7326                    list.add(ri);
7327                }
7328            }
7329            return list;
7330        }
7331
7332        // reader
7333        synchronized (mPackages) {
7334            String pkgName = intent.getPackage();
7335            if (pkgName == null) {
7336                return applyPostServiceResolutionFilter(
7337                        mServices.queryIntent(intent, resolvedType, flags, userId),
7338                        instantAppPkgName);
7339            }
7340            final PackageParser.Package pkg = mPackages.get(pkgName);
7341            if (pkg != null) {
7342                return applyPostServiceResolutionFilter(
7343                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7344                                userId),
7345                        instantAppPkgName);
7346            }
7347            return Collections.emptyList();
7348        }
7349    }
7350
7351    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7352            String instantAppPkgName) {
7353        if (instantAppPkgName == null) {
7354            return resolveInfos;
7355        }
7356        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7357            final ResolveInfo info = resolveInfos.get(i);
7358            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7359            // allow services that are defined in the provided package
7360            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7361                if (info.serviceInfo.splitName != null
7362                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7363                                info.serviceInfo.splitName)) {
7364                    // requested service is defined in a split that hasn't been installed yet.
7365                    // add the installer to the resolve list
7366                    if (DEBUG_EPHEMERAL) {
7367                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7368                    }
7369                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7370                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7371                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7372                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7373                            null /*failureIntent*/);
7374                    // make sure this resolver is the default
7375                    installerInfo.isDefault = true;
7376                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7377                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7378                    // add a non-generic filter
7379                    installerInfo.filter = new IntentFilter();
7380                    // load resources from the correct package
7381                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7382                    resolveInfos.set(i, installerInfo);
7383                }
7384                continue;
7385            }
7386            // allow services that have been explicitly exposed to ephemeral apps
7387            if (!isEphemeralApp
7388                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7389                continue;
7390            }
7391            resolveInfos.remove(i);
7392        }
7393        return resolveInfos;
7394    }
7395
7396    @Override
7397    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7398            String resolvedType, int flags, int userId) {
7399        return new ParceledListSlice<>(
7400                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7401    }
7402
7403    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7404            Intent intent, String resolvedType, int flags, int userId) {
7405        if (!sUserManager.exists(userId)) return Collections.emptyList();
7406        final int callingUid = Binder.getCallingUid();
7407        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7408        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7409                false /*includeInstantApps*/);
7410        ComponentName comp = intent.getComponent();
7411        if (comp == null) {
7412            if (intent.getSelector() != null) {
7413                intent = intent.getSelector();
7414                comp = intent.getComponent();
7415            }
7416        }
7417        if (comp != null) {
7418            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7419            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7420            if (pi != null) {
7421                // When specifying an explicit component, we prevent the provider from being
7422                // used when either 1) the provider is in an instant application and the
7423                // caller is not the same instant application or 2) the calling package is an
7424                // instant application and the provider is not visible to instant applications.
7425                final boolean matchInstantApp =
7426                        (flags & PackageManager.MATCH_INSTANT) != 0;
7427                final boolean matchVisibleToInstantAppOnly =
7428                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7429                final boolean isCallerInstantApp =
7430                        instantAppPkgName != null;
7431                final boolean isTargetSameInstantApp =
7432                        comp.getPackageName().equals(instantAppPkgName);
7433                final boolean isTargetInstantApp =
7434                        (pi.applicationInfo.privateFlags
7435                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7436                final boolean isTargetHiddenFromInstantApp =
7437                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7438                final boolean blockResolution =
7439                        !isTargetSameInstantApp
7440                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7441                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7442                                        && isTargetHiddenFromInstantApp));
7443                if (!blockResolution) {
7444                    final ResolveInfo ri = new ResolveInfo();
7445                    ri.providerInfo = pi;
7446                    list.add(ri);
7447                }
7448            }
7449            return list;
7450        }
7451
7452        // reader
7453        synchronized (mPackages) {
7454            String pkgName = intent.getPackage();
7455            if (pkgName == null) {
7456                return applyPostContentProviderResolutionFilter(
7457                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7458                        instantAppPkgName);
7459            }
7460            final PackageParser.Package pkg = mPackages.get(pkgName);
7461            if (pkg != null) {
7462                return applyPostContentProviderResolutionFilter(
7463                        mProviders.queryIntentForPackage(
7464                        intent, resolvedType, flags, pkg.providers, userId),
7465                        instantAppPkgName);
7466            }
7467            return Collections.emptyList();
7468        }
7469    }
7470
7471    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7472            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7473        if (instantAppPkgName == null) {
7474            return resolveInfos;
7475        }
7476        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7477            final ResolveInfo info = resolveInfos.get(i);
7478            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7479            // allow providers that are defined in the provided package
7480            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7481                if (info.providerInfo.splitName != null
7482                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7483                                info.providerInfo.splitName)) {
7484                    // requested provider is defined in a split that hasn't been installed yet.
7485                    // add the installer to the resolve list
7486                    if (DEBUG_EPHEMERAL) {
7487                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7488                    }
7489                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7490                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7491                            info.providerInfo.packageName, info.providerInfo.splitName,
7492                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7493                            null /*failureIntent*/);
7494                    // make sure this resolver is the default
7495                    installerInfo.isDefault = true;
7496                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7497                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7498                    // add a non-generic filter
7499                    installerInfo.filter = new IntentFilter();
7500                    // load resources from the correct package
7501                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7502                    resolveInfos.set(i, installerInfo);
7503                }
7504                continue;
7505            }
7506            // allow providers that have been explicitly exposed to instant applications
7507            if (!isEphemeralApp
7508                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7509                continue;
7510            }
7511            resolveInfos.remove(i);
7512        }
7513        return resolveInfos;
7514    }
7515
7516    @Override
7517    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7518        final int callingUid = Binder.getCallingUid();
7519        if (getInstantAppPackageName(callingUid) != null) {
7520            return ParceledListSlice.emptyList();
7521        }
7522        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7523        flags = updateFlagsForPackage(flags, userId, null);
7524        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7525        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7526                true /* requireFullPermission */, false /* checkShell */,
7527                "get installed packages");
7528
7529        // writer
7530        synchronized (mPackages) {
7531            ArrayList<PackageInfo> list;
7532            if (listUninstalled) {
7533                list = new ArrayList<>(mSettings.mPackages.size());
7534                for (PackageSetting ps : mSettings.mPackages.values()) {
7535                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7536                        continue;
7537                    }
7538                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7539                        continue;
7540                    }
7541                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7542                    if (pi != null) {
7543                        list.add(pi);
7544                    }
7545                }
7546            } else {
7547                list = new ArrayList<>(mPackages.size());
7548                for (PackageParser.Package p : mPackages.values()) {
7549                    final PackageSetting ps = (PackageSetting) p.mExtras;
7550                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7551                        continue;
7552                    }
7553                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7554                        continue;
7555                    }
7556                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7557                            p.mExtras, flags, userId);
7558                    if (pi != null) {
7559                        list.add(pi);
7560                    }
7561                }
7562            }
7563
7564            return new ParceledListSlice<>(list);
7565        }
7566    }
7567
7568    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7569            String[] permissions, boolean[] tmp, int flags, int userId) {
7570        int numMatch = 0;
7571        final PermissionsState permissionsState = ps.getPermissionsState();
7572        for (int i=0; i<permissions.length; i++) {
7573            final String permission = permissions[i];
7574            if (permissionsState.hasPermission(permission, userId)) {
7575                tmp[i] = true;
7576                numMatch++;
7577            } else {
7578                tmp[i] = false;
7579            }
7580        }
7581        if (numMatch == 0) {
7582            return;
7583        }
7584        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7585
7586        // The above might return null in cases of uninstalled apps or install-state
7587        // skew across users/profiles.
7588        if (pi != null) {
7589            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7590                if (numMatch == permissions.length) {
7591                    pi.requestedPermissions = permissions;
7592                } else {
7593                    pi.requestedPermissions = new String[numMatch];
7594                    numMatch = 0;
7595                    for (int i=0; i<permissions.length; i++) {
7596                        if (tmp[i]) {
7597                            pi.requestedPermissions[numMatch] = permissions[i];
7598                            numMatch++;
7599                        }
7600                    }
7601                }
7602            }
7603            list.add(pi);
7604        }
7605    }
7606
7607    @Override
7608    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7609            String[] permissions, int flags, int userId) {
7610        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7611        flags = updateFlagsForPackage(flags, userId, permissions);
7612        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7613                true /* requireFullPermission */, false /* checkShell */,
7614                "get packages holding permissions");
7615        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7616
7617        // writer
7618        synchronized (mPackages) {
7619            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7620            boolean[] tmpBools = new boolean[permissions.length];
7621            if (listUninstalled) {
7622                for (PackageSetting ps : mSettings.mPackages.values()) {
7623                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7624                            userId);
7625                }
7626            } else {
7627                for (PackageParser.Package pkg : mPackages.values()) {
7628                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7629                    if (ps != null) {
7630                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7631                                userId);
7632                    }
7633                }
7634            }
7635
7636            return new ParceledListSlice<PackageInfo>(list);
7637        }
7638    }
7639
7640    @Override
7641    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7642        final int callingUid = Binder.getCallingUid();
7643        if (getInstantAppPackageName(callingUid) != null) {
7644            return ParceledListSlice.emptyList();
7645        }
7646        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7647        flags = updateFlagsForApplication(flags, userId, null);
7648        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7649
7650        // writer
7651        synchronized (mPackages) {
7652            ArrayList<ApplicationInfo> list;
7653            if (listUninstalled) {
7654                list = new ArrayList<>(mSettings.mPackages.size());
7655                for (PackageSetting ps : mSettings.mPackages.values()) {
7656                    ApplicationInfo ai;
7657                    int effectiveFlags = flags;
7658                    if (ps.isSystem()) {
7659                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7660                    }
7661                    if (ps.pkg != null) {
7662                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7663                            continue;
7664                        }
7665                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7666                            continue;
7667                        }
7668                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7669                                ps.readUserState(userId), userId);
7670                        if (ai != null) {
7671                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7672                        }
7673                    } else {
7674                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7675                        // and already converts to externally visible package name
7676                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7677                                callingUid, effectiveFlags, userId);
7678                    }
7679                    if (ai != null) {
7680                        list.add(ai);
7681                    }
7682                }
7683            } else {
7684                list = new ArrayList<>(mPackages.size());
7685                for (PackageParser.Package p : mPackages.values()) {
7686                    if (p.mExtras != null) {
7687                        PackageSetting ps = (PackageSetting) p.mExtras;
7688                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7689                            continue;
7690                        }
7691                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7692                            continue;
7693                        }
7694                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7695                                ps.readUserState(userId), userId);
7696                        if (ai != null) {
7697                            ai.packageName = resolveExternalPackageNameLPr(p);
7698                            list.add(ai);
7699                        }
7700                    }
7701                }
7702            }
7703
7704            return new ParceledListSlice<>(list);
7705        }
7706    }
7707
7708    @Override
7709    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7710        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7711            return null;
7712        }
7713        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7714            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7715                    "getEphemeralApplications");
7716        }
7717        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7718                true /* requireFullPermission */, false /* checkShell */,
7719                "getEphemeralApplications");
7720        synchronized (mPackages) {
7721            List<InstantAppInfo> instantApps = mInstantAppRegistry
7722                    .getInstantAppsLPr(userId);
7723            if (instantApps != null) {
7724                return new ParceledListSlice<>(instantApps);
7725            }
7726        }
7727        return null;
7728    }
7729
7730    @Override
7731    public boolean isInstantApp(String packageName, int userId) {
7732        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7733                true /* requireFullPermission */, false /* checkShell */,
7734                "isInstantApp");
7735        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7736            return false;
7737        }
7738
7739        synchronized (mPackages) {
7740            int callingUid = Binder.getCallingUid();
7741            if (Process.isIsolated(callingUid)) {
7742                callingUid = mIsolatedOwners.get(callingUid);
7743            }
7744            final PackageSetting ps = mSettings.mPackages.get(packageName);
7745            PackageParser.Package pkg = mPackages.get(packageName);
7746            final boolean returnAllowed =
7747                    ps != null
7748                    && (isCallerSameApp(packageName, callingUid)
7749                            || canViewInstantApps(callingUid, userId)
7750                            || mInstantAppRegistry.isInstantAccessGranted(
7751                                    userId, UserHandle.getAppId(callingUid), ps.appId));
7752            if (returnAllowed) {
7753                return ps.getInstantApp(userId);
7754            }
7755        }
7756        return false;
7757    }
7758
7759    @Override
7760    public byte[] getInstantAppCookie(String packageName, int userId) {
7761        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7762            return null;
7763        }
7764
7765        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7766                true /* requireFullPermission */, false /* checkShell */,
7767                "getInstantAppCookie");
7768        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7769            return null;
7770        }
7771        synchronized (mPackages) {
7772            return mInstantAppRegistry.getInstantAppCookieLPw(
7773                    packageName, userId);
7774        }
7775    }
7776
7777    @Override
7778    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7779        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7780            return true;
7781        }
7782
7783        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7784                true /* requireFullPermission */, true /* checkShell */,
7785                "setInstantAppCookie");
7786        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7787            return false;
7788        }
7789        synchronized (mPackages) {
7790            return mInstantAppRegistry.setInstantAppCookieLPw(
7791                    packageName, cookie, userId);
7792        }
7793    }
7794
7795    @Override
7796    public Bitmap getInstantAppIcon(String packageName, int userId) {
7797        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7798            return null;
7799        }
7800
7801        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
7802            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7803                    "getInstantAppIcon");
7804        }
7805        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7806                true /* requireFullPermission */, false /* checkShell */,
7807                "getInstantAppIcon");
7808
7809        synchronized (mPackages) {
7810            return mInstantAppRegistry.getInstantAppIconLPw(
7811                    packageName, userId);
7812        }
7813    }
7814
7815    private boolean isCallerSameApp(String packageName, int uid) {
7816        PackageParser.Package pkg = mPackages.get(packageName);
7817        return pkg != null
7818                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7819    }
7820
7821    @Override
7822    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7823        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7824            return ParceledListSlice.emptyList();
7825        }
7826        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7827    }
7828
7829    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7830        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7831
7832        // reader
7833        synchronized (mPackages) {
7834            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7835            final int userId = UserHandle.getCallingUserId();
7836            while (i.hasNext()) {
7837                final PackageParser.Package p = i.next();
7838                if (p.applicationInfo == null) continue;
7839
7840                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7841                        && !p.applicationInfo.isDirectBootAware();
7842                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7843                        && p.applicationInfo.isDirectBootAware();
7844
7845                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7846                        && (!mSafeMode || isSystemApp(p))
7847                        && (matchesUnaware || matchesAware)) {
7848                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7849                    if (ps != null) {
7850                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7851                                ps.readUserState(userId), userId);
7852                        if (ai != null) {
7853                            finalList.add(ai);
7854                        }
7855                    }
7856                }
7857            }
7858        }
7859
7860        return finalList;
7861    }
7862
7863    @Override
7864    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7865        return resolveContentProviderInternal(name, flags, userId);
7866    }
7867
7868    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
7869        if (!sUserManager.exists(userId)) return null;
7870        flags = updateFlagsForComponent(flags, userId, name);
7871        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7872        // reader
7873        synchronized (mPackages) {
7874            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7875            PackageSetting ps = provider != null
7876                    ? mSettings.mPackages.get(provider.owner.packageName)
7877                    : null;
7878            if (ps != null) {
7879                final boolean isInstantApp = ps.getInstantApp(userId);
7880                // normal application; filter out instant application provider
7881                if (instantAppPkgName == null && isInstantApp) {
7882                    return null;
7883                }
7884                // instant application; filter out other instant applications
7885                if (instantAppPkgName != null
7886                        && isInstantApp
7887                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7888                    return null;
7889                }
7890                // instant application; filter out non-exposed provider
7891                if (instantAppPkgName != null
7892                        && !isInstantApp
7893                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7894                    return null;
7895                }
7896                // provider not enabled
7897                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7898                    return null;
7899                }
7900                return PackageParser.generateProviderInfo(
7901                        provider, flags, ps.readUserState(userId), userId);
7902            }
7903            return null;
7904        }
7905    }
7906
7907    /**
7908     * @deprecated
7909     */
7910    @Deprecated
7911    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7912        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7913            return;
7914        }
7915        // reader
7916        synchronized (mPackages) {
7917            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7918                    .entrySet().iterator();
7919            final int userId = UserHandle.getCallingUserId();
7920            while (i.hasNext()) {
7921                Map.Entry<String, PackageParser.Provider> entry = i.next();
7922                PackageParser.Provider p = entry.getValue();
7923                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7924
7925                if (ps != null && p.syncable
7926                        && (!mSafeMode || (p.info.applicationInfo.flags
7927                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7928                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7929                            ps.readUserState(userId), userId);
7930                    if (info != null) {
7931                        outNames.add(entry.getKey());
7932                        outInfo.add(info);
7933                    }
7934                }
7935            }
7936        }
7937    }
7938
7939    @Override
7940    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7941            int uid, int flags, String metaDataKey) {
7942        final int callingUid = Binder.getCallingUid();
7943        final int userId = processName != null ? UserHandle.getUserId(uid)
7944                : UserHandle.getCallingUserId();
7945        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7946        flags = updateFlagsForComponent(flags, userId, processName);
7947        ArrayList<ProviderInfo> finalList = null;
7948        // reader
7949        synchronized (mPackages) {
7950            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7951            while (i.hasNext()) {
7952                final PackageParser.Provider p = i.next();
7953                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7954                if (ps != null && p.info.authority != null
7955                        && (processName == null
7956                                || (p.info.processName.equals(processName)
7957                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7958                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7959
7960                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7961                    // parameter.
7962                    if (metaDataKey != null
7963                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7964                        continue;
7965                    }
7966                    final ComponentName component =
7967                            new ComponentName(p.info.packageName, p.info.name);
7968                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
7969                        continue;
7970                    }
7971                    if (finalList == null) {
7972                        finalList = new ArrayList<ProviderInfo>(3);
7973                    }
7974                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7975                            ps.readUserState(userId), userId);
7976                    if (info != null) {
7977                        finalList.add(info);
7978                    }
7979                }
7980            }
7981        }
7982
7983        if (finalList != null) {
7984            Collections.sort(finalList, mProviderInitOrderSorter);
7985            return new ParceledListSlice<ProviderInfo>(finalList);
7986        }
7987
7988        return ParceledListSlice.emptyList();
7989    }
7990
7991    @Override
7992    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
7993        // reader
7994        synchronized (mPackages) {
7995            final int callingUid = Binder.getCallingUid();
7996            final int callingUserId = UserHandle.getUserId(callingUid);
7997            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
7998            if (ps == null) return null;
7999            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8000                return null;
8001            }
8002            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8003            return PackageParser.generateInstrumentationInfo(i, flags);
8004        }
8005    }
8006
8007    @Override
8008    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8009            String targetPackage, int flags) {
8010        final int callingUid = Binder.getCallingUid();
8011        final int callingUserId = UserHandle.getUserId(callingUid);
8012        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8013        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8014            return ParceledListSlice.emptyList();
8015        }
8016        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8017    }
8018
8019    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8020            int flags) {
8021        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8022
8023        // reader
8024        synchronized (mPackages) {
8025            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8026            while (i.hasNext()) {
8027                final PackageParser.Instrumentation p = i.next();
8028                if (targetPackage == null
8029                        || targetPackage.equals(p.info.targetPackage)) {
8030                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8031                            flags);
8032                    if (ii != null) {
8033                        finalList.add(ii);
8034                    }
8035                }
8036            }
8037        }
8038
8039        return finalList;
8040    }
8041
8042    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8043        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8044        try {
8045            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8046        } finally {
8047            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8048        }
8049    }
8050
8051    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8052        final File[] files = dir.listFiles();
8053        if (ArrayUtils.isEmpty(files)) {
8054            Log.d(TAG, "No files in app dir " + dir);
8055            return;
8056        }
8057
8058        if (DEBUG_PACKAGE_SCANNING) {
8059            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8060                    + " flags=0x" + Integer.toHexString(parseFlags));
8061        }
8062        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8063                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8064                mParallelPackageParserCallback)) {
8065            // Submit files for parsing in parallel
8066            int fileCount = 0;
8067            for (File file : files) {
8068                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8069                        && !PackageInstallerService.isStageName(file.getName());
8070                if (!isPackage) {
8071                    // Ignore entries which are not packages
8072                    continue;
8073                }
8074                parallelPackageParser.submit(file, parseFlags);
8075                fileCount++;
8076            }
8077
8078            // Process results one by one
8079            for (; fileCount > 0; fileCount--) {
8080                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8081                Throwable throwable = parseResult.throwable;
8082                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8083
8084                if (throwable == null) {
8085                    // Static shared libraries have synthetic package names
8086                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8087                        renameStaticSharedLibraryPackage(parseResult.pkg);
8088                    }
8089                    try {
8090                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8091                            scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8092                                    currentTime, null);
8093                        }
8094                    } catch (PackageManagerException e) {
8095                        errorCode = e.error;
8096                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8097                    }
8098                } else if (throwable instanceof PackageParser.PackageParserException) {
8099                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8100                            throwable;
8101                    errorCode = e.error;
8102                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8103                } else {
8104                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8105                            + parseResult.scanFile, throwable);
8106                }
8107
8108                // Delete invalid userdata apps
8109                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8110                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8111                    logCriticalInfo(Log.WARN,
8112                            "Deleting invalid package at " + parseResult.scanFile);
8113                    removeCodePathLI(parseResult.scanFile);
8114                }
8115            }
8116        }
8117    }
8118
8119    public static void reportSettingsProblem(int priority, String msg) {
8120        logCriticalInfo(priority, msg);
8121    }
8122
8123    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8124            final @ParseFlags int parseFlags) throws PackageManagerException {
8125        // When upgrading from pre-N MR1, verify the package time stamp using the package
8126        // directory and not the APK file.
8127        final long lastModifiedTime = mIsPreNMR1Upgrade
8128                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8129        if (ps != null
8130                && ps.codePath.equals(srcFile)
8131                && ps.timeStamp == lastModifiedTime
8132                && !isCompatSignatureUpdateNeeded(pkg)
8133                && !isRecoverSignatureUpdateNeeded(pkg)) {
8134            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8135            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
8136            ArraySet<PublicKey> signingKs;
8137            synchronized (mPackages) {
8138                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8139            }
8140            if (ps.signatures.mSignatures != null
8141                    && ps.signatures.mSignatures.length != 0
8142                    && signingKs != null) {
8143                // Optimization: reuse the existing cached certificates
8144                // if the package appears to be unchanged.
8145                pkg.mSignatures = ps.signatures.mSignatures;
8146                pkg.mSigningKeys = signingKs;
8147                return;
8148            }
8149
8150            Slog.w(TAG, "PackageSetting for " + ps.name
8151                    + " is missing signatures.  Collecting certs again to recover them.");
8152        } else {
8153            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8154        }
8155
8156        try {
8157            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8158            PackageParser.collectCertificates(pkg, parseFlags);
8159        } catch (PackageParserException e) {
8160            throw PackageManagerException.from(e);
8161        } finally {
8162            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8163        }
8164    }
8165
8166    /**
8167     *  Traces a package scan.
8168     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8169     */
8170    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8171            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8172        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8173        try {
8174            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8175        } finally {
8176            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8177        }
8178    }
8179
8180    /**
8181     *  Scans a package and returns the newly parsed package.
8182     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8183     */
8184    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8185            long currentTime, UserHandle user) throws PackageManagerException {
8186        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8187        PackageParser pp = new PackageParser();
8188        pp.setSeparateProcesses(mSeparateProcesses);
8189        pp.setOnlyCoreApps(mOnlyCore);
8190        pp.setDisplayMetrics(mMetrics);
8191        pp.setCallback(mPackageParserCallback);
8192
8193        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8194        final PackageParser.Package pkg;
8195        try {
8196            pkg = pp.parsePackage(scanFile, parseFlags);
8197        } catch (PackageParserException e) {
8198            throw PackageManagerException.from(e);
8199        } finally {
8200            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8201        }
8202
8203        // Static shared libraries have synthetic package names
8204        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8205            renameStaticSharedLibraryPackage(pkg);
8206        }
8207
8208        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8209    }
8210
8211    /**
8212     *  Scans a package and returns the newly parsed package.
8213     *  @throws PackageManagerException on a parse error.
8214     */
8215    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8216            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8217            @Nullable UserHandle user)
8218                    throws PackageManagerException {
8219        // If the package has children and this is the first dive in the function
8220        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8221        // packages (parent and children) would be successfully scanned before the
8222        // actual scan since scanning mutates internal state and we want to atomically
8223        // install the package and its children.
8224        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8225            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8226                scanFlags |= SCAN_CHECK_ONLY;
8227            }
8228        } else {
8229            scanFlags &= ~SCAN_CHECK_ONLY;
8230        }
8231
8232        // Scan the parent
8233        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
8234                scanFlags, currentTime, user);
8235
8236        // Scan the children
8237        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8238        for (int i = 0; i < childCount; i++) {
8239            PackageParser.Package childPackage = pkg.childPackages.get(i);
8240            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
8241                    currentTime, user);
8242        }
8243
8244
8245        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8246            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8247        }
8248
8249        return scannedPkg;
8250    }
8251
8252    /**
8253     *  Scans a package and returns the newly parsed package.
8254     *  @throws PackageManagerException on a parse error.
8255     */
8256    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8257            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8258            @Nullable UserHandle user)
8259                    throws PackageManagerException {
8260        PackageSetting ps = null;
8261        PackageSetting updatedPkg;
8262        // reader
8263        synchronized (mPackages) {
8264            // Look to see if we already know about this package.
8265            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8266            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8267                // This package has been renamed to its original name.  Let's
8268                // use that.
8269                ps = mSettings.getPackageLPr(oldName);
8270            }
8271            // If there was no original package, see one for the real package name.
8272            if (ps == null) {
8273                ps = mSettings.getPackageLPr(pkg.packageName);
8274            }
8275            // Check to see if this package could be hiding/updating a system
8276            // package.  Must look for it either under the original or real
8277            // package name depending on our state.
8278            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8279            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8280
8281            // If this is a package we don't know about on the system partition, we
8282            // may need to remove disabled child packages on the system partition
8283            // or may need to not add child packages if the parent apk is updated
8284            // on the data partition and no longer defines this child package.
8285            if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
8286                // If this is a parent package for an updated system app and this system
8287                // app got an OTA update which no longer defines some of the child packages
8288                // we have to prune them from the disabled system packages.
8289                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8290                if (disabledPs != null) {
8291                    final int scannedChildCount = (pkg.childPackages != null)
8292                            ? pkg.childPackages.size() : 0;
8293                    final int disabledChildCount = disabledPs.childPackageNames != null
8294                            ? disabledPs.childPackageNames.size() : 0;
8295                    for (int i = 0; i < disabledChildCount; i++) {
8296                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8297                        boolean disabledPackageAvailable = false;
8298                        for (int j = 0; j < scannedChildCount; j++) {
8299                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8300                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8301                                disabledPackageAvailable = true;
8302                                break;
8303                            }
8304                         }
8305                         if (!disabledPackageAvailable) {
8306                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8307                         }
8308                    }
8309                }
8310            }
8311        }
8312
8313        final boolean isUpdatedPkg = updatedPkg != null;
8314        final boolean isUpdatedSystemPkg = isUpdatedPkg && (scanFlags & SCAN_AS_SYSTEM) != 0;
8315        boolean isUpdatedPkgBetter = false;
8316        // First check if this is a system package that may involve an update
8317        if (isUpdatedSystemPkg) {
8318            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8319            // it needs to drop FLAG_PRIVILEGED.
8320            if (locationIsPrivileged(scanFile)) {
8321                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8322            } else {
8323                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8324            }
8325            // If new package is not located in "/oem" (e.g. due to an OTA),
8326            // it needs to drop FLAG_OEM.
8327            if (locationIsOem(scanFile)) {
8328                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8329            } else {
8330                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8331            }
8332
8333            if (ps != null && !ps.codePath.equals(scanFile)) {
8334                // The path has changed from what was last scanned...  check the
8335                // version of the new path against what we have stored to determine
8336                // what to do.
8337                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8338                if (pkg.mVersionCode <= ps.versionCode) {
8339                    // The system package has been updated and the code path does not match
8340                    // Ignore entry. Skip it.
8341                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8342                            + " ignored: updated version " + ps.versionCode
8343                            + " better than this " + pkg.mVersionCode);
8344                    if (!updatedPkg.codePath.equals(scanFile)) {
8345                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8346                                + ps.name + " changing from " + updatedPkg.codePathString
8347                                + " to " + scanFile);
8348                        updatedPkg.codePath = scanFile;
8349                        updatedPkg.codePathString = scanFile.toString();
8350                        updatedPkg.resourcePath = scanFile;
8351                        updatedPkg.resourcePathString = scanFile.toString();
8352                    }
8353                    updatedPkg.pkg = pkg;
8354                    updatedPkg.versionCode = pkg.mVersionCode;
8355
8356                    // Update the disabled system child packages to point to the package too.
8357                    final int childCount = updatedPkg.childPackageNames != null
8358                            ? updatedPkg.childPackageNames.size() : 0;
8359                    for (int i = 0; i < childCount; i++) {
8360                        String childPackageName = updatedPkg.childPackageNames.get(i);
8361                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8362                                childPackageName);
8363                        if (updatedChildPkg != null) {
8364                            updatedChildPkg.pkg = pkg;
8365                            updatedChildPkg.versionCode = pkg.mVersionCode;
8366                        }
8367                    }
8368                } else {
8369                    // The current app on the system partition is better than
8370                    // what we have updated to on the data partition; switch
8371                    // back to the system partition version.
8372                    // At this point, its safely assumed that package installation for
8373                    // apps in system partition will go through. If not there won't be a working
8374                    // version of the app
8375                    // writer
8376                    synchronized (mPackages) {
8377                        // Just remove the loaded entries from package lists.
8378                        mPackages.remove(ps.name);
8379                    }
8380
8381                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8382                            + " reverting from " + ps.codePathString
8383                            + ": new version " + pkg.mVersionCode
8384                            + " better than installed " + ps.versionCode);
8385
8386                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8387                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8388                    synchronized (mInstallLock) {
8389                        args.cleanUpResourcesLI();
8390                    }
8391                    synchronized (mPackages) {
8392                        mSettings.enableSystemPackageLPw(ps.name);
8393                    }
8394                    isUpdatedPkgBetter = true;
8395                }
8396            }
8397        }
8398
8399        String resourcePath = null;
8400        String baseResourcePath = null;
8401        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8402            if (ps != null && ps.resourcePathString != null) {
8403                resourcePath = ps.resourcePathString;
8404                baseResourcePath = ps.resourcePathString;
8405            } else {
8406                // Should not happen at all. Just log an error.
8407                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8408            }
8409        } else {
8410            resourcePath = pkg.codePath;
8411            baseResourcePath = pkg.baseCodePath;
8412        }
8413
8414        // Set application objects path explicitly.
8415        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8416        pkg.setApplicationInfoCodePath(pkg.codePath);
8417        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8418        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8419        pkg.setApplicationInfoResourcePath(resourcePath);
8420        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8421        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8422
8423        // throw an exception if we have an update to a system application, but, it's not more
8424        // recent than the package we've already scanned
8425        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8426            // Set CPU Abis to application info.
8427            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8428                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8429                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8430            } else {
8431                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8432                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8433            }
8434            pkg.mExtras = updatedPkg;
8435
8436            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8437                    + scanFile + " ignored: updated version " + ps.versionCode
8438                    + " better than this " + pkg.mVersionCode);
8439        }
8440
8441        if (isUpdatedPkg) {
8442            // updated system applications don't initially have the SCAN_AS_SYSTEM flag set
8443            scanFlags |= SCAN_AS_SYSTEM;
8444
8445            // An updated privileged application will not have the PARSE_IS_PRIVILEGED
8446            // flag set initially
8447            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8448                scanFlags |= SCAN_AS_PRIVILEGED;
8449            }
8450
8451            // An updated OEM app will not have the PARSE_IS_OEM
8452            // flag set initially
8453            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8454                scanFlags |= SCAN_AS_OEM;
8455            }
8456        }
8457
8458        // Verify certificates against what was last scanned
8459        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
8460
8461        /*
8462         * A new system app appeared, but we already had a non-system one of the
8463         * same name installed earlier.
8464         */
8465        boolean shouldHideSystemApp = false;
8466        if (!isUpdatedPkg && ps != null
8467                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8468            /*
8469             * Check to make sure the signatures match first. If they don't,
8470             * wipe the installed application and its data.
8471             */
8472            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8473                    != PackageManager.SIGNATURE_MATCH) {
8474                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8475                        + " signatures don't match existing userdata copy; removing");
8476                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8477                        "scanPackageInternalLI")) {
8478                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8479                }
8480                ps = null;
8481            } else {
8482                /*
8483                 * If the newly-added system app is an older version than the
8484                 * already installed version, hide it. It will be scanned later
8485                 * and re-added like an update.
8486                 */
8487                if (pkg.mVersionCode <= ps.versionCode) {
8488                    shouldHideSystemApp = true;
8489                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8490                            + " but new version " + pkg.mVersionCode + " better than installed "
8491                            + ps.versionCode + "; hiding system");
8492                } else {
8493                    /*
8494                     * The newly found system app is a newer version that the
8495                     * one previously installed. Simply remove the
8496                     * already-installed application and replace it with our own
8497                     * while keeping the application data.
8498                     */
8499                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8500                            + " reverting from " + ps.codePathString + ": new version "
8501                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8502                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8503                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8504                    synchronized (mInstallLock) {
8505                        args.cleanUpResourcesLI();
8506                    }
8507                }
8508            }
8509        }
8510
8511        // The apk is forward locked (not public) if its code and resources
8512        // are kept in different files. (except for app in either system or
8513        // vendor path).
8514        // TODO grab this value from PackageSettings
8515        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8516            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8517                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
8518            }
8519        }
8520
8521        final int userId = ((user == null) ? 0 : user.getIdentifier());
8522        if (ps != null && ps.getInstantApp(userId)) {
8523            scanFlags |= SCAN_AS_INSTANT_APP;
8524        }
8525        if (ps != null && ps.getVirtulalPreload(userId)) {
8526            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8527        }
8528
8529        // Note that we invoke the following method only if we are about to unpack an application
8530        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
8531                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8532
8533        /*
8534         * If the system app should be overridden by a previously installed
8535         * data, hide the system app now and let the /data/app scan pick it up
8536         * again.
8537         */
8538        if (shouldHideSystemApp) {
8539            synchronized (mPackages) {
8540                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8541            }
8542        }
8543
8544        return scannedPkg;
8545    }
8546
8547    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8548        // Derive the new package synthetic package name
8549        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8550                + pkg.staticSharedLibVersion);
8551    }
8552
8553    private static String fixProcessName(String defProcessName,
8554            String processName) {
8555        if (processName == null) {
8556            return defProcessName;
8557        }
8558        return processName;
8559    }
8560
8561    /**
8562     * Enforces that only the system UID or root's UID can call a method exposed
8563     * via Binder.
8564     *
8565     * @param message used as message if SecurityException is thrown
8566     * @throws SecurityException if the caller is not system or root
8567     */
8568    private static final void enforceSystemOrRoot(String message) {
8569        final int uid = Binder.getCallingUid();
8570        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8571            throw new SecurityException(message);
8572        }
8573    }
8574
8575    @Override
8576    public void performFstrimIfNeeded() {
8577        enforceSystemOrRoot("Only the system can request fstrim");
8578
8579        // Before everything else, see whether we need to fstrim.
8580        try {
8581            IStorageManager sm = PackageHelper.getStorageManager();
8582            if (sm != null) {
8583                boolean doTrim = false;
8584                final long interval = android.provider.Settings.Global.getLong(
8585                        mContext.getContentResolver(),
8586                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8587                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8588                if (interval > 0) {
8589                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8590                    if (timeSinceLast > interval) {
8591                        doTrim = true;
8592                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8593                                + "; running immediately");
8594                    }
8595                }
8596                if (doTrim) {
8597                    final boolean dexOptDialogShown;
8598                    synchronized (mPackages) {
8599                        dexOptDialogShown = mDexOptDialogShown;
8600                    }
8601                    if (!isFirstBoot() && dexOptDialogShown) {
8602                        try {
8603                            ActivityManager.getService().showBootMessage(
8604                                    mContext.getResources().getString(
8605                                            R.string.android_upgrading_fstrim), true);
8606                        } catch (RemoteException e) {
8607                        }
8608                    }
8609                    sm.runMaintenance();
8610                }
8611            } else {
8612                Slog.e(TAG, "storageManager service unavailable!");
8613            }
8614        } catch (RemoteException e) {
8615            // Can't happen; StorageManagerService is local
8616        }
8617    }
8618
8619    @Override
8620    public void updatePackagesIfNeeded() {
8621        enforceSystemOrRoot("Only the system can request package update");
8622
8623        // We need to re-extract after an OTA.
8624        boolean causeUpgrade = isUpgrade();
8625
8626        // First boot or factory reset.
8627        // Note: we also handle devices that are upgrading to N right now as if it is their
8628        //       first boot, as they do not have profile data.
8629        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8630
8631        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8632        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8633
8634        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8635            return;
8636        }
8637
8638        List<PackageParser.Package> pkgs;
8639        synchronized (mPackages) {
8640            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8641        }
8642
8643        final long startTime = System.nanoTime();
8644        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8645                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
8646                    false /* bootComplete */);
8647
8648        final int elapsedTimeSeconds =
8649                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8650
8651        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8652        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8653        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8654        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8655        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8656    }
8657
8658    /*
8659     * Return the prebuilt profile path given a package base code path.
8660     */
8661    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8662        return pkg.baseCodePath + ".prof";
8663    }
8664
8665    /**
8666     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8667     * containing statistics about the invocation. The array consists of three elements,
8668     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8669     * and {@code numberOfPackagesFailed}.
8670     */
8671    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8672            final String compilerFilter, boolean bootComplete) {
8673
8674        int numberOfPackagesVisited = 0;
8675        int numberOfPackagesOptimized = 0;
8676        int numberOfPackagesSkipped = 0;
8677        int numberOfPackagesFailed = 0;
8678        final int numberOfPackagesToDexopt = pkgs.size();
8679
8680        for (PackageParser.Package pkg : pkgs) {
8681            numberOfPackagesVisited++;
8682
8683            boolean useProfileForDexopt = false;
8684
8685            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8686                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8687                // that are already compiled.
8688                File profileFile = new File(getPrebuildProfilePath(pkg));
8689                // Copy profile if it exists.
8690                if (profileFile.exists()) {
8691                    try {
8692                        // We could also do this lazily before calling dexopt in
8693                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8694                        // is that we don't have a good way to say "do this only once".
8695                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8696                                pkg.applicationInfo.uid, pkg.packageName)) {
8697                            Log.e(TAG, "Installer failed to copy system profile!");
8698                        } else {
8699                            // Disabled as this causes speed-profile compilation during first boot
8700                            // even if things are already compiled.
8701                            // useProfileForDexopt = true;
8702                        }
8703                    } catch (Exception e) {
8704                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8705                                e);
8706                    }
8707                } else {
8708                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8709                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8710                    // minimize the number off apps being speed-profile compiled during first boot.
8711                    // The other paths will not change the filter.
8712                    if (disabledPs != null && disabledPs.pkg.isStub) {
8713                        // The package is the stub one, remove the stub suffix to get the normal
8714                        // package and APK names.
8715                        String systemProfilePath =
8716                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8717                        profileFile = new File(systemProfilePath);
8718                        // If we have a profile for a compressed APK, copy it to the reference
8719                        // location.
8720                        // Note that copying the profile here will cause it to override the
8721                        // reference profile every OTA even though the existing reference profile
8722                        // may have more data. We can't copy during decompression since the
8723                        // directories are not set up at that point.
8724                        if (profileFile.exists()) {
8725                            try {
8726                                // We could also do this lazily before calling dexopt in
8727                                // PackageDexOptimizer to prevent this happening on first boot. The
8728                                // issue is that we don't have a good way to say "do this only
8729                                // once".
8730                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8731                                        pkg.applicationInfo.uid, pkg.packageName)) {
8732                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8733                                } else {
8734                                    useProfileForDexopt = true;
8735                                }
8736                            } catch (Exception e) {
8737                                Log.e(TAG, "Failed to copy profile " +
8738                                        profileFile.getAbsolutePath() + " ", e);
8739                            }
8740                        }
8741                    }
8742                }
8743            }
8744
8745            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8746                if (DEBUG_DEXOPT) {
8747                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8748                }
8749                numberOfPackagesSkipped++;
8750                continue;
8751            }
8752
8753            if (DEBUG_DEXOPT) {
8754                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8755                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8756            }
8757
8758            if (showDialog) {
8759                try {
8760                    ActivityManager.getService().showBootMessage(
8761                            mContext.getResources().getString(R.string.android_upgrading_apk,
8762                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8763                } catch (RemoteException e) {
8764                }
8765                synchronized (mPackages) {
8766                    mDexOptDialogShown = true;
8767                }
8768            }
8769
8770            String pkgCompilerFilter = compilerFilter;
8771            if (useProfileForDexopt) {
8772                // Use background dexopt mode to try and use the profile. Note that this does not
8773                // guarantee usage of the profile.
8774                pkgCompilerFilter =
8775                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
8776                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
8777            }
8778
8779            // checkProfiles is false to avoid merging profiles during boot which
8780            // might interfere with background compilation (b/28612421).
8781            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8782            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8783            // trade-off worth doing to save boot time work.
8784            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
8785            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
8786                    pkg.packageName,
8787                    pkgCompilerFilter,
8788                    dexoptFlags));
8789
8790            switch (primaryDexOptStaus) {
8791                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8792                    numberOfPackagesOptimized++;
8793                    break;
8794                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8795                    numberOfPackagesSkipped++;
8796                    break;
8797                case PackageDexOptimizer.DEX_OPT_FAILED:
8798                    numberOfPackagesFailed++;
8799                    break;
8800                default:
8801                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
8802                    break;
8803            }
8804        }
8805
8806        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8807                numberOfPackagesFailed };
8808    }
8809
8810    @Override
8811    public void notifyPackageUse(String packageName, int reason) {
8812        synchronized (mPackages) {
8813            final int callingUid = Binder.getCallingUid();
8814            final int callingUserId = UserHandle.getUserId(callingUid);
8815            if (getInstantAppPackageName(callingUid) != null) {
8816                if (!isCallerSameApp(packageName, callingUid)) {
8817                    return;
8818                }
8819            } else {
8820                if (isInstantApp(packageName, callingUserId)) {
8821                    return;
8822                }
8823            }
8824            notifyPackageUseLocked(packageName, reason);
8825        }
8826    }
8827
8828    private void notifyPackageUseLocked(String packageName, int reason) {
8829        final PackageParser.Package p = mPackages.get(packageName);
8830        if (p == null) {
8831            return;
8832        }
8833        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8834    }
8835
8836    @Override
8837    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
8838            List<String> classPaths, String loaderIsa) {
8839        int userId = UserHandle.getCallingUserId();
8840        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8841        if (ai == null) {
8842            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8843                + loadingPackageName + ", user=" + userId);
8844            return;
8845        }
8846        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
8847    }
8848
8849    @Override
8850    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
8851            IDexModuleRegisterCallback callback) {
8852        int userId = UserHandle.getCallingUserId();
8853        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
8854        DexManager.RegisterDexModuleResult result;
8855        if (ai == null) {
8856            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
8857                     " calling user. package=" + packageName + ", user=" + userId);
8858            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
8859        } else {
8860            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
8861        }
8862
8863        if (callback != null) {
8864            mHandler.post(() -> {
8865                try {
8866                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
8867                } catch (RemoteException e) {
8868                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
8869                }
8870            });
8871        }
8872    }
8873
8874    /**
8875     * Ask the package manager to perform a dex-opt with the given compiler filter.
8876     *
8877     * Note: exposed only for the shell command to allow moving packages explicitly to a
8878     *       definite state.
8879     */
8880    @Override
8881    public boolean performDexOptMode(String packageName,
8882            boolean checkProfiles, String targetCompilerFilter, boolean force,
8883            boolean bootComplete, String splitName) {
8884        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
8885                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
8886                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
8887        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
8888                splitName, flags));
8889    }
8890
8891    /**
8892     * Ask the package manager to perform a dex-opt with the given compiler filter on the
8893     * secondary dex files belonging to the given package.
8894     *
8895     * Note: exposed only for the shell command to allow moving packages explicitly to a
8896     *       definite state.
8897     */
8898    @Override
8899    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8900            boolean force) {
8901        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
8902                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
8903                DexoptOptions.DEXOPT_BOOT_COMPLETE |
8904                (force ? DexoptOptions.DEXOPT_FORCE : 0);
8905        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
8906    }
8907
8908    /*package*/ boolean performDexOpt(DexoptOptions options) {
8909        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8910            return false;
8911        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
8912            return false;
8913        }
8914
8915        if (options.isDexoptOnlySecondaryDex()) {
8916            return mDexManager.dexoptSecondaryDex(options);
8917        } else {
8918            int dexoptStatus = performDexOptWithStatus(options);
8919            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8920        }
8921    }
8922
8923    /**
8924     * Perform dexopt on the given package and return one of following result:
8925     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
8926     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
8927     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
8928     */
8929    /* package */ int performDexOptWithStatus(DexoptOptions options) {
8930        return performDexOptTraced(options);
8931    }
8932
8933    private int performDexOptTraced(DexoptOptions options) {
8934        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8935        try {
8936            return performDexOptInternal(options);
8937        } finally {
8938            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8939        }
8940    }
8941
8942    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8943    // if the package can now be considered up to date for the given filter.
8944    private int performDexOptInternal(DexoptOptions options) {
8945        PackageParser.Package p;
8946        synchronized (mPackages) {
8947            p = mPackages.get(options.getPackageName());
8948            if (p == null) {
8949                // Package could not be found. Report failure.
8950                return PackageDexOptimizer.DEX_OPT_FAILED;
8951            }
8952            mPackageUsage.maybeWriteAsync(mPackages);
8953            mCompilerStats.maybeWriteAsync();
8954        }
8955        long callingId = Binder.clearCallingIdentity();
8956        try {
8957            synchronized (mInstallLock) {
8958                return performDexOptInternalWithDependenciesLI(p, options);
8959            }
8960        } finally {
8961            Binder.restoreCallingIdentity(callingId);
8962        }
8963    }
8964
8965    public ArraySet<String> getOptimizablePackages() {
8966        ArraySet<String> pkgs = new ArraySet<String>();
8967        synchronized (mPackages) {
8968            for (PackageParser.Package p : mPackages.values()) {
8969                if (PackageDexOptimizer.canOptimizePackage(p)) {
8970                    pkgs.add(p.packageName);
8971                }
8972            }
8973        }
8974        return pkgs;
8975    }
8976
8977    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8978            DexoptOptions options) {
8979        // Select the dex optimizer based on the force parameter.
8980        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8981        //       allocate an object here.
8982        PackageDexOptimizer pdo = options.isForce()
8983                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8984                : mPackageDexOptimizer;
8985
8986        // Dexopt all dependencies first. Note: we ignore the return value and march on
8987        // on errors.
8988        // Note that we are going to call performDexOpt on those libraries as many times as
8989        // they are referenced in packages. When we do a batch of performDexOpt (for example
8990        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8991        // and the first package that uses the library will dexopt it. The
8992        // others will see that the compiled code for the library is up to date.
8993        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8994        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8995        if (!deps.isEmpty()) {
8996            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
8997                    options.getCompilerFilter(), options.getSplitName(),
8998                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
8999            for (PackageParser.Package depPackage : deps) {
9000                // TODO: Analyze and investigate if we (should) profile libraries.
9001                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9002                        getOrCreateCompilerPackageStats(depPackage),
9003                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9004            }
9005        }
9006        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9007                getOrCreateCompilerPackageStats(p),
9008                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9009    }
9010
9011    /**
9012     * Reconcile the information we have about the secondary dex files belonging to
9013     * {@code packagName} and the actual dex files. For all dex files that were
9014     * deleted, update the internal records and delete the generated oat files.
9015     */
9016    @Override
9017    public void reconcileSecondaryDexFiles(String packageName) {
9018        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9019            return;
9020        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9021            return;
9022        }
9023        mDexManager.reconcileSecondaryDexFiles(packageName);
9024    }
9025
9026    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9027    // a reference there.
9028    /*package*/ DexManager getDexManager() {
9029        return mDexManager;
9030    }
9031
9032    /**
9033     * Execute the background dexopt job immediately.
9034     */
9035    @Override
9036    public boolean runBackgroundDexoptJob() {
9037        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9038            return false;
9039        }
9040        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9041    }
9042
9043    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9044        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9045                || p.usesStaticLibraries != null) {
9046            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9047            Set<String> collectedNames = new HashSet<>();
9048            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9049
9050            retValue.remove(p);
9051
9052            return retValue;
9053        } else {
9054            return Collections.emptyList();
9055        }
9056    }
9057
9058    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9059            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9060        if (!collectedNames.contains(p.packageName)) {
9061            collectedNames.add(p.packageName);
9062            collected.add(p);
9063
9064            if (p.usesLibraries != null) {
9065                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9066                        null, collected, collectedNames);
9067            }
9068            if (p.usesOptionalLibraries != null) {
9069                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9070                        null, collected, collectedNames);
9071            }
9072            if (p.usesStaticLibraries != null) {
9073                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9074                        p.usesStaticLibrariesVersions, collected, collectedNames);
9075            }
9076        }
9077    }
9078
9079    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9080            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9081        final int libNameCount = libs.size();
9082        for (int i = 0; i < libNameCount; i++) {
9083            String libName = libs.get(i);
9084            int version = (versions != null && versions.length == libNameCount)
9085                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9086            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9087            if (libPkg != null) {
9088                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9089            }
9090        }
9091    }
9092
9093    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9094        synchronized (mPackages) {
9095            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9096            if (libEntry != null) {
9097                return mPackages.get(libEntry.apk);
9098            }
9099            return null;
9100        }
9101    }
9102
9103    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9104        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9105        if (versionedLib == null) {
9106            return null;
9107        }
9108        return versionedLib.get(version);
9109    }
9110
9111    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9112        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9113                pkg.staticSharedLibName);
9114        if (versionedLib == null) {
9115            return null;
9116        }
9117        int previousLibVersion = -1;
9118        final int versionCount = versionedLib.size();
9119        for (int i = 0; i < versionCount; i++) {
9120            final int libVersion = versionedLib.keyAt(i);
9121            if (libVersion < pkg.staticSharedLibVersion) {
9122                previousLibVersion = Math.max(previousLibVersion, libVersion);
9123            }
9124        }
9125        if (previousLibVersion >= 0) {
9126            return versionedLib.get(previousLibVersion);
9127        }
9128        return null;
9129    }
9130
9131    public void shutdown() {
9132        mPackageUsage.writeNow(mPackages);
9133        mCompilerStats.writeNow();
9134        mDexManager.writePackageDexUsageNow();
9135    }
9136
9137    @Override
9138    public void dumpProfiles(String packageName) {
9139        PackageParser.Package pkg;
9140        synchronized (mPackages) {
9141            pkg = mPackages.get(packageName);
9142            if (pkg == null) {
9143                throw new IllegalArgumentException("Unknown package: " + packageName);
9144            }
9145        }
9146        /* Only the shell, root, or the app user should be able to dump profiles. */
9147        int callingUid = Binder.getCallingUid();
9148        if (callingUid != Process.SHELL_UID &&
9149            callingUid != Process.ROOT_UID &&
9150            callingUid != pkg.applicationInfo.uid) {
9151            throw new SecurityException("dumpProfiles");
9152        }
9153
9154        synchronized (mInstallLock) {
9155            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9156            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9157            try {
9158                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9159                String codePaths = TextUtils.join(";", allCodePaths);
9160                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9161            } catch (InstallerException e) {
9162                Slog.w(TAG, "Failed to dump profiles", e);
9163            }
9164            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9165        }
9166    }
9167
9168    @Override
9169    public void forceDexOpt(String packageName) {
9170        enforceSystemOrRoot("forceDexOpt");
9171
9172        PackageParser.Package pkg;
9173        synchronized (mPackages) {
9174            pkg = mPackages.get(packageName);
9175            if (pkg == null) {
9176                throw new IllegalArgumentException("Unknown package: " + packageName);
9177            }
9178        }
9179
9180        synchronized (mInstallLock) {
9181            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9182
9183            // Whoever is calling forceDexOpt wants a compiled package.
9184            // Don't use profiles since that may cause compilation to be skipped.
9185            final int res = performDexOptInternalWithDependenciesLI(
9186                    pkg,
9187                    new DexoptOptions(packageName,
9188                            getDefaultCompilerFilter(),
9189                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9190
9191            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9192            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9193                throw new IllegalStateException("Failed to dexopt: " + res);
9194            }
9195        }
9196    }
9197
9198    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9199        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9200            Slog.w(TAG, "Unable to update from " + oldPkg.name
9201                    + " to " + newPkg.packageName
9202                    + ": old package not in system partition");
9203            return false;
9204        } else if (mPackages.get(oldPkg.name) != null) {
9205            Slog.w(TAG, "Unable to update from " + oldPkg.name
9206                    + " to " + newPkg.packageName
9207                    + ": old package still exists");
9208            return false;
9209        }
9210        return true;
9211    }
9212
9213    void removeCodePathLI(File codePath) {
9214        if (codePath.isDirectory()) {
9215            try {
9216                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9217            } catch (InstallerException e) {
9218                Slog.w(TAG, "Failed to remove code path", e);
9219            }
9220        } else {
9221            codePath.delete();
9222        }
9223    }
9224
9225    private int[] resolveUserIds(int userId) {
9226        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9227    }
9228
9229    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9230        if (pkg == null) {
9231            Slog.wtf(TAG, "Package was null!", new Throwable());
9232            return;
9233        }
9234        clearAppDataLeafLIF(pkg, userId, flags);
9235        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9236        for (int i = 0; i < childCount; i++) {
9237            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9238        }
9239    }
9240
9241    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9242        final PackageSetting ps;
9243        synchronized (mPackages) {
9244            ps = mSettings.mPackages.get(pkg.packageName);
9245        }
9246        for (int realUserId : resolveUserIds(userId)) {
9247            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9248            try {
9249                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9250                        ceDataInode);
9251            } catch (InstallerException e) {
9252                Slog.w(TAG, String.valueOf(e));
9253            }
9254        }
9255    }
9256
9257    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9258        if (pkg == null) {
9259            Slog.wtf(TAG, "Package was null!", new Throwable());
9260            return;
9261        }
9262        destroyAppDataLeafLIF(pkg, userId, flags);
9263        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9264        for (int i = 0; i < childCount; i++) {
9265            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9266        }
9267    }
9268
9269    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9270        final PackageSetting ps;
9271        synchronized (mPackages) {
9272            ps = mSettings.mPackages.get(pkg.packageName);
9273        }
9274        for (int realUserId : resolveUserIds(userId)) {
9275            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9276            try {
9277                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9278                        ceDataInode);
9279            } catch (InstallerException e) {
9280                Slog.w(TAG, String.valueOf(e));
9281            }
9282            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9283        }
9284    }
9285
9286    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9287        if (pkg == null) {
9288            Slog.wtf(TAG, "Package was null!", new Throwable());
9289            return;
9290        }
9291        destroyAppProfilesLeafLIF(pkg);
9292        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9293        for (int i = 0; i < childCount; i++) {
9294            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9295        }
9296    }
9297
9298    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9299        try {
9300            mInstaller.destroyAppProfiles(pkg.packageName);
9301        } catch (InstallerException e) {
9302            Slog.w(TAG, String.valueOf(e));
9303        }
9304    }
9305
9306    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9307        if (pkg == null) {
9308            Slog.wtf(TAG, "Package was null!", new Throwable());
9309            return;
9310        }
9311        clearAppProfilesLeafLIF(pkg);
9312        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9313        for (int i = 0; i < childCount; i++) {
9314            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9315        }
9316    }
9317
9318    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9319        try {
9320            mInstaller.clearAppProfiles(pkg.packageName);
9321        } catch (InstallerException e) {
9322            Slog.w(TAG, String.valueOf(e));
9323        }
9324    }
9325
9326    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9327            long lastUpdateTime) {
9328        // Set parent install/update time
9329        PackageSetting ps = (PackageSetting) pkg.mExtras;
9330        if (ps != null) {
9331            ps.firstInstallTime = firstInstallTime;
9332            ps.lastUpdateTime = lastUpdateTime;
9333        }
9334        // Set children install/update time
9335        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9336        for (int i = 0; i < childCount; i++) {
9337            PackageParser.Package childPkg = pkg.childPackages.get(i);
9338            ps = (PackageSetting) childPkg.mExtras;
9339            if (ps != null) {
9340                ps.firstInstallTime = firstInstallTime;
9341                ps.lastUpdateTime = lastUpdateTime;
9342            }
9343        }
9344    }
9345
9346    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9347            SharedLibraryEntry file,
9348            PackageParser.Package changingLib) {
9349        if (file.path != null) {
9350            usesLibraryFiles.add(file.path);
9351            return;
9352        }
9353        PackageParser.Package p = mPackages.get(file.apk);
9354        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9355            // If we are doing this while in the middle of updating a library apk,
9356            // then we need to make sure to use that new apk for determining the
9357            // dependencies here.  (We haven't yet finished committing the new apk
9358            // to the package manager state.)
9359            if (p == null || p.packageName.equals(changingLib.packageName)) {
9360                p = changingLib;
9361            }
9362        }
9363        if (p != null) {
9364            usesLibraryFiles.addAll(p.getAllCodePaths());
9365            if (p.usesLibraryFiles != null) {
9366                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9367            }
9368        }
9369    }
9370
9371    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9372            PackageParser.Package changingLib) throws PackageManagerException {
9373        if (pkg == null) {
9374            return;
9375        }
9376        // The collection used here must maintain the order of addition (so
9377        // that libraries are searched in the correct order) and must have no
9378        // duplicates.
9379        Set<String> usesLibraryFiles = null;
9380        if (pkg.usesLibraries != null) {
9381            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9382                    null, null, pkg.packageName, changingLib, true,
9383                    pkg.applicationInfo.targetSdkVersion, null);
9384        }
9385        if (pkg.usesStaticLibraries != null) {
9386            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9387                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9388                    pkg.packageName, changingLib, true,
9389                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9390        }
9391        if (pkg.usesOptionalLibraries != null) {
9392            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9393                    null, null, pkg.packageName, changingLib, false,
9394                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9395        }
9396        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9397            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9398        } else {
9399            pkg.usesLibraryFiles = null;
9400        }
9401    }
9402
9403    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9404            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9405            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9406            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9407            throws PackageManagerException {
9408        final int libCount = requestedLibraries.size();
9409        for (int i = 0; i < libCount; i++) {
9410            final String libName = requestedLibraries.get(i);
9411            final int libVersion = requiredVersions != null ? requiredVersions[i]
9412                    : SharedLibraryInfo.VERSION_UNDEFINED;
9413            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9414            if (libEntry == null) {
9415                if (required) {
9416                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9417                            "Package " + packageName + " requires unavailable shared library "
9418                                    + libName + "; failing!");
9419                } else if (DEBUG_SHARED_LIBRARIES) {
9420                    Slog.i(TAG, "Package " + packageName
9421                            + " desires unavailable shared library "
9422                            + libName + "; ignoring!");
9423                }
9424            } else {
9425                if (requiredVersions != null && requiredCertDigests != null) {
9426                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9427                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9428                            "Package " + packageName + " requires unavailable static shared"
9429                                    + " library " + libName + " version "
9430                                    + libEntry.info.getVersion() + "; failing!");
9431                    }
9432
9433                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9434                    if (libPkg == null) {
9435                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9436                                "Package " + packageName + " requires unavailable static shared"
9437                                        + " library; failing!");
9438                    }
9439
9440                    final String[] expectedCertDigests = requiredCertDigests[i];
9441                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9442                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9443                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9444                            : PackageUtils.computeSignaturesSha256Digests(
9445                                    new Signature[]{libPkg.mSignatures[0]});
9446
9447                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9448                    // target O we don't parse the "additional-certificate" tags similarly
9449                    // how we only consider all certs only for apps targeting O (see above).
9450                    // Therefore, the size check is safe to make.
9451                    if (expectedCertDigests.length != libCertDigests.length) {
9452                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9453                                "Package " + packageName + " requires differently signed" +
9454                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9455                    }
9456
9457                    // Use a predictable order as signature order may vary
9458                    Arrays.sort(libCertDigests);
9459                    Arrays.sort(expectedCertDigests);
9460
9461                    final int certCount = libCertDigests.length;
9462                    for (int j = 0; j < certCount; j++) {
9463                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9464                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9465                                    "Package " + packageName + " requires differently signed" +
9466                                            " static shared library; failing!");
9467                        }
9468                    }
9469                }
9470
9471                if (outUsedLibraries == null) {
9472                    // Use LinkedHashSet to preserve the order of files added to
9473                    // usesLibraryFiles while eliminating duplicates.
9474                    outUsedLibraries = new LinkedHashSet<>();
9475                }
9476                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9477            }
9478        }
9479        return outUsedLibraries;
9480    }
9481
9482    private static boolean hasString(List<String> list, List<String> which) {
9483        if (list == null) {
9484            return false;
9485        }
9486        for (int i=list.size()-1; i>=0; i--) {
9487            for (int j=which.size()-1; j>=0; j--) {
9488                if (which.get(j).equals(list.get(i))) {
9489                    return true;
9490                }
9491            }
9492        }
9493        return false;
9494    }
9495
9496    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9497            PackageParser.Package changingPkg) {
9498        ArrayList<PackageParser.Package> res = null;
9499        for (PackageParser.Package pkg : mPackages.values()) {
9500            if (changingPkg != null
9501                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9502                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9503                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9504                            changingPkg.staticSharedLibName)) {
9505                return null;
9506            }
9507            if (res == null) {
9508                res = new ArrayList<>();
9509            }
9510            res.add(pkg);
9511            try {
9512                updateSharedLibrariesLPr(pkg, changingPkg);
9513            } catch (PackageManagerException e) {
9514                // If a system app update or an app and a required lib missing we
9515                // delete the package and for updated system apps keep the data as
9516                // it is better for the user to reinstall than to be in an limbo
9517                // state. Also libs disappearing under an app should never happen
9518                // - just in case.
9519                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9520                    final int flags = pkg.isUpdatedSystemApp()
9521                            ? PackageManager.DELETE_KEEP_DATA : 0;
9522                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9523                            flags , null, true, null);
9524                }
9525                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9526            }
9527        }
9528        return res;
9529    }
9530
9531    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9532            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9533            @Nullable UserHandle user) throws PackageManagerException {
9534        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9535        // If the package has children and this is the first dive in the function
9536        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9537        // whether all packages (parent and children) would be successfully scanned
9538        // before the actual scan since scanning mutates internal state and we want
9539        // to atomically install the package and its children.
9540        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9541            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9542                scanFlags |= SCAN_CHECK_ONLY;
9543            }
9544        } else {
9545            scanFlags &= ~SCAN_CHECK_ONLY;
9546        }
9547
9548        final PackageParser.Package scannedPkg;
9549        try {
9550            // Scan the parent
9551            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
9552            // Scan the children
9553            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9554            for (int i = 0; i < childCount; i++) {
9555                PackageParser.Package childPkg = pkg.childPackages.get(i);
9556                scanPackageLI(childPkg, parseFlags,
9557                        scanFlags, currentTime, user);
9558            }
9559        } finally {
9560            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9561        }
9562
9563        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9564            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9565        }
9566
9567        return scannedPkg;
9568    }
9569
9570    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
9571            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9572            @Nullable UserHandle user) throws PackageManagerException {
9573        boolean success = false;
9574        try {
9575            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
9576                    currentTime, user);
9577            success = true;
9578            return res;
9579        } finally {
9580            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9581                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9582                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9583                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9584                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9585            }
9586        }
9587    }
9588
9589    /**
9590     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9591     */
9592    private static boolean apkHasCode(String fileName) {
9593        StrictJarFile jarFile = null;
9594        try {
9595            jarFile = new StrictJarFile(fileName,
9596                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9597            return jarFile.findEntry("classes.dex") != null;
9598        } catch (IOException ignore) {
9599        } finally {
9600            try {
9601                if (jarFile != null) {
9602                    jarFile.close();
9603                }
9604            } catch (IOException ignore) {}
9605        }
9606        return false;
9607    }
9608
9609    /**
9610     * Enforces code policy for the package. This ensures that if an APK has
9611     * declared hasCode="true" in its manifest that the APK actually contains
9612     * code.
9613     *
9614     * @throws PackageManagerException If bytecode could not be found when it should exist
9615     */
9616    private static void assertCodePolicy(PackageParser.Package pkg)
9617            throws PackageManagerException {
9618        final boolean shouldHaveCode =
9619                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9620        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9621            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9622                    "Package " + pkg.baseCodePath + " code is missing");
9623        }
9624
9625        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9626            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9627                final boolean splitShouldHaveCode =
9628                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9629                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9630                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9631                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9632                }
9633            }
9634        }
9635    }
9636
9637    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9638            final @ParseFlags int parseFlags, final @ScanFlags int scanFlags, long currentTime,
9639            @Nullable UserHandle user)
9640                    throws PackageManagerException {
9641        if (DEBUG_PACKAGE_SCANNING) {
9642            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9643                Log.d(TAG, "Scanning package " + pkg.packageName);
9644        }
9645
9646        applyPolicy(pkg, parseFlags, scanFlags);
9647
9648        assertPackageIsValid(pkg, parseFlags, scanFlags);
9649
9650        if (Build.IS_DEBUGGABLE &&
9651                pkg.isPrivileged() &&
9652                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
9653            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
9654        }
9655
9656        // Initialize package source and resource directories
9657        final File scanFile = new File(pkg.codePath);
9658        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9659        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9660
9661        SharedUserSetting suid = null;
9662        PackageSetting pkgSetting = null;
9663
9664        // Getting the package setting may have a side-effect, so if we
9665        // are only checking if scan would succeed, stash a copy of the
9666        // old setting to restore at the end.
9667        PackageSetting nonMutatedPs = null;
9668
9669        // We keep references to the derived CPU Abis from settings in oder to reuse
9670        // them in the case where we're not upgrading or booting for the first time.
9671        String primaryCpuAbiFromSettings = null;
9672        String secondaryCpuAbiFromSettings = null;
9673
9674        // writer
9675        synchronized (mPackages) {
9676            if (pkg.mSharedUserId != null) {
9677                // SIDE EFFECTS; may potentially allocate a new shared user
9678                suid = mSettings.getSharedUserLPw(
9679                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9680                if (DEBUG_PACKAGE_SCANNING) {
9681                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9682                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9683                                + "): packages=" + suid.packages);
9684                }
9685            }
9686
9687            // Check if we are renaming from an original package name.
9688            PackageSetting origPackage = null;
9689            String realName = null;
9690            if (pkg.mOriginalPackages != null) {
9691                // This package may need to be renamed to a previously
9692                // installed name.  Let's check on that...
9693                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9694                if (pkg.mOriginalPackages.contains(renamed)) {
9695                    // This package had originally been installed as the
9696                    // original name, and we have already taken care of
9697                    // transitioning to the new one.  Just update the new
9698                    // one to continue using the old name.
9699                    realName = pkg.mRealPackage;
9700                    if (!pkg.packageName.equals(renamed)) {
9701                        // Callers into this function may have already taken
9702                        // care of renaming the package; only do it here if
9703                        // it is not already done.
9704                        pkg.setPackageName(renamed);
9705                    }
9706                } else {
9707                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9708                        if ((origPackage = mSettings.getPackageLPr(
9709                                pkg.mOriginalPackages.get(i))) != null) {
9710                            // We do have the package already installed under its
9711                            // original name...  should we use it?
9712                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9713                                // New package is not compatible with original.
9714                                origPackage = null;
9715                                continue;
9716                            } else if (origPackage.sharedUser != null) {
9717                                // Make sure uid is compatible between packages.
9718                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9719                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9720                                            + " to " + pkg.packageName + ": old uid "
9721                                            + origPackage.sharedUser.name
9722                                            + " differs from " + pkg.mSharedUserId);
9723                                    origPackage = null;
9724                                    continue;
9725                                }
9726                                // TODO: Add case when shared user id is added [b/28144775]
9727                            } else {
9728                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9729                                        + pkg.packageName + " to old name " + origPackage.name);
9730                            }
9731                            break;
9732                        }
9733                    }
9734                }
9735            }
9736
9737            if (mTransferedPackages.contains(pkg.packageName)) {
9738                Slog.w(TAG, "Package " + pkg.packageName
9739                        + " was transferred to another, but its .apk remains");
9740            }
9741
9742            // See comments in nonMutatedPs declaration
9743            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9744                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9745                if (foundPs != null) {
9746                    nonMutatedPs = new PackageSetting(foundPs);
9747                }
9748            }
9749
9750            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9751                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9752                if (foundPs != null) {
9753                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9754                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9755                }
9756            }
9757
9758            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9759            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9760                PackageManagerService.reportSettingsProblem(Log.WARN,
9761                        "Package " + pkg.packageName + " shared user changed from "
9762                                + (pkgSetting.sharedUser != null
9763                                        ? pkgSetting.sharedUser.name : "<nothing>")
9764                                + " to "
9765                                + (suid != null ? suid.name : "<nothing>")
9766                                + "; replacing with new");
9767                pkgSetting = null;
9768            }
9769            final PackageSetting oldPkgSetting =
9770                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9771            final PackageSetting disabledPkgSetting =
9772                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9773
9774            String[] usesStaticLibraries = null;
9775            if (pkg.usesStaticLibraries != null) {
9776                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9777                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9778            }
9779
9780            if (pkgSetting == null) {
9781                final String parentPackageName = (pkg.parentPackage != null)
9782                        ? pkg.parentPackage.packageName : null;
9783                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9784                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
9785                // REMOVE SharedUserSetting from method; update in a separate call
9786                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9787                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9788                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9789                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9790                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9791                        true /*allowInstall*/, instantApp, virtualPreload,
9792                        parentPackageName, pkg.getChildPackageNames(),
9793                        UserManagerService.getInstance(), usesStaticLibraries,
9794                        pkg.usesStaticLibrariesVersions);
9795                // SIDE EFFECTS; updates system state; move elsewhere
9796                if (origPackage != null) {
9797                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9798                }
9799                mSettings.addUserToSettingLPw(pkgSetting);
9800            } else {
9801                // REMOVE SharedUserSetting from method; update in a separate call.
9802                //
9803                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9804                // secondaryCpuAbi are not known at this point so we always update them
9805                // to null here, only to reset them at a later point.
9806                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9807                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9808                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9809                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9810                        UserManagerService.getInstance(), usesStaticLibraries,
9811                        pkg.usesStaticLibrariesVersions);
9812            }
9813            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9814            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9815
9816            // SIDE EFFECTS; modifies system state; move elsewhere
9817            if (pkgSetting.origPackage != null) {
9818                // If we are first transitioning from an original package,
9819                // fix up the new package's name now.  We need to do this after
9820                // looking up the package under its new name, so getPackageLP
9821                // can take care of fiddling things correctly.
9822                pkg.setPackageName(origPackage.name);
9823
9824                // File a report about this.
9825                String msg = "New package " + pkgSetting.realName
9826                        + " renamed to replace old package " + pkgSetting.name;
9827                reportSettingsProblem(Log.WARN, msg);
9828
9829                // Make a note of it.
9830                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9831                    mTransferedPackages.add(origPackage.name);
9832                }
9833
9834                // No longer need to retain this.
9835                pkgSetting.origPackage = null;
9836            }
9837
9838            // SIDE EFFECTS; modifies system state; move elsewhere
9839            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9840                // Make a note of it.
9841                mTransferedPackages.add(pkg.packageName);
9842            }
9843
9844            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9845                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9846            }
9847
9848            if ((scanFlags & SCAN_BOOTING) == 0
9849                    && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9850                // Check all shared libraries and map to their actual file path.
9851                // We only do this here for apps not on a system dir, because those
9852                // are the only ones that can fail an install due to this.  We
9853                // will take care of the system apps by updating all of their
9854                // library paths after the scan is done. Also during the initial
9855                // scan don't update any libs as we do this wholesale after all
9856                // apps are scanned to avoid dependency based scanning.
9857                updateSharedLibrariesLPr(pkg, null);
9858            }
9859
9860            if (mFoundPolicyFile) {
9861                SELinuxMMAC.assignSeInfoValue(pkg);
9862            }
9863            pkg.applicationInfo.uid = pkgSetting.appId;
9864            pkg.mExtras = pkgSetting;
9865
9866
9867            // Static shared libs have same package with different versions where
9868            // we internally use a synthetic package name to allow multiple versions
9869            // of the same package, therefore we need to compare signatures against
9870            // the package setting for the latest library version.
9871            PackageSetting signatureCheckPs = pkgSetting;
9872            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9873                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9874                if (libraryEntry != null) {
9875                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9876                }
9877            }
9878
9879            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
9880            if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
9881                if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
9882                    // We just determined the app is signed correctly, so bring
9883                    // over the latest parsed certs.
9884                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9885                } else {
9886                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9887                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9888                                "Package " + pkg.packageName + " upgrade keys do not match the "
9889                                + "previously installed version");
9890                    } else {
9891                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9892                        String msg = "System package " + pkg.packageName
9893                                + " signature changed; retaining data.";
9894                        reportSettingsProblem(Log.WARN, msg);
9895                    }
9896                }
9897            } else {
9898                try {
9899                    final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
9900                    final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
9901                    final boolean compatMatch = verifySignatures(signatureCheckPs, pkg.mSignatures,
9902                            compareCompat, compareRecover);
9903                    // The new KeySets will be re-added later in the scanning process.
9904                    if (compatMatch) {
9905                        synchronized (mPackages) {
9906                            ksms.removeAppKeySetDataLPw(pkg.packageName);
9907                        }
9908                    }
9909                    // We just determined the app is signed correctly, so bring
9910                    // over the latest parsed certs.
9911                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9912                } catch (PackageManagerException e) {
9913                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9914                        throw e;
9915                    }
9916                    // The signature has changed, but this package is in the system
9917                    // image...  let's recover!
9918                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9919                    // However...  if this package is part of a shared user, but it
9920                    // doesn't match the signature of the shared user, let's fail.
9921                    // What this means is that you can't change the signatures
9922                    // associated with an overall shared user, which doesn't seem all
9923                    // that unreasonable.
9924                    if (signatureCheckPs.sharedUser != null) {
9925                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9926                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9927                            throw new PackageManagerException(
9928                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9929                                    "Signature mismatch for shared user: "
9930                                            + pkgSetting.sharedUser);
9931                        }
9932                    }
9933                    // File a report about this.
9934                    String msg = "System package " + pkg.packageName
9935                            + " signature changed; retaining data.";
9936                    reportSettingsProblem(Log.WARN, msg);
9937                }
9938            }
9939
9940            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9941                // This package wants to adopt ownership of permissions from
9942                // another package.
9943                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9944                    final String origName = pkg.mAdoptPermissions.get(i);
9945                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9946                    if (orig != null) {
9947                        if (verifyPackageUpdateLPr(orig, pkg)) {
9948                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9949                                    + pkg.packageName);
9950                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9951                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
9952                        }
9953                    }
9954                }
9955            }
9956        }
9957
9958        pkg.applicationInfo.processName = fixProcessName(
9959                pkg.applicationInfo.packageName,
9960                pkg.applicationInfo.processName);
9961
9962        if (pkg != mPlatformPackage) {
9963            // Get all of our default paths setup
9964            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9965        }
9966
9967        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9968
9969        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9970            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9971                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9972                final boolean extractNativeLibs = !pkg.isLibrary();
9973                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
9974                        mAppLib32InstallDir);
9975                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9976
9977                // Some system apps still use directory structure for native libraries
9978                // in which case we might end up not detecting abi solely based on apk
9979                // structure. Try to detect abi based on directory structure.
9980                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9981                        pkg.applicationInfo.primaryCpuAbi == null) {
9982                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9983                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9984                }
9985            } else {
9986                // This is not a first boot or an upgrade, don't bother deriving the
9987                // ABI during the scan. Instead, trust the value that was stored in the
9988                // package setting.
9989                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9990                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9991
9992                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9993
9994                if (DEBUG_ABI_SELECTION) {
9995                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9996                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9997                        pkg.applicationInfo.secondaryCpuAbi);
9998                }
9999            }
10000        } else {
10001            if ((scanFlags & SCAN_MOVE) != 0) {
10002                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10003                // but we already have this packages package info in the PackageSetting. We just
10004                // use that and derive the native library path based on the new codepath.
10005                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10006                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10007            }
10008
10009            // Set native library paths again. For moves, the path will be updated based on the
10010            // ABIs we've determined above. For non-moves, the path will be updated based on the
10011            // ABIs we determined during compilation, but the path will depend on the final
10012            // package path (after the rename away from the stage path).
10013            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10014        }
10015
10016        // This is a special case for the "system" package, where the ABI is
10017        // dictated by the zygote configuration (and init.rc). We should keep track
10018        // of this ABI so that we can deal with "normal" applications that run under
10019        // the same UID correctly.
10020        if (mPlatformPackage == pkg) {
10021            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10022                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10023        }
10024
10025        // If there's a mismatch between the abi-override in the package setting
10026        // and the abiOverride specified for the install. Warn about this because we
10027        // would've already compiled the app without taking the package setting into
10028        // account.
10029        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10030            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10031                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10032                        " for package " + pkg.packageName);
10033            }
10034        }
10035
10036        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10037        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10038        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10039
10040        // Copy the derived override back to the parsed package, so that we can
10041        // update the package settings accordingly.
10042        pkg.cpuAbiOverride = cpuAbiOverride;
10043
10044        if (DEBUG_ABI_SELECTION) {
10045            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10046                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10047                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10048        }
10049
10050        // Push the derived path down into PackageSettings so we know what to
10051        // clean up at uninstall time.
10052        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10053
10054        if (DEBUG_ABI_SELECTION) {
10055            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10056                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10057                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10058        }
10059
10060        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10061        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10062            // We don't do this here during boot because we can do it all
10063            // at once after scanning all existing packages.
10064            //
10065            // We also do this *before* we perform dexopt on this package, so that
10066            // we can avoid redundant dexopts, and also to make sure we've got the
10067            // code and package path correct.
10068            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10069        }
10070
10071        if (mFactoryTest && pkg.requestedPermissions.contains(
10072                android.Manifest.permission.FACTORY_TEST)) {
10073            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10074        }
10075
10076        if (isSystemApp(pkg)) {
10077            pkgSetting.isOrphaned = true;
10078        }
10079
10080        // Take care of first install / last update times.
10081        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10082        if (currentTime != 0) {
10083            if (pkgSetting.firstInstallTime == 0) {
10084                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10085            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10086                pkgSetting.lastUpdateTime = currentTime;
10087            }
10088        } else if (pkgSetting.firstInstallTime == 0) {
10089            // We need *something*.  Take time time stamp of the file.
10090            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10091        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10092            if (scanFileTime != pkgSetting.timeStamp) {
10093                // A package on the system image has changed; consider this
10094                // to be an update.
10095                pkgSetting.lastUpdateTime = scanFileTime;
10096            }
10097        }
10098        pkgSetting.setTimeStamp(scanFileTime);
10099
10100        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10101            if (nonMutatedPs != null) {
10102                synchronized (mPackages) {
10103                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10104                }
10105            }
10106        } else {
10107            final int userId = user == null ? 0 : user.getIdentifier();
10108            // Modify state for the given package setting
10109            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10110                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10111            if (pkgSetting.getInstantApp(userId)) {
10112                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10113            }
10114        }
10115        return pkg;
10116    }
10117
10118    /**
10119     * Applies policy to the parsed package based upon the given policy flags.
10120     * Ensures the package is in a good state.
10121     * <p>
10122     * Implementation detail: This method must NOT have any side effect. It would
10123     * ideally be static, but, it requires locks to read system state.
10124     */
10125    private void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10126            final @ScanFlags int scanFlags) {
10127        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10128            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10129            if (pkg.applicationInfo.isDirectBootAware()) {
10130                // we're direct boot aware; set for all components
10131                for (PackageParser.Service s : pkg.services) {
10132                    s.info.encryptionAware = s.info.directBootAware = true;
10133                }
10134                for (PackageParser.Provider p : pkg.providers) {
10135                    p.info.encryptionAware = p.info.directBootAware = true;
10136                }
10137                for (PackageParser.Activity a : pkg.activities) {
10138                    a.info.encryptionAware = a.info.directBootAware = true;
10139                }
10140                for (PackageParser.Activity r : pkg.receivers) {
10141                    r.info.encryptionAware = r.info.directBootAware = true;
10142                }
10143            }
10144            if (compressedFileExists(pkg.codePath)) {
10145                pkg.isStub = true;
10146            }
10147        } else {
10148            // non system apps can't be flagged as core
10149            pkg.coreApp = false;
10150            // clear flags not applicable to regular apps
10151            pkg.applicationInfo.flags &=
10152                    ~ApplicationInfo.FLAG_PERSISTENT;
10153            pkg.applicationInfo.privateFlags &=
10154                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10155            pkg.applicationInfo.privateFlags &=
10156                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10157            // clear protected broadcasts
10158            pkg.protectedBroadcasts = null;
10159            // cap permission priorities
10160            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10161                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10162                    pkg.permissionGroups.get(i).info.priority = 0;
10163                }
10164            }
10165        }
10166        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10167            // ignore export request for single user receivers
10168            if (pkg.receivers != null) {
10169                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10170                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10171                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10172                        receiver.info.exported = false;
10173                    }
10174                }
10175            }
10176            // ignore export request for single user services
10177            if (pkg.services != null) {
10178                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10179                    final PackageParser.Service service = pkg.services.get(i);
10180                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10181                        service.info.exported = false;
10182                    }
10183                }
10184            }
10185            // ignore export request for single user providers
10186            if (pkg.providers != null) {
10187                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10188                    final PackageParser.Provider provider = pkg.providers.get(i);
10189                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10190                        provider.info.exported = false;
10191                    }
10192                }
10193            }
10194        }
10195        pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0;
10196
10197        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10198            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10199        }
10200
10201        if ((scanFlags & SCAN_AS_OEM) != 0) {
10202            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10203        }
10204
10205        if (!isSystemApp(pkg)) {
10206            // Only system apps can use these features.
10207            pkg.mOriginalPackages = null;
10208            pkg.mRealPackage = null;
10209            pkg.mAdoptPermissions = null;
10210        }
10211    }
10212
10213    /**
10214     * Asserts the parsed package is valid according to the given policy. If the
10215     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10216     * <p>
10217     * Implementation detail: This method must NOT have any side effects. It would
10218     * ideally be static, but, it requires locks to read system state.
10219     *
10220     * @throws PackageManagerException If the package fails any of the validation checks
10221     */
10222    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10223            final @ScanFlags int scanFlags)
10224                    throws PackageManagerException {
10225        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10226            assertCodePolicy(pkg);
10227        }
10228
10229        if (pkg.applicationInfo.getCodePath() == null ||
10230                pkg.applicationInfo.getResourcePath() == null) {
10231            // Bail out. The resource and code paths haven't been set.
10232            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10233                    "Code and resource paths haven't been set correctly");
10234        }
10235
10236        // Make sure we're not adding any bogus keyset info
10237        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10238        ksms.assertScannedPackageValid(pkg);
10239
10240        synchronized (mPackages) {
10241            // The special "android" package can only be defined once
10242            if (pkg.packageName.equals("android")) {
10243                if (mAndroidApplication != null) {
10244                    Slog.w(TAG, "*************************************************");
10245                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10246                    Slog.w(TAG, " codePath=" + pkg.codePath);
10247                    Slog.w(TAG, "*************************************************");
10248                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10249                            "Core android package being redefined.  Skipping.");
10250                }
10251            }
10252
10253            // A package name must be unique; don't allow duplicates
10254            if (mPackages.containsKey(pkg.packageName)) {
10255                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10256                        "Application package " + pkg.packageName
10257                        + " already installed.  Skipping duplicate.");
10258            }
10259
10260            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10261                // Static libs have a synthetic package name containing the version
10262                // but we still want the base name to be unique.
10263                if (mPackages.containsKey(pkg.manifestPackageName)) {
10264                    throw new PackageManagerException(
10265                            "Duplicate static shared lib provider package");
10266                }
10267
10268                // Static shared libraries should have at least O target SDK
10269                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10270                    throw new PackageManagerException(
10271                            "Packages declaring static-shared libs must target O SDK or higher");
10272                }
10273
10274                // Package declaring static a shared lib cannot be instant apps
10275                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10276                    throw new PackageManagerException(
10277                            "Packages declaring static-shared libs cannot be instant apps");
10278                }
10279
10280                // Package declaring static a shared lib cannot be renamed since the package
10281                // name is synthetic and apps can't code around package manager internals.
10282                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10283                    throw new PackageManagerException(
10284                            "Packages declaring static-shared libs cannot be renamed");
10285                }
10286
10287                // Package declaring static a shared lib cannot declare child packages
10288                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10289                    throw new PackageManagerException(
10290                            "Packages declaring static-shared libs cannot have child packages");
10291                }
10292
10293                // Package declaring static a shared lib cannot declare dynamic libs
10294                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10295                    throw new PackageManagerException(
10296                            "Packages declaring static-shared libs cannot declare dynamic libs");
10297                }
10298
10299                // Package declaring static a shared lib cannot declare shared users
10300                if (pkg.mSharedUserId != null) {
10301                    throw new PackageManagerException(
10302                            "Packages declaring static-shared libs cannot declare shared users");
10303                }
10304
10305                // Static shared libs cannot declare activities
10306                if (!pkg.activities.isEmpty()) {
10307                    throw new PackageManagerException(
10308                            "Static shared libs cannot declare activities");
10309                }
10310
10311                // Static shared libs cannot declare services
10312                if (!pkg.services.isEmpty()) {
10313                    throw new PackageManagerException(
10314                            "Static shared libs cannot declare services");
10315                }
10316
10317                // Static shared libs cannot declare providers
10318                if (!pkg.providers.isEmpty()) {
10319                    throw new PackageManagerException(
10320                            "Static shared libs cannot declare content providers");
10321                }
10322
10323                // Static shared libs cannot declare receivers
10324                if (!pkg.receivers.isEmpty()) {
10325                    throw new PackageManagerException(
10326                            "Static shared libs cannot declare broadcast receivers");
10327                }
10328
10329                // Static shared libs cannot declare permission groups
10330                if (!pkg.permissionGroups.isEmpty()) {
10331                    throw new PackageManagerException(
10332                            "Static shared libs cannot declare permission groups");
10333                }
10334
10335                // Static shared libs cannot declare permissions
10336                if (!pkg.permissions.isEmpty()) {
10337                    throw new PackageManagerException(
10338                            "Static shared libs cannot declare permissions");
10339                }
10340
10341                // Static shared libs cannot declare protected broadcasts
10342                if (pkg.protectedBroadcasts != null) {
10343                    throw new PackageManagerException(
10344                            "Static shared libs cannot declare protected broadcasts");
10345                }
10346
10347                // Static shared libs cannot be overlay targets
10348                if (pkg.mOverlayTarget != null) {
10349                    throw new PackageManagerException(
10350                            "Static shared libs cannot be overlay targets");
10351                }
10352
10353                // The version codes must be ordered as lib versions
10354                int minVersionCode = Integer.MIN_VALUE;
10355                int maxVersionCode = Integer.MAX_VALUE;
10356
10357                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10358                        pkg.staticSharedLibName);
10359                if (versionedLib != null) {
10360                    final int versionCount = versionedLib.size();
10361                    for (int i = 0; i < versionCount; i++) {
10362                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10363                        final int libVersionCode = libInfo.getDeclaringPackage()
10364                                .getVersionCode();
10365                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10366                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10367                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10368                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10369                        } else {
10370                            minVersionCode = maxVersionCode = libVersionCode;
10371                            break;
10372                        }
10373                    }
10374                }
10375                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10376                    throw new PackageManagerException("Static shared"
10377                            + " lib version codes must be ordered as lib versions");
10378                }
10379            }
10380
10381            // Only privileged apps and updated privileged apps can add child packages.
10382            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10383                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10384                    throw new PackageManagerException("Only privileged apps can add child "
10385                            + "packages. Ignoring package " + pkg.packageName);
10386                }
10387                final int childCount = pkg.childPackages.size();
10388                for (int i = 0; i < childCount; i++) {
10389                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10390                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10391                            childPkg.packageName)) {
10392                        throw new PackageManagerException("Can't override child of "
10393                                + "another disabled app. Ignoring package " + pkg.packageName);
10394                    }
10395                }
10396            }
10397
10398            // If we're only installing presumed-existing packages, require that the
10399            // scanned APK is both already known and at the path previously established
10400            // for it.  Previously unknown packages we pick up normally, but if we have an
10401            // a priori expectation about this package's install presence, enforce it.
10402            // With a singular exception for new system packages. When an OTA contains
10403            // a new system package, we allow the codepath to change from a system location
10404            // to the user-installed location. If we don't allow this change, any newer,
10405            // user-installed version of the application will be ignored.
10406            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10407                if (mExpectingBetter.containsKey(pkg.packageName)) {
10408                    logCriticalInfo(Log.WARN,
10409                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10410                } else {
10411                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10412                    if (known != null) {
10413                        if (DEBUG_PACKAGE_SCANNING) {
10414                            Log.d(TAG, "Examining " + pkg.codePath
10415                                    + " and requiring known paths " + known.codePathString
10416                                    + " & " + known.resourcePathString);
10417                        }
10418                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10419                                || !pkg.applicationInfo.getResourcePath().equals(
10420                                        known.resourcePathString)) {
10421                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10422                                    "Application package " + pkg.packageName
10423                                    + " found at " + pkg.applicationInfo.getCodePath()
10424                                    + " but expected at " + known.codePathString
10425                                    + "; ignoring.");
10426                        }
10427                    } else {
10428                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10429                                "Application package " + pkg.packageName
10430                                + " not found; ignoring.");
10431                    }
10432                }
10433            }
10434
10435            // Verify that this new package doesn't have any content providers
10436            // that conflict with existing packages.  Only do this if the
10437            // package isn't already installed, since we don't want to break
10438            // things that are installed.
10439            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10440                final int N = pkg.providers.size();
10441                int i;
10442                for (i=0; i<N; i++) {
10443                    PackageParser.Provider p = pkg.providers.get(i);
10444                    if (p.info.authority != null) {
10445                        String names[] = p.info.authority.split(";");
10446                        for (int j = 0; j < names.length; j++) {
10447                            if (mProvidersByAuthority.containsKey(names[j])) {
10448                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10449                                final String otherPackageName =
10450                                        ((other != null && other.getComponentName() != null) ?
10451                                                other.getComponentName().getPackageName() : "?");
10452                                throw new PackageManagerException(
10453                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10454                                        "Can't install because provider name " + names[j]
10455                                                + " (in package " + pkg.applicationInfo.packageName
10456                                                + ") is already used by " + otherPackageName);
10457                            }
10458                        }
10459                    }
10460                }
10461            }
10462        }
10463    }
10464
10465    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10466            int type, String declaringPackageName, int declaringVersionCode) {
10467        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10468        if (versionedLib == null) {
10469            versionedLib = new SparseArray<>();
10470            mSharedLibraries.put(name, versionedLib);
10471            if (type == SharedLibraryInfo.TYPE_STATIC) {
10472                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10473            }
10474        } else if (versionedLib.indexOfKey(version) >= 0) {
10475            return false;
10476        }
10477        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10478                version, type, declaringPackageName, declaringVersionCode);
10479        versionedLib.put(version, libEntry);
10480        return true;
10481    }
10482
10483    private boolean removeSharedLibraryLPw(String name, int version) {
10484        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10485        if (versionedLib == null) {
10486            return false;
10487        }
10488        final int libIdx = versionedLib.indexOfKey(version);
10489        if (libIdx < 0) {
10490            return false;
10491        }
10492        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10493        versionedLib.remove(version);
10494        if (versionedLib.size() <= 0) {
10495            mSharedLibraries.remove(name);
10496            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10497                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10498                        .getPackageName());
10499            }
10500        }
10501        return true;
10502    }
10503
10504    /**
10505     * Adds a scanned package to the system. When this method is finished, the package will
10506     * be available for query, resolution, etc...
10507     */
10508    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10509            UserHandle user, final @ScanFlags int scanFlags, boolean chatty)
10510                    throws PackageManagerException {
10511        final String pkgName = pkg.packageName;
10512        if (mCustomResolverComponentName != null &&
10513                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10514            setUpCustomResolverActivity(pkg);
10515        }
10516
10517        if (pkg.packageName.equals("android")) {
10518            synchronized (mPackages) {
10519                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10520                    // Set up information for our fall-back user intent resolution activity.
10521                    mPlatformPackage = pkg;
10522                    pkg.mVersionCode = mSdkVersion;
10523                    mAndroidApplication = pkg.applicationInfo;
10524                    if (!mResolverReplaced) {
10525                        mResolveActivity.applicationInfo = mAndroidApplication;
10526                        mResolveActivity.name = ResolverActivity.class.getName();
10527                        mResolveActivity.packageName = mAndroidApplication.packageName;
10528                        mResolveActivity.processName = "system:ui";
10529                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10530                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10531                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10532                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10533                        mResolveActivity.exported = true;
10534                        mResolveActivity.enabled = true;
10535                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10536                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10537                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10538                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10539                                | ActivityInfo.CONFIG_ORIENTATION
10540                                | ActivityInfo.CONFIG_KEYBOARD
10541                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10542                        mResolveInfo.activityInfo = mResolveActivity;
10543                        mResolveInfo.priority = 0;
10544                        mResolveInfo.preferredOrder = 0;
10545                        mResolveInfo.match = 0;
10546                        mResolveComponentName = new ComponentName(
10547                                mAndroidApplication.packageName, mResolveActivity.name);
10548                    }
10549                }
10550            }
10551        }
10552
10553        ArrayList<PackageParser.Package> clientLibPkgs = null;
10554        // writer
10555        synchronized (mPackages) {
10556            boolean hasStaticSharedLibs = false;
10557
10558            // Any app can add new static shared libraries
10559            if (pkg.staticSharedLibName != null) {
10560                // Static shared libs don't allow renaming as they have synthetic package
10561                // names to allow install of multiple versions, so use name from manifest.
10562                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10563                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10564                        pkg.manifestPackageName, pkg.mVersionCode)) {
10565                    hasStaticSharedLibs = true;
10566                } else {
10567                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10568                                + pkg.staticSharedLibName + " already exists; skipping");
10569                }
10570                // Static shared libs cannot be updated once installed since they
10571                // use synthetic package name which includes the version code, so
10572                // not need to update other packages's shared lib dependencies.
10573            }
10574
10575            if (!hasStaticSharedLibs
10576                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10577                // Only system apps can add new dynamic shared libraries.
10578                if (pkg.libraryNames != null) {
10579                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10580                        String name = pkg.libraryNames.get(i);
10581                        boolean allowed = false;
10582                        if (pkg.isUpdatedSystemApp()) {
10583                            // New library entries can only be added through the
10584                            // system image.  This is important to get rid of a lot
10585                            // of nasty edge cases: for example if we allowed a non-
10586                            // system update of the app to add a library, then uninstalling
10587                            // the update would make the library go away, and assumptions
10588                            // we made such as through app install filtering would now
10589                            // have allowed apps on the device which aren't compatible
10590                            // with it.  Better to just have the restriction here, be
10591                            // conservative, and create many fewer cases that can negatively
10592                            // impact the user experience.
10593                            final PackageSetting sysPs = mSettings
10594                                    .getDisabledSystemPkgLPr(pkg.packageName);
10595                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10596                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10597                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10598                                        allowed = true;
10599                                        break;
10600                                    }
10601                                }
10602                            }
10603                        } else {
10604                            allowed = true;
10605                        }
10606                        if (allowed) {
10607                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10608                                    SharedLibraryInfo.VERSION_UNDEFINED,
10609                                    SharedLibraryInfo.TYPE_DYNAMIC,
10610                                    pkg.packageName, pkg.mVersionCode)) {
10611                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10612                                        + name + " already exists; skipping");
10613                            }
10614                        } else {
10615                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10616                                    + name + " that is not declared on system image; skipping");
10617                        }
10618                    }
10619
10620                    if ((scanFlags & SCAN_BOOTING) == 0) {
10621                        // If we are not booting, we need to update any applications
10622                        // that are clients of our shared library.  If we are booting,
10623                        // this will all be done once the scan is complete.
10624                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10625                    }
10626                }
10627            }
10628        }
10629
10630        if ((scanFlags & SCAN_BOOTING) != 0) {
10631            // No apps can run during boot scan, so they don't need to be frozen
10632        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10633            // Caller asked to not kill app, so it's probably not frozen
10634        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10635            // Caller asked us to ignore frozen check for some reason; they
10636            // probably didn't know the package name
10637        } else {
10638            // We're doing major surgery on this package, so it better be frozen
10639            // right now to keep it from launching
10640            checkPackageFrozen(pkgName);
10641        }
10642
10643        // Also need to kill any apps that are dependent on the library.
10644        if (clientLibPkgs != null) {
10645            for (int i=0; i<clientLibPkgs.size(); i++) {
10646                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10647                killApplication(clientPkg.applicationInfo.packageName,
10648                        clientPkg.applicationInfo.uid, "update lib");
10649            }
10650        }
10651
10652        // writer
10653        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10654
10655        synchronized (mPackages) {
10656            // We don't expect installation to fail beyond this point
10657
10658            // Add the new setting to mSettings
10659            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10660            // Add the new setting to mPackages
10661            mPackages.put(pkg.applicationInfo.packageName, pkg);
10662            // Make sure we don't accidentally delete its data.
10663            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10664            while (iter.hasNext()) {
10665                PackageCleanItem item = iter.next();
10666                if (pkgName.equals(item.packageName)) {
10667                    iter.remove();
10668                }
10669            }
10670
10671            // Add the package's KeySets to the global KeySetManagerService
10672            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10673            ksms.addScannedPackageLPw(pkg);
10674
10675            int N = pkg.providers.size();
10676            StringBuilder r = null;
10677            int i;
10678            for (i=0; i<N; i++) {
10679                PackageParser.Provider p = pkg.providers.get(i);
10680                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10681                        p.info.processName);
10682                mProviders.addProvider(p);
10683                p.syncable = p.info.isSyncable;
10684                if (p.info.authority != null) {
10685                    String names[] = p.info.authority.split(";");
10686                    p.info.authority = null;
10687                    for (int j = 0; j < names.length; j++) {
10688                        if (j == 1 && p.syncable) {
10689                            // We only want the first authority for a provider to possibly be
10690                            // syncable, so if we already added this provider using a different
10691                            // authority clear the syncable flag. We copy the provider before
10692                            // changing it because the mProviders object contains a reference
10693                            // to a provider that we don't want to change.
10694                            // Only do this for the second authority since the resulting provider
10695                            // object can be the same for all future authorities for this provider.
10696                            p = new PackageParser.Provider(p);
10697                            p.syncable = false;
10698                        }
10699                        if (!mProvidersByAuthority.containsKey(names[j])) {
10700                            mProvidersByAuthority.put(names[j], p);
10701                            if (p.info.authority == null) {
10702                                p.info.authority = names[j];
10703                            } else {
10704                                p.info.authority = p.info.authority + ";" + names[j];
10705                            }
10706                            if (DEBUG_PACKAGE_SCANNING) {
10707                                if (chatty)
10708                                    Log.d(TAG, "Registered content provider: " + names[j]
10709                                            + ", className = " + p.info.name + ", isSyncable = "
10710                                            + p.info.isSyncable);
10711                            }
10712                        } else {
10713                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10714                            Slog.w(TAG, "Skipping provider name " + names[j] +
10715                                    " (in package " + pkg.applicationInfo.packageName +
10716                                    "): name already used by "
10717                                    + ((other != null && other.getComponentName() != null)
10718                                            ? other.getComponentName().getPackageName() : "?"));
10719                        }
10720                    }
10721                }
10722                if (chatty) {
10723                    if (r == null) {
10724                        r = new StringBuilder(256);
10725                    } else {
10726                        r.append(' ');
10727                    }
10728                    r.append(p.info.name);
10729                }
10730            }
10731            if (r != null) {
10732                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10733            }
10734
10735            N = pkg.services.size();
10736            r = null;
10737            for (i=0; i<N; i++) {
10738                PackageParser.Service s = pkg.services.get(i);
10739                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10740                        s.info.processName);
10741                mServices.addService(s);
10742                if (chatty) {
10743                    if (r == null) {
10744                        r = new StringBuilder(256);
10745                    } else {
10746                        r.append(' ');
10747                    }
10748                    r.append(s.info.name);
10749                }
10750            }
10751            if (r != null) {
10752                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10753            }
10754
10755            N = pkg.receivers.size();
10756            r = null;
10757            for (i=0; i<N; i++) {
10758                PackageParser.Activity a = pkg.receivers.get(i);
10759                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10760                        a.info.processName);
10761                mReceivers.addActivity(a, "receiver");
10762                if (chatty) {
10763                    if (r == null) {
10764                        r = new StringBuilder(256);
10765                    } else {
10766                        r.append(' ');
10767                    }
10768                    r.append(a.info.name);
10769                }
10770            }
10771            if (r != null) {
10772                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10773            }
10774
10775            N = pkg.activities.size();
10776            r = null;
10777            for (i=0; i<N; i++) {
10778                PackageParser.Activity a = pkg.activities.get(i);
10779                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10780                        a.info.processName);
10781                mActivities.addActivity(a, "activity");
10782                if (chatty) {
10783                    if (r == null) {
10784                        r = new StringBuilder(256);
10785                    } else {
10786                        r.append(' ');
10787                    }
10788                    r.append(a.info.name);
10789                }
10790            }
10791            if (r != null) {
10792                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10793            }
10794
10795            // Don't allow ephemeral applications to define new permissions groups.
10796            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10797                Slog.w(TAG, "Permission groups from package " + pkg.packageName
10798                        + " ignored: instant apps cannot define new permission groups.");
10799            } else {
10800                mPermissionManager.addAllPermissionGroups(pkg, chatty);
10801            }
10802
10803            // Don't allow ephemeral applications to define new permissions.
10804            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10805                Slog.w(TAG, "Permissions from package " + pkg.packageName
10806                        + " ignored: instant apps cannot define new permissions.");
10807            } else {
10808                mPermissionManager.addAllPermissions(pkg, chatty);
10809            }
10810
10811            N = pkg.instrumentation.size();
10812            r = null;
10813            for (i=0; i<N; i++) {
10814                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10815                a.info.packageName = pkg.applicationInfo.packageName;
10816                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10817                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10818                a.info.splitNames = pkg.splitNames;
10819                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10820                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10821                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10822                a.info.dataDir = pkg.applicationInfo.dataDir;
10823                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10824                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10825                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10826                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10827                mInstrumentation.put(a.getComponentName(), a);
10828                if (chatty) {
10829                    if (r == null) {
10830                        r = new StringBuilder(256);
10831                    } else {
10832                        r.append(' ');
10833                    }
10834                    r.append(a.info.name);
10835                }
10836            }
10837            if (r != null) {
10838                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10839            }
10840
10841            if (pkg.protectedBroadcasts != null) {
10842                N = pkg.protectedBroadcasts.size();
10843                synchronized (mProtectedBroadcasts) {
10844                    for (i = 0; i < N; i++) {
10845                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10846                    }
10847                }
10848            }
10849        }
10850
10851        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10852    }
10853
10854    /**
10855     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10856     * is derived purely on the basis of the contents of {@code scanFile} and
10857     * {@code cpuAbiOverride}.
10858     *
10859     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10860     */
10861    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10862                                 String cpuAbiOverride, boolean extractLibs,
10863                                 File appLib32InstallDir)
10864            throws PackageManagerException {
10865        // Give ourselves some initial paths; we'll come back for another
10866        // pass once we've determined ABI below.
10867        setNativeLibraryPaths(pkg, appLib32InstallDir);
10868
10869        // We would never need to extract libs for forward-locked and external packages,
10870        // since the container service will do it for us. We shouldn't attempt to
10871        // extract libs from system app when it was not updated.
10872        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10873                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10874            extractLibs = false;
10875        }
10876
10877        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10878        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10879
10880        NativeLibraryHelper.Handle handle = null;
10881        try {
10882            handle = NativeLibraryHelper.Handle.create(pkg);
10883            // TODO(multiArch): This can be null for apps that didn't go through the
10884            // usual installation process. We can calculate it again, like we
10885            // do during install time.
10886            //
10887            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10888            // unnecessary.
10889            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10890
10891            // Null out the abis so that they can be recalculated.
10892            pkg.applicationInfo.primaryCpuAbi = null;
10893            pkg.applicationInfo.secondaryCpuAbi = null;
10894            if (isMultiArch(pkg.applicationInfo)) {
10895                // Warn if we've set an abiOverride for multi-lib packages..
10896                // By definition, we need to copy both 32 and 64 bit libraries for
10897                // such packages.
10898                if (pkg.cpuAbiOverride != null
10899                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10900                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10901                }
10902
10903                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10904                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10905                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10906                    if (extractLibs) {
10907                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10908                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10909                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10910                                useIsaSpecificSubdirs);
10911                    } else {
10912                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10913                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10914                    }
10915                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10916                }
10917
10918                // Shared library native code should be in the APK zip aligned
10919                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
10920                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10921                            "Shared library native lib extraction not supported");
10922                }
10923
10924                maybeThrowExceptionForMultiArchCopy(
10925                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10926
10927                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10928                    if (extractLibs) {
10929                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10930                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10931                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10932                                useIsaSpecificSubdirs);
10933                    } else {
10934                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10935                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10936                    }
10937                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10938                }
10939
10940                maybeThrowExceptionForMultiArchCopy(
10941                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10942
10943                if (abi64 >= 0) {
10944                    // Shared library native libs should be in the APK zip aligned
10945                    if (extractLibs && pkg.isLibrary()) {
10946                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10947                                "Shared library native lib extraction not supported");
10948                    }
10949                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10950                }
10951
10952                if (abi32 >= 0) {
10953                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10954                    if (abi64 >= 0) {
10955                        if (pkg.use32bitAbi) {
10956                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10957                            pkg.applicationInfo.primaryCpuAbi = abi;
10958                        } else {
10959                            pkg.applicationInfo.secondaryCpuAbi = abi;
10960                        }
10961                    } else {
10962                        pkg.applicationInfo.primaryCpuAbi = abi;
10963                    }
10964                }
10965            } else {
10966                String[] abiList = (cpuAbiOverride != null) ?
10967                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10968
10969                // Enable gross and lame hacks for apps that are built with old
10970                // SDK tools. We must scan their APKs for renderscript bitcode and
10971                // not launch them if it's present. Don't bother checking on devices
10972                // that don't have 64 bit support.
10973                boolean needsRenderScriptOverride = false;
10974                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10975                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10976                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10977                    needsRenderScriptOverride = true;
10978                }
10979
10980                final int copyRet;
10981                if (extractLibs) {
10982                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10983                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10984                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10985                } else {
10986                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10987                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10988                }
10989                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10990
10991                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10992                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10993                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10994                }
10995
10996                if (copyRet >= 0) {
10997                    // Shared libraries that have native libs must be multi-architecture
10998                    if (pkg.isLibrary()) {
10999                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11000                                "Shared library with native libs must be multiarch");
11001                    }
11002                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11003                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11004                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11005                } else if (needsRenderScriptOverride) {
11006                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11007                }
11008            }
11009        } catch (IOException ioe) {
11010            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11011        } finally {
11012            IoUtils.closeQuietly(handle);
11013        }
11014
11015        // Now that we've calculated the ABIs and determined if it's an internal app,
11016        // we will go ahead and populate the nativeLibraryPath.
11017        setNativeLibraryPaths(pkg, appLib32InstallDir);
11018    }
11019
11020    /**
11021     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11022     * i.e, so that all packages can be run inside a single process if required.
11023     *
11024     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11025     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11026     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11027     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11028     * updating a package that belongs to a shared user.
11029     *
11030     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11031     * adds unnecessary complexity.
11032     */
11033    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11034            PackageParser.Package scannedPackage) {
11035        String requiredInstructionSet = null;
11036        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11037            requiredInstructionSet = VMRuntime.getInstructionSet(
11038                     scannedPackage.applicationInfo.primaryCpuAbi);
11039        }
11040
11041        PackageSetting requirer = null;
11042        for (PackageSetting ps : packagesForUser) {
11043            // If packagesForUser contains scannedPackage, we skip it. This will happen
11044            // when scannedPackage is an update of an existing package. Without this check,
11045            // we will never be able to change the ABI of any package belonging to a shared
11046            // user, even if it's compatible with other packages.
11047            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11048                if (ps.primaryCpuAbiString == null) {
11049                    continue;
11050                }
11051
11052                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11053                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11054                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11055                    // this but there's not much we can do.
11056                    String errorMessage = "Instruction set mismatch, "
11057                            + ((requirer == null) ? "[caller]" : requirer)
11058                            + " requires " + requiredInstructionSet + " whereas " + ps
11059                            + " requires " + instructionSet;
11060                    Slog.w(TAG, errorMessage);
11061                }
11062
11063                if (requiredInstructionSet == null) {
11064                    requiredInstructionSet = instructionSet;
11065                    requirer = ps;
11066                }
11067            }
11068        }
11069
11070        if (requiredInstructionSet != null) {
11071            String adjustedAbi;
11072            if (requirer != null) {
11073                // requirer != null implies that either scannedPackage was null or that scannedPackage
11074                // did not require an ABI, in which case we have to adjust scannedPackage to match
11075                // the ABI of the set (which is the same as requirer's ABI)
11076                adjustedAbi = requirer.primaryCpuAbiString;
11077                if (scannedPackage != null) {
11078                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11079                }
11080            } else {
11081                // requirer == null implies that we're updating all ABIs in the set to
11082                // match scannedPackage.
11083                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11084            }
11085
11086            for (PackageSetting ps : packagesForUser) {
11087                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11088                    if (ps.primaryCpuAbiString != null) {
11089                        continue;
11090                    }
11091
11092                    ps.primaryCpuAbiString = adjustedAbi;
11093                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11094                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11095                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11096                        if (DEBUG_ABI_SELECTION) {
11097                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11098                                    + " (requirer="
11099                                    + (requirer != null ? requirer.pkg : "null")
11100                                    + ", scannedPackage="
11101                                    + (scannedPackage != null ? scannedPackage : "null")
11102                                    + ")");
11103                        }
11104                        try {
11105                            mInstaller.rmdex(ps.codePathString,
11106                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11107                        } catch (InstallerException ignored) {
11108                        }
11109                    }
11110                }
11111            }
11112        }
11113    }
11114
11115    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11116        synchronized (mPackages) {
11117            mResolverReplaced = true;
11118            // Set up information for custom user intent resolution activity.
11119            mResolveActivity.applicationInfo = pkg.applicationInfo;
11120            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11121            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11122            mResolveActivity.processName = pkg.applicationInfo.packageName;
11123            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11124            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11125                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11126            mResolveActivity.theme = 0;
11127            mResolveActivity.exported = true;
11128            mResolveActivity.enabled = true;
11129            mResolveInfo.activityInfo = mResolveActivity;
11130            mResolveInfo.priority = 0;
11131            mResolveInfo.preferredOrder = 0;
11132            mResolveInfo.match = 0;
11133            mResolveComponentName = mCustomResolverComponentName;
11134            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11135                    mResolveComponentName);
11136        }
11137    }
11138
11139    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11140        if (installerActivity == null) {
11141            if (DEBUG_EPHEMERAL) {
11142                Slog.d(TAG, "Clear ephemeral installer activity");
11143            }
11144            mInstantAppInstallerActivity = null;
11145            return;
11146        }
11147
11148        if (DEBUG_EPHEMERAL) {
11149            Slog.d(TAG, "Set ephemeral installer activity: "
11150                    + installerActivity.getComponentName());
11151        }
11152        // Set up information for ephemeral installer activity
11153        mInstantAppInstallerActivity = installerActivity;
11154        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11155                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11156        mInstantAppInstallerActivity.exported = true;
11157        mInstantAppInstallerActivity.enabled = true;
11158        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11159        mInstantAppInstallerInfo.priority = 0;
11160        mInstantAppInstallerInfo.preferredOrder = 1;
11161        mInstantAppInstallerInfo.isDefault = true;
11162        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11163                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11164    }
11165
11166    private static String calculateBundledApkRoot(final String codePathString) {
11167        final File codePath = new File(codePathString);
11168        final File codeRoot;
11169        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11170            codeRoot = Environment.getRootDirectory();
11171        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11172            codeRoot = Environment.getOemDirectory();
11173        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11174            codeRoot = Environment.getVendorDirectory();
11175        } else {
11176            // Unrecognized code path; take its top real segment as the apk root:
11177            // e.g. /something/app/blah.apk => /something
11178            try {
11179                File f = codePath.getCanonicalFile();
11180                File parent = f.getParentFile();    // non-null because codePath is a file
11181                File tmp;
11182                while ((tmp = parent.getParentFile()) != null) {
11183                    f = parent;
11184                    parent = tmp;
11185                }
11186                codeRoot = f;
11187                Slog.w(TAG, "Unrecognized code path "
11188                        + codePath + " - using " + codeRoot);
11189            } catch (IOException e) {
11190                // Can't canonicalize the code path -- shenanigans?
11191                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11192                return Environment.getRootDirectory().getPath();
11193            }
11194        }
11195        return codeRoot.getPath();
11196    }
11197
11198    /**
11199     * Derive and set the location of native libraries for the given package,
11200     * which varies depending on where and how the package was installed.
11201     */
11202    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11203        final ApplicationInfo info = pkg.applicationInfo;
11204        final String codePath = pkg.codePath;
11205        final File codeFile = new File(codePath);
11206        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11207        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11208
11209        info.nativeLibraryRootDir = null;
11210        info.nativeLibraryRootRequiresIsa = false;
11211        info.nativeLibraryDir = null;
11212        info.secondaryNativeLibraryDir = null;
11213
11214        if (isApkFile(codeFile)) {
11215            // Monolithic install
11216            if (bundledApp) {
11217                // If "/system/lib64/apkname" exists, assume that is the per-package
11218                // native library directory to use; otherwise use "/system/lib/apkname".
11219                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11220                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11221                        getPrimaryInstructionSet(info));
11222
11223                // This is a bundled system app so choose the path based on the ABI.
11224                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11225                // is just the default path.
11226                final String apkName = deriveCodePathName(codePath);
11227                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11228                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11229                        apkName).getAbsolutePath();
11230
11231                if (info.secondaryCpuAbi != null) {
11232                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11233                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11234                            secondaryLibDir, apkName).getAbsolutePath();
11235                }
11236            } else if (asecApp) {
11237                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11238                        .getAbsolutePath();
11239            } else {
11240                final String apkName = deriveCodePathName(codePath);
11241                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11242                        .getAbsolutePath();
11243            }
11244
11245            info.nativeLibraryRootRequiresIsa = false;
11246            info.nativeLibraryDir = info.nativeLibraryRootDir;
11247        } else {
11248            // Cluster install
11249            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11250            info.nativeLibraryRootRequiresIsa = true;
11251
11252            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11253                    getPrimaryInstructionSet(info)).getAbsolutePath();
11254
11255            if (info.secondaryCpuAbi != null) {
11256                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11257                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11258            }
11259        }
11260    }
11261
11262    /**
11263     * Calculate the abis and roots for a bundled app. These can uniquely
11264     * be determined from the contents of the system partition, i.e whether
11265     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11266     * of this information, and instead assume that the system was built
11267     * sensibly.
11268     */
11269    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11270                                           PackageSetting pkgSetting) {
11271        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11272
11273        // If "/system/lib64/apkname" exists, assume that is the per-package
11274        // native library directory to use; otherwise use "/system/lib/apkname".
11275        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11276        setBundledAppAbi(pkg, apkRoot, apkName);
11277        // pkgSetting might be null during rescan following uninstall of updates
11278        // to a bundled app, so accommodate that possibility.  The settings in
11279        // that case will be established later from the parsed package.
11280        //
11281        // If the settings aren't null, sync them up with what we've just derived.
11282        // note that apkRoot isn't stored in the package settings.
11283        if (pkgSetting != null) {
11284            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11285            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11286        }
11287    }
11288
11289    /**
11290     * Deduces the ABI of a bundled app and sets the relevant fields on the
11291     * parsed pkg object.
11292     *
11293     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11294     *        under which system libraries are installed.
11295     * @param apkName the name of the installed package.
11296     */
11297    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11298        final File codeFile = new File(pkg.codePath);
11299
11300        final boolean has64BitLibs;
11301        final boolean has32BitLibs;
11302        if (isApkFile(codeFile)) {
11303            // Monolithic install
11304            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11305            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11306        } else {
11307            // Cluster install
11308            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11309            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11310                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11311                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11312                has64BitLibs = (new File(rootDir, isa)).exists();
11313            } else {
11314                has64BitLibs = false;
11315            }
11316            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11317                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11318                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11319                has32BitLibs = (new File(rootDir, isa)).exists();
11320            } else {
11321                has32BitLibs = false;
11322            }
11323        }
11324
11325        if (has64BitLibs && !has32BitLibs) {
11326            // The package has 64 bit libs, but not 32 bit libs. Its primary
11327            // ABI should be 64 bit. We can safely assume here that the bundled
11328            // native libraries correspond to the most preferred ABI in the list.
11329
11330            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11331            pkg.applicationInfo.secondaryCpuAbi = null;
11332        } else if (has32BitLibs && !has64BitLibs) {
11333            // The package has 32 bit libs but not 64 bit libs. Its primary
11334            // ABI should be 32 bit.
11335
11336            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11337            pkg.applicationInfo.secondaryCpuAbi = null;
11338        } else if (has32BitLibs && has64BitLibs) {
11339            // The application has both 64 and 32 bit bundled libraries. We check
11340            // here that the app declares multiArch support, and warn if it doesn't.
11341            //
11342            // We will be lenient here and record both ABIs. The primary will be the
11343            // ABI that's higher on the list, i.e, a device that's configured to prefer
11344            // 64 bit apps will see a 64 bit primary ABI,
11345
11346            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11347                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11348            }
11349
11350            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11351                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11352                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11353            } else {
11354                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11355                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11356            }
11357        } else {
11358            pkg.applicationInfo.primaryCpuAbi = null;
11359            pkg.applicationInfo.secondaryCpuAbi = null;
11360        }
11361    }
11362
11363    private void killApplication(String pkgName, int appId, String reason) {
11364        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11365    }
11366
11367    private void killApplication(String pkgName, int appId, int userId, String reason) {
11368        // Request the ActivityManager to kill the process(only for existing packages)
11369        // so that we do not end up in a confused state while the user is still using the older
11370        // version of the application while the new one gets installed.
11371        final long token = Binder.clearCallingIdentity();
11372        try {
11373            IActivityManager am = ActivityManager.getService();
11374            if (am != null) {
11375                try {
11376                    am.killApplication(pkgName, appId, userId, reason);
11377                } catch (RemoteException e) {
11378                }
11379            }
11380        } finally {
11381            Binder.restoreCallingIdentity(token);
11382        }
11383    }
11384
11385    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11386        // Remove the parent package setting
11387        PackageSetting ps = (PackageSetting) pkg.mExtras;
11388        if (ps != null) {
11389            removePackageLI(ps, chatty);
11390        }
11391        // Remove the child package setting
11392        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11393        for (int i = 0; i < childCount; i++) {
11394            PackageParser.Package childPkg = pkg.childPackages.get(i);
11395            ps = (PackageSetting) childPkg.mExtras;
11396            if (ps != null) {
11397                removePackageLI(ps, chatty);
11398            }
11399        }
11400    }
11401
11402    void removePackageLI(PackageSetting ps, boolean chatty) {
11403        if (DEBUG_INSTALL) {
11404            if (chatty)
11405                Log.d(TAG, "Removing package " + ps.name);
11406        }
11407
11408        // writer
11409        synchronized (mPackages) {
11410            mPackages.remove(ps.name);
11411            final PackageParser.Package pkg = ps.pkg;
11412            if (pkg != null) {
11413                cleanPackageDataStructuresLILPw(pkg, chatty);
11414            }
11415        }
11416    }
11417
11418    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11419        if (DEBUG_INSTALL) {
11420            if (chatty)
11421                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11422        }
11423
11424        // writer
11425        synchronized (mPackages) {
11426            // Remove the parent package
11427            mPackages.remove(pkg.applicationInfo.packageName);
11428            cleanPackageDataStructuresLILPw(pkg, chatty);
11429
11430            // Remove the child packages
11431            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11432            for (int i = 0; i < childCount; i++) {
11433                PackageParser.Package childPkg = pkg.childPackages.get(i);
11434                mPackages.remove(childPkg.applicationInfo.packageName);
11435                cleanPackageDataStructuresLILPw(childPkg, chatty);
11436            }
11437        }
11438    }
11439
11440    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11441        int N = pkg.providers.size();
11442        StringBuilder r = null;
11443        int i;
11444        for (i=0; i<N; i++) {
11445            PackageParser.Provider p = pkg.providers.get(i);
11446            mProviders.removeProvider(p);
11447            if (p.info.authority == null) {
11448
11449                /* There was another ContentProvider with this authority when
11450                 * this app was installed so this authority is null,
11451                 * Ignore it as we don't have to unregister the provider.
11452                 */
11453                continue;
11454            }
11455            String names[] = p.info.authority.split(";");
11456            for (int j = 0; j < names.length; j++) {
11457                if (mProvidersByAuthority.get(names[j]) == p) {
11458                    mProvidersByAuthority.remove(names[j]);
11459                    if (DEBUG_REMOVE) {
11460                        if (chatty)
11461                            Log.d(TAG, "Unregistered content provider: " + names[j]
11462                                    + ", className = " + p.info.name + ", isSyncable = "
11463                                    + p.info.isSyncable);
11464                    }
11465                }
11466            }
11467            if (DEBUG_REMOVE && chatty) {
11468                if (r == null) {
11469                    r = new StringBuilder(256);
11470                } else {
11471                    r.append(' ');
11472                }
11473                r.append(p.info.name);
11474            }
11475        }
11476        if (r != null) {
11477            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11478        }
11479
11480        N = pkg.services.size();
11481        r = null;
11482        for (i=0; i<N; i++) {
11483            PackageParser.Service s = pkg.services.get(i);
11484            mServices.removeService(s);
11485            if (chatty) {
11486                if (r == null) {
11487                    r = new StringBuilder(256);
11488                } else {
11489                    r.append(' ');
11490                }
11491                r.append(s.info.name);
11492            }
11493        }
11494        if (r != null) {
11495            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11496        }
11497
11498        N = pkg.receivers.size();
11499        r = null;
11500        for (i=0; i<N; i++) {
11501            PackageParser.Activity a = pkg.receivers.get(i);
11502            mReceivers.removeActivity(a, "receiver");
11503            if (DEBUG_REMOVE && chatty) {
11504                if (r == null) {
11505                    r = new StringBuilder(256);
11506                } else {
11507                    r.append(' ');
11508                }
11509                r.append(a.info.name);
11510            }
11511        }
11512        if (r != null) {
11513            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11514        }
11515
11516        N = pkg.activities.size();
11517        r = null;
11518        for (i=0; i<N; i++) {
11519            PackageParser.Activity a = pkg.activities.get(i);
11520            mActivities.removeActivity(a, "activity");
11521            if (DEBUG_REMOVE && chatty) {
11522                if (r == null) {
11523                    r = new StringBuilder(256);
11524                } else {
11525                    r.append(' ');
11526                }
11527                r.append(a.info.name);
11528            }
11529        }
11530        if (r != null) {
11531            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11532        }
11533
11534        mPermissionManager.removeAllPermissions(pkg, chatty);
11535
11536        N = pkg.instrumentation.size();
11537        r = null;
11538        for (i=0; i<N; i++) {
11539            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11540            mInstrumentation.remove(a.getComponentName());
11541            if (DEBUG_REMOVE && chatty) {
11542                if (r == null) {
11543                    r = new StringBuilder(256);
11544                } else {
11545                    r.append(' ');
11546                }
11547                r.append(a.info.name);
11548            }
11549        }
11550        if (r != null) {
11551            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11552        }
11553
11554        r = null;
11555        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11556            // Only system apps can hold shared libraries.
11557            if (pkg.libraryNames != null) {
11558                for (i = 0; i < pkg.libraryNames.size(); i++) {
11559                    String name = pkg.libraryNames.get(i);
11560                    if (removeSharedLibraryLPw(name, 0)) {
11561                        if (DEBUG_REMOVE && chatty) {
11562                            if (r == null) {
11563                                r = new StringBuilder(256);
11564                            } else {
11565                                r.append(' ');
11566                            }
11567                            r.append(name);
11568                        }
11569                    }
11570                }
11571            }
11572        }
11573
11574        r = null;
11575
11576        // Any package can hold static shared libraries.
11577        if (pkg.staticSharedLibName != null) {
11578            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11579                if (DEBUG_REMOVE && chatty) {
11580                    if (r == null) {
11581                        r = new StringBuilder(256);
11582                    } else {
11583                        r.append(' ');
11584                    }
11585                    r.append(pkg.staticSharedLibName);
11586                }
11587            }
11588        }
11589
11590        if (r != null) {
11591            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11592        }
11593    }
11594
11595
11596    final class ActivityIntentResolver
11597            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11598        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11599                boolean defaultOnly, int userId) {
11600            if (!sUserManager.exists(userId)) return null;
11601            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11602            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11603        }
11604
11605        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11606                int userId) {
11607            if (!sUserManager.exists(userId)) return null;
11608            mFlags = flags;
11609            return super.queryIntent(intent, resolvedType,
11610                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11611                    userId);
11612        }
11613
11614        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11615                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11616            if (!sUserManager.exists(userId)) return null;
11617            if (packageActivities == null) {
11618                return null;
11619            }
11620            mFlags = flags;
11621            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11622            final int N = packageActivities.size();
11623            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11624                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11625
11626            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11627            for (int i = 0; i < N; ++i) {
11628                intentFilters = packageActivities.get(i).intents;
11629                if (intentFilters != null && intentFilters.size() > 0) {
11630                    PackageParser.ActivityIntentInfo[] array =
11631                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11632                    intentFilters.toArray(array);
11633                    listCut.add(array);
11634                }
11635            }
11636            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11637        }
11638
11639        /**
11640         * Finds a privileged activity that matches the specified activity names.
11641         */
11642        private PackageParser.Activity findMatchingActivity(
11643                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11644            for (PackageParser.Activity sysActivity : activityList) {
11645                if (sysActivity.info.name.equals(activityInfo.name)) {
11646                    return sysActivity;
11647                }
11648                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11649                    return sysActivity;
11650                }
11651                if (sysActivity.info.targetActivity != null) {
11652                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11653                        return sysActivity;
11654                    }
11655                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11656                        return sysActivity;
11657                    }
11658                }
11659            }
11660            return null;
11661        }
11662
11663        public class IterGenerator<E> {
11664            public Iterator<E> generate(ActivityIntentInfo info) {
11665                return null;
11666            }
11667        }
11668
11669        public class ActionIterGenerator extends IterGenerator<String> {
11670            @Override
11671            public Iterator<String> generate(ActivityIntentInfo info) {
11672                return info.actionsIterator();
11673            }
11674        }
11675
11676        public class CategoriesIterGenerator extends IterGenerator<String> {
11677            @Override
11678            public Iterator<String> generate(ActivityIntentInfo info) {
11679                return info.categoriesIterator();
11680            }
11681        }
11682
11683        public class SchemesIterGenerator extends IterGenerator<String> {
11684            @Override
11685            public Iterator<String> generate(ActivityIntentInfo info) {
11686                return info.schemesIterator();
11687            }
11688        }
11689
11690        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11691            @Override
11692            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11693                return info.authoritiesIterator();
11694            }
11695        }
11696
11697        /**
11698         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11699         * MODIFIED. Do not pass in a list that should not be changed.
11700         */
11701        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11702                IterGenerator<T> generator, Iterator<T> searchIterator) {
11703            // loop through the set of actions; every one must be found in the intent filter
11704            while (searchIterator.hasNext()) {
11705                // we must have at least one filter in the list to consider a match
11706                if (intentList.size() == 0) {
11707                    break;
11708                }
11709
11710                final T searchAction = searchIterator.next();
11711
11712                // loop through the set of intent filters
11713                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11714                while (intentIter.hasNext()) {
11715                    final ActivityIntentInfo intentInfo = intentIter.next();
11716                    boolean selectionFound = false;
11717
11718                    // loop through the intent filter's selection criteria; at least one
11719                    // of them must match the searched criteria
11720                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11721                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11722                        final T intentSelection = intentSelectionIter.next();
11723                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11724                            selectionFound = true;
11725                            break;
11726                        }
11727                    }
11728
11729                    // the selection criteria wasn't found in this filter's set; this filter
11730                    // is not a potential match
11731                    if (!selectionFound) {
11732                        intentIter.remove();
11733                    }
11734                }
11735            }
11736        }
11737
11738        private boolean isProtectedAction(ActivityIntentInfo filter) {
11739            final Iterator<String> actionsIter = filter.actionsIterator();
11740            while (actionsIter != null && actionsIter.hasNext()) {
11741                final String filterAction = actionsIter.next();
11742                if (PROTECTED_ACTIONS.contains(filterAction)) {
11743                    return true;
11744                }
11745            }
11746            return false;
11747        }
11748
11749        /**
11750         * Adjusts the priority of the given intent filter according to policy.
11751         * <p>
11752         * <ul>
11753         * <li>The priority for non privileged applications is capped to '0'</li>
11754         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11755         * <li>The priority for unbundled updates to privileged applications is capped to the
11756         *      priority defined on the system partition</li>
11757         * </ul>
11758         * <p>
11759         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11760         * allowed to obtain any priority on any action.
11761         */
11762        private void adjustPriority(
11763                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11764            // nothing to do; priority is fine as-is
11765            if (intent.getPriority() <= 0) {
11766                return;
11767            }
11768
11769            final ActivityInfo activityInfo = intent.activity.info;
11770            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11771
11772            final boolean privilegedApp =
11773                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11774            if (!privilegedApp) {
11775                // non-privileged applications can never define a priority >0
11776                if (DEBUG_FILTERS) {
11777                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
11778                            + " package: " + applicationInfo.packageName
11779                            + " activity: " + intent.activity.className
11780                            + " origPrio: " + intent.getPriority());
11781                }
11782                intent.setPriority(0);
11783                return;
11784            }
11785
11786            if (systemActivities == null) {
11787                // the system package is not disabled; we're parsing the system partition
11788                if (isProtectedAction(intent)) {
11789                    if (mDeferProtectedFilters) {
11790                        // We can't deal with these just yet. No component should ever obtain a
11791                        // >0 priority for a protected actions, with ONE exception -- the setup
11792                        // wizard. The setup wizard, however, cannot be known until we're able to
11793                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11794                        // until all intent filters have been processed. Chicken, meet egg.
11795                        // Let the filter temporarily have a high priority and rectify the
11796                        // priorities after all system packages have been scanned.
11797                        mProtectedFilters.add(intent);
11798                        if (DEBUG_FILTERS) {
11799                            Slog.i(TAG, "Protected action; save for later;"
11800                                    + " package: " + applicationInfo.packageName
11801                                    + " activity: " + intent.activity.className
11802                                    + " origPrio: " + intent.getPriority());
11803                        }
11804                        return;
11805                    } else {
11806                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11807                            Slog.i(TAG, "No setup wizard;"
11808                                + " All protected intents capped to priority 0");
11809                        }
11810                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11811                            if (DEBUG_FILTERS) {
11812                                Slog.i(TAG, "Found setup wizard;"
11813                                    + " allow priority " + intent.getPriority() + ";"
11814                                    + " package: " + intent.activity.info.packageName
11815                                    + " activity: " + intent.activity.className
11816                                    + " priority: " + intent.getPriority());
11817                            }
11818                            // setup wizard gets whatever it wants
11819                            return;
11820                        }
11821                        if (DEBUG_FILTERS) {
11822                            Slog.i(TAG, "Protected action; cap priority to 0;"
11823                                    + " package: " + intent.activity.info.packageName
11824                                    + " activity: " + intent.activity.className
11825                                    + " origPrio: " + intent.getPriority());
11826                        }
11827                        intent.setPriority(0);
11828                        return;
11829                    }
11830                }
11831                // privileged apps on the system image get whatever priority they request
11832                return;
11833            }
11834
11835            // privileged app unbundled update ... try to find the same activity
11836            final PackageParser.Activity foundActivity =
11837                    findMatchingActivity(systemActivities, activityInfo);
11838            if (foundActivity == null) {
11839                // this is a new activity; it cannot obtain >0 priority
11840                if (DEBUG_FILTERS) {
11841                    Slog.i(TAG, "New activity; cap priority to 0;"
11842                            + " package: " + applicationInfo.packageName
11843                            + " activity: " + intent.activity.className
11844                            + " origPrio: " + intent.getPriority());
11845                }
11846                intent.setPriority(0);
11847                return;
11848            }
11849
11850            // found activity, now check for filter equivalence
11851
11852            // a shallow copy is enough; we modify the list, not its contents
11853            final List<ActivityIntentInfo> intentListCopy =
11854                    new ArrayList<>(foundActivity.intents);
11855            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11856
11857            // find matching action subsets
11858            final Iterator<String> actionsIterator = intent.actionsIterator();
11859            if (actionsIterator != null) {
11860                getIntentListSubset(
11861                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11862                if (intentListCopy.size() == 0) {
11863                    // no more intents to match; we're not equivalent
11864                    if (DEBUG_FILTERS) {
11865                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11866                                + " package: " + applicationInfo.packageName
11867                                + " activity: " + intent.activity.className
11868                                + " origPrio: " + intent.getPriority());
11869                    }
11870                    intent.setPriority(0);
11871                    return;
11872                }
11873            }
11874
11875            // find matching category subsets
11876            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11877            if (categoriesIterator != null) {
11878                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11879                        categoriesIterator);
11880                if (intentListCopy.size() == 0) {
11881                    // no more intents to match; we're not equivalent
11882                    if (DEBUG_FILTERS) {
11883                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11884                                + " package: " + applicationInfo.packageName
11885                                + " activity: " + intent.activity.className
11886                                + " origPrio: " + intent.getPriority());
11887                    }
11888                    intent.setPriority(0);
11889                    return;
11890                }
11891            }
11892
11893            // find matching schemes subsets
11894            final Iterator<String> schemesIterator = intent.schemesIterator();
11895            if (schemesIterator != null) {
11896                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11897                        schemesIterator);
11898                if (intentListCopy.size() == 0) {
11899                    // no more intents to match; we're not equivalent
11900                    if (DEBUG_FILTERS) {
11901                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11902                                + " package: " + applicationInfo.packageName
11903                                + " activity: " + intent.activity.className
11904                                + " origPrio: " + intent.getPriority());
11905                    }
11906                    intent.setPriority(0);
11907                    return;
11908                }
11909            }
11910
11911            // find matching authorities subsets
11912            final Iterator<IntentFilter.AuthorityEntry>
11913                    authoritiesIterator = intent.authoritiesIterator();
11914            if (authoritiesIterator != null) {
11915                getIntentListSubset(intentListCopy,
11916                        new AuthoritiesIterGenerator(),
11917                        authoritiesIterator);
11918                if (intentListCopy.size() == 0) {
11919                    // no more intents to match; we're not equivalent
11920                    if (DEBUG_FILTERS) {
11921                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11922                                + " package: " + applicationInfo.packageName
11923                                + " activity: " + intent.activity.className
11924                                + " origPrio: " + intent.getPriority());
11925                    }
11926                    intent.setPriority(0);
11927                    return;
11928                }
11929            }
11930
11931            // we found matching filter(s); app gets the max priority of all intents
11932            int cappedPriority = 0;
11933            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
11934                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
11935            }
11936            if (intent.getPriority() > cappedPriority) {
11937                if (DEBUG_FILTERS) {
11938                    Slog.i(TAG, "Found matching filter(s);"
11939                            + " cap priority to " + cappedPriority + ";"
11940                            + " package: " + applicationInfo.packageName
11941                            + " activity: " + intent.activity.className
11942                            + " origPrio: " + intent.getPriority());
11943                }
11944                intent.setPriority(cappedPriority);
11945                return;
11946            }
11947            // all this for nothing; the requested priority was <= what was on the system
11948        }
11949
11950        public final void addActivity(PackageParser.Activity a, String type) {
11951            mActivities.put(a.getComponentName(), a);
11952            if (DEBUG_SHOW_INFO)
11953                Log.v(
11954                TAG, "  " + type + " " +
11955                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
11956            if (DEBUG_SHOW_INFO)
11957                Log.v(TAG, "    Class=" + a.info.name);
11958            final int NI = a.intents.size();
11959            for (int j=0; j<NI; j++) {
11960                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11961                if ("activity".equals(type)) {
11962                    final PackageSetting ps =
11963                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
11964                    final List<PackageParser.Activity> systemActivities =
11965                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
11966                    adjustPriority(systemActivities, intent);
11967                }
11968                if (DEBUG_SHOW_INFO) {
11969                    Log.v(TAG, "    IntentFilter:");
11970                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11971                }
11972                if (!intent.debugCheck()) {
11973                    Log.w(TAG, "==> For Activity " + a.info.name);
11974                }
11975                addFilter(intent);
11976            }
11977        }
11978
11979        public final void removeActivity(PackageParser.Activity a, String type) {
11980            mActivities.remove(a.getComponentName());
11981            if (DEBUG_SHOW_INFO) {
11982                Log.v(TAG, "  " + type + " "
11983                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
11984                                : a.info.name) + ":");
11985                Log.v(TAG, "    Class=" + a.info.name);
11986            }
11987            final int NI = a.intents.size();
11988            for (int j=0; j<NI; j++) {
11989                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
11990                if (DEBUG_SHOW_INFO) {
11991                    Log.v(TAG, "    IntentFilter:");
11992                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11993                }
11994                removeFilter(intent);
11995            }
11996        }
11997
11998        @Override
11999        protected boolean allowFilterResult(
12000                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12001            ActivityInfo filterAi = filter.activity.info;
12002            for (int i=dest.size()-1; i>=0; i--) {
12003                ActivityInfo destAi = dest.get(i).activityInfo;
12004                if (destAi.name == filterAi.name
12005                        && destAi.packageName == filterAi.packageName) {
12006                    return false;
12007                }
12008            }
12009            return true;
12010        }
12011
12012        @Override
12013        protected ActivityIntentInfo[] newArray(int size) {
12014            return new ActivityIntentInfo[size];
12015        }
12016
12017        @Override
12018        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12019            if (!sUserManager.exists(userId)) return true;
12020            PackageParser.Package p = filter.activity.owner;
12021            if (p != null) {
12022                PackageSetting ps = (PackageSetting)p.mExtras;
12023                if (ps != null) {
12024                    // System apps are never considered stopped for purposes of
12025                    // filtering, because there may be no way for the user to
12026                    // actually re-launch them.
12027                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12028                            && ps.getStopped(userId);
12029                }
12030            }
12031            return false;
12032        }
12033
12034        @Override
12035        protected boolean isPackageForFilter(String packageName,
12036                PackageParser.ActivityIntentInfo info) {
12037            return packageName.equals(info.activity.owner.packageName);
12038        }
12039
12040        @Override
12041        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12042                int match, int userId) {
12043            if (!sUserManager.exists(userId)) return null;
12044            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12045                return null;
12046            }
12047            final PackageParser.Activity activity = info.activity;
12048            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12049            if (ps == null) {
12050                return null;
12051            }
12052            final PackageUserState userState = ps.readUserState(userId);
12053            ActivityInfo ai =
12054                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12055            if (ai == null) {
12056                return null;
12057            }
12058            final boolean matchExplicitlyVisibleOnly =
12059                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12060            final boolean matchVisibleToInstantApp =
12061                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12062            final boolean componentVisible =
12063                    matchVisibleToInstantApp
12064                    && info.isVisibleToInstantApp()
12065                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12066            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12067            // throw out filters that aren't visible to ephemeral apps
12068            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12069                return null;
12070            }
12071            // throw out instant app filters if we're not explicitly requesting them
12072            if (!matchInstantApp && userState.instantApp) {
12073                return null;
12074            }
12075            // throw out instant app filters if updates are available; will trigger
12076            // instant app resolution
12077            if (userState.instantApp && ps.isUpdateAvailable()) {
12078                return null;
12079            }
12080            final ResolveInfo res = new ResolveInfo();
12081            res.activityInfo = ai;
12082            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12083                res.filter = info;
12084            }
12085            if (info != null) {
12086                res.handleAllWebDataURI = info.handleAllWebDataURI();
12087            }
12088            res.priority = info.getPriority();
12089            res.preferredOrder = activity.owner.mPreferredOrder;
12090            //System.out.println("Result: " + res.activityInfo.className +
12091            //                   " = " + res.priority);
12092            res.match = match;
12093            res.isDefault = info.hasDefault;
12094            res.labelRes = info.labelRes;
12095            res.nonLocalizedLabel = info.nonLocalizedLabel;
12096            if (userNeedsBadging(userId)) {
12097                res.noResourceId = true;
12098            } else {
12099                res.icon = info.icon;
12100            }
12101            res.iconResourceId = info.icon;
12102            res.system = res.activityInfo.applicationInfo.isSystemApp();
12103            res.isInstantAppAvailable = userState.instantApp;
12104            return res;
12105        }
12106
12107        @Override
12108        protected void sortResults(List<ResolveInfo> results) {
12109            Collections.sort(results, mResolvePrioritySorter);
12110        }
12111
12112        @Override
12113        protected void dumpFilter(PrintWriter out, String prefix,
12114                PackageParser.ActivityIntentInfo filter) {
12115            out.print(prefix); out.print(
12116                    Integer.toHexString(System.identityHashCode(filter.activity)));
12117                    out.print(' ');
12118                    filter.activity.printComponentShortName(out);
12119                    out.print(" filter ");
12120                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12121        }
12122
12123        @Override
12124        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12125            return filter.activity;
12126        }
12127
12128        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12129            PackageParser.Activity activity = (PackageParser.Activity)label;
12130            out.print(prefix); out.print(
12131                    Integer.toHexString(System.identityHashCode(activity)));
12132                    out.print(' ');
12133                    activity.printComponentShortName(out);
12134            if (count > 1) {
12135                out.print(" ("); out.print(count); out.print(" filters)");
12136            }
12137            out.println();
12138        }
12139
12140        // Keys are String (activity class name), values are Activity.
12141        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12142                = new ArrayMap<ComponentName, PackageParser.Activity>();
12143        private int mFlags;
12144    }
12145
12146    private final class ServiceIntentResolver
12147            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12148        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12149                boolean defaultOnly, int userId) {
12150            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12151            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12152        }
12153
12154        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12155                int userId) {
12156            if (!sUserManager.exists(userId)) return null;
12157            mFlags = flags;
12158            return super.queryIntent(intent, resolvedType,
12159                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12160                    userId);
12161        }
12162
12163        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12164                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12165            if (!sUserManager.exists(userId)) return null;
12166            if (packageServices == null) {
12167                return null;
12168            }
12169            mFlags = flags;
12170            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12171            final int N = packageServices.size();
12172            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12173                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12174
12175            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12176            for (int i = 0; i < N; ++i) {
12177                intentFilters = packageServices.get(i).intents;
12178                if (intentFilters != null && intentFilters.size() > 0) {
12179                    PackageParser.ServiceIntentInfo[] array =
12180                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12181                    intentFilters.toArray(array);
12182                    listCut.add(array);
12183                }
12184            }
12185            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12186        }
12187
12188        public final void addService(PackageParser.Service s) {
12189            mServices.put(s.getComponentName(), s);
12190            if (DEBUG_SHOW_INFO) {
12191                Log.v(TAG, "  "
12192                        + (s.info.nonLocalizedLabel != null
12193                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12194                Log.v(TAG, "    Class=" + s.info.name);
12195            }
12196            final int NI = s.intents.size();
12197            int j;
12198            for (j=0; j<NI; j++) {
12199                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12200                if (DEBUG_SHOW_INFO) {
12201                    Log.v(TAG, "    IntentFilter:");
12202                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12203                }
12204                if (!intent.debugCheck()) {
12205                    Log.w(TAG, "==> For Service " + s.info.name);
12206                }
12207                addFilter(intent);
12208            }
12209        }
12210
12211        public final void removeService(PackageParser.Service s) {
12212            mServices.remove(s.getComponentName());
12213            if (DEBUG_SHOW_INFO) {
12214                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12215                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12216                Log.v(TAG, "    Class=" + s.info.name);
12217            }
12218            final int NI = s.intents.size();
12219            int j;
12220            for (j=0; j<NI; j++) {
12221                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12222                if (DEBUG_SHOW_INFO) {
12223                    Log.v(TAG, "    IntentFilter:");
12224                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12225                }
12226                removeFilter(intent);
12227            }
12228        }
12229
12230        @Override
12231        protected boolean allowFilterResult(
12232                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12233            ServiceInfo filterSi = filter.service.info;
12234            for (int i=dest.size()-1; i>=0; i--) {
12235                ServiceInfo destAi = dest.get(i).serviceInfo;
12236                if (destAi.name == filterSi.name
12237                        && destAi.packageName == filterSi.packageName) {
12238                    return false;
12239                }
12240            }
12241            return true;
12242        }
12243
12244        @Override
12245        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12246            return new PackageParser.ServiceIntentInfo[size];
12247        }
12248
12249        @Override
12250        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12251            if (!sUserManager.exists(userId)) return true;
12252            PackageParser.Package p = filter.service.owner;
12253            if (p != null) {
12254                PackageSetting ps = (PackageSetting)p.mExtras;
12255                if (ps != null) {
12256                    // System apps are never considered stopped for purposes of
12257                    // filtering, because there may be no way for the user to
12258                    // actually re-launch them.
12259                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12260                            && ps.getStopped(userId);
12261                }
12262            }
12263            return false;
12264        }
12265
12266        @Override
12267        protected boolean isPackageForFilter(String packageName,
12268                PackageParser.ServiceIntentInfo info) {
12269            return packageName.equals(info.service.owner.packageName);
12270        }
12271
12272        @Override
12273        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12274                int match, int userId) {
12275            if (!sUserManager.exists(userId)) return null;
12276            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12277            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12278                return null;
12279            }
12280            final PackageParser.Service service = info.service;
12281            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12282            if (ps == null) {
12283                return null;
12284            }
12285            final PackageUserState userState = ps.readUserState(userId);
12286            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12287                    userState, userId);
12288            if (si == null) {
12289                return null;
12290            }
12291            final boolean matchVisibleToInstantApp =
12292                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12293            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12294            // throw out filters that aren't visible to ephemeral apps
12295            if (matchVisibleToInstantApp
12296                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12297                return null;
12298            }
12299            // throw out ephemeral filters if we're not explicitly requesting them
12300            if (!isInstantApp && userState.instantApp) {
12301                return null;
12302            }
12303            // throw out instant app filters if updates are available; will trigger
12304            // instant app resolution
12305            if (userState.instantApp && ps.isUpdateAvailable()) {
12306                return null;
12307            }
12308            final ResolveInfo res = new ResolveInfo();
12309            res.serviceInfo = si;
12310            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12311                res.filter = filter;
12312            }
12313            res.priority = info.getPriority();
12314            res.preferredOrder = service.owner.mPreferredOrder;
12315            res.match = match;
12316            res.isDefault = info.hasDefault;
12317            res.labelRes = info.labelRes;
12318            res.nonLocalizedLabel = info.nonLocalizedLabel;
12319            res.icon = info.icon;
12320            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12321            return res;
12322        }
12323
12324        @Override
12325        protected void sortResults(List<ResolveInfo> results) {
12326            Collections.sort(results, mResolvePrioritySorter);
12327        }
12328
12329        @Override
12330        protected void dumpFilter(PrintWriter out, String prefix,
12331                PackageParser.ServiceIntentInfo filter) {
12332            out.print(prefix); out.print(
12333                    Integer.toHexString(System.identityHashCode(filter.service)));
12334                    out.print(' ');
12335                    filter.service.printComponentShortName(out);
12336                    out.print(" filter ");
12337                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12338        }
12339
12340        @Override
12341        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12342            return filter.service;
12343        }
12344
12345        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12346            PackageParser.Service service = (PackageParser.Service)label;
12347            out.print(prefix); out.print(
12348                    Integer.toHexString(System.identityHashCode(service)));
12349                    out.print(' ');
12350                    service.printComponentShortName(out);
12351            if (count > 1) {
12352                out.print(" ("); out.print(count); out.print(" filters)");
12353            }
12354            out.println();
12355        }
12356
12357//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12358//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12359//            final List<ResolveInfo> retList = Lists.newArrayList();
12360//            while (i.hasNext()) {
12361//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12362//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12363//                    retList.add(resolveInfo);
12364//                }
12365//            }
12366//            return retList;
12367//        }
12368
12369        // Keys are String (activity class name), values are Activity.
12370        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12371                = new ArrayMap<ComponentName, PackageParser.Service>();
12372        private int mFlags;
12373    }
12374
12375    private final class ProviderIntentResolver
12376            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12377        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12378                boolean defaultOnly, int userId) {
12379            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12380            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12381        }
12382
12383        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12384                int userId) {
12385            if (!sUserManager.exists(userId))
12386                return null;
12387            mFlags = flags;
12388            return super.queryIntent(intent, resolvedType,
12389                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12390                    userId);
12391        }
12392
12393        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12394                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12395            if (!sUserManager.exists(userId))
12396                return null;
12397            if (packageProviders == null) {
12398                return null;
12399            }
12400            mFlags = flags;
12401            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12402            final int N = packageProviders.size();
12403            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12404                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12405
12406            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12407            for (int i = 0; i < N; ++i) {
12408                intentFilters = packageProviders.get(i).intents;
12409                if (intentFilters != null && intentFilters.size() > 0) {
12410                    PackageParser.ProviderIntentInfo[] array =
12411                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12412                    intentFilters.toArray(array);
12413                    listCut.add(array);
12414                }
12415            }
12416            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12417        }
12418
12419        public final void addProvider(PackageParser.Provider p) {
12420            if (mProviders.containsKey(p.getComponentName())) {
12421                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12422                return;
12423            }
12424
12425            mProviders.put(p.getComponentName(), p);
12426            if (DEBUG_SHOW_INFO) {
12427                Log.v(TAG, "  "
12428                        + (p.info.nonLocalizedLabel != null
12429                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12430                Log.v(TAG, "    Class=" + p.info.name);
12431            }
12432            final int NI = p.intents.size();
12433            int j;
12434            for (j = 0; j < NI; j++) {
12435                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12436                if (DEBUG_SHOW_INFO) {
12437                    Log.v(TAG, "    IntentFilter:");
12438                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12439                }
12440                if (!intent.debugCheck()) {
12441                    Log.w(TAG, "==> For Provider " + p.info.name);
12442                }
12443                addFilter(intent);
12444            }
12445        }
12446
12447        public final void removeProvider(PackageParser.Provider p) {
12448            mProviders.remove(p.getComponentName());
12449            if (DEBUG_SHOW_INFO) {
12450                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12451                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12452                Log.v(TAG, "    Class=" + p.info.name);
12453            }
12454            final int NI = p.intents.size();
12455            int j;
12456            for (j = 0; j < NI; j++) {
12457                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12458                if (DEBUG_SHOW_INFO) {
12459                    Log.v(TAG, "    IntentFilter:");
12460                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12461                }
12462                removeFilter(intent);
12463            }
12464        }
12465
12466        @Override
12467        protected boolean allowFilterResult(
12468                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12469            ProviderInfo filterPi = filter.provider.info;
12470            for (int i = dest.size() - 1; i >= 0; i--) {
12471                ProviderInfo destPi = dest.get(i).providerInfo;
12472                if (destPi.name == filterPi.name
12473                        && destPi.packageName == filterPi.packageName) {
12474                    return false;
12475                }
12476            }
12477            return true;
12478        }
12479
12480        @Override
12481        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12482            return new PackageParser.ProviderIntentInfo[size];
12483        }
12484
12485        @Override
12486        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12487            if (!sUserManager.exists(userId))
12488                return true;
12489            PackageParser.Package p = filter.provider.owner;
12490            if (p != null) {
12491                PackageSetting ps = (PackageSetting) p.mExtras;
12492                if (ps != null) {
12493                    // System apps are never considered stopped for purposes of
12494                    // filtering, because there may be no way for the user to
12495                    // actually re-launch them.
12496                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12497                            && ps.getStopped(userId);
12498                }
12499            }
12500            return false;
12501        }
12502
12503        @Override
12504        protected boolean isPackageForFilter(String packageName,
12505                PackageParser.ProviderIntentInfo info) {
12506            return packageName.equals(info.provider.owner.packageName);
12507        }
12508
12509        @Override
12510        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12511                int match, int userId) {
12512            if (!sUserManager.exists(userId))
12513                return null;
12514            final PackageParser.ProviderIntentInfo info = filter;
12515            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12516                return null;
12517            }
12518            final PackageParser.Provider provider = info.provider;
12519            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12520            if (ps == null) {
12521                return null;
12522            }
12523            final PackageUserState userState = ps.readUserState(userId);
12524            final boolean matchVisibleToInstantApp =
12525                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12526            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12527            // throw out filters that aren't visible to instant applications
12528            if (matchVisibleToInstantApp
12529                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12530                return null;
12531            }
12532            // throw out instant application filters if we're not explicitly requesting them
12533            if (!isInstantApp && userState.instantApp) {
12534                return null;
12535            }
12536            // throw out instant application filters if updates are available; will trigger
12537            // instant application resolution
12538            if (userState.instantApp && ps.isUpdateAvailable()) {
12539                return null;
12540            }
12541            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12542                    userState, userId);
12543            if (pi == null) {
12544                return null;
12545            }
12546            final ResolveInfo res = new ResolveInfo();
12547            res.providerInfo = pi;
12548            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12549                res.filter = filter;
12550            }
12551            res.priority = info.getPriority();
12552            res.preferredOrder = provider.owner.mPreferredOrder;
12553            res.match = match;
12554            res.isDefault = info.hasDefault;
12555            res.labelRes = info.labelRes;
12556            res.nonLocalizedLabel = info.nonLocalizedLabel;
12557            res.icon = info.icon;
12558            res.system = res.providerInfo.applicationInfo.isSystemApp();
12559            return res;
12560        }
12561
12562        @Override
12563        protected void sortResults(List<ResolveInfo> results) {
12564            Collections.sort(results, mResolvePrioritySorter);
12565        }
12566
12567        @Override
12568        protected void dumpFilter(PrintWriter out, String prefix,
12569                PackageParser.ProviderIntentInfo filter) {
12570            out.print(prefix);
12571            out.print(
12572                    Integer.toHexString(System.identityHashCode(filter.provider)));
12573            out.print(' ');
12574            filter.provider.printComponentShortName(out);
12575            out.print(" filter ");
12576            out.println(Integer.toHexString(System.identityHashCode(filter)));
12577        }
12578
12579        @Override
12580        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12581            return filter.provider;
12582        }
12583
12584        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12585            PackageParser.Provider provider = (PackageParser.Provider)label;
12586            out.print(prefix); out.print(
12587                    Integer.toHexString(System.identityHashCode(provider)));
12588                    out.print(' ');
12589                    provider.printComponentShortName(out);
12590            if (count > 1) {
12591                out.print(" ("); out.print(count); out.print(" filters)");
12592            }
12593            out.println();
12594        }
12595
12596        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12597                = new ArrayMap<ComponentName, PackageParser.Provider>();
12598        private int mFlags;
12599    }
12600
12601    static final class EphemeralIntentResolver
12602            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12603        /**
12604         * The result that has the highest defined order. Ordering applies on a
12605         * per-package basis. Mapping is from package name to Pair of order and
12606         * EphemeralResolveInfo.
12607         * <p>
12608         * NOTE: This is implemented as a field variable for convenience and efficiency.
12609         * By having a field variable, we're able to track filter ordering as soon as
12610         * a non-zero order is defined. Otherwise, multiple loops across the result set
12611         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12612         * this needs to be contained entirely within {@link #filterResults}.
12613         */
12614        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12615
12616        @Override
12617        protected AuxiliaryResolveInfo[] newArray(int size) {
12618            return new AuxiliaryResolveInfo[size];
12619        }
12620
12621        @Override
12622        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12623            return true;
12624        }
12625
12626        @Override
12627        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12628                int userId) {
12629            if (!sUserManager.exists(userId)) {
12630                return null;
12631            }
12632            final String packageName = responseObj.resolveInfo.getPackageName();
12633            final Integer order = responseObj.getOrder();
12634            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12635                    mOrderResult.get(packageName);
12636            // ordering is enabled and this item's order isn't high enough
12637            if (lastOrderResult != null && lastOrderResult.first >= order) {
12638                return null;
12639            }
12640            final InstantAppResolveInfo res = responseObj.resolveInfo;
12641            if (order > 0) {
12642                // non-zero order, enable ordering
12643                mOrderResult.put(packageName, new Pair<>(order, res));
12644            }
12645            return responseObj;
12646        }
12647
12648        @Override
12649        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12650            // only do work if ordering is enabled [most of the time it won't be]
12651            if (mOrderResult.size() == 0) {
12652                return;
12653            }
12654            int resultSize = results.size();
12655            for (int i = 0; i < resultSize; i++) {
12656                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12657                final String packageName = info.getPackageName();
12658                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12659                if (savedInfo == null) {
12660                    // package doesn't having ordering
12661                    continue;
12662                }
12663                if (savedInfo.second == info) {
12664                    // circled back to the highest ordered item; remove from order list
12665                    mOrderResult.remove(packageName);
12666                    if (mOrderResult.size() == 0) {
12667                        // no more ordered items
12668                        break;
12669                    }
12670                    continue;
12671                }
12672                // item has a worse order, remove it from the result list
12673                results.remove(i);
12674                resultSize--;
12675                i--;
12676            }
12677        }
12678    }
12679
12680    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12681            new Comparator<ResolveInfo>() {
12682        public int compare(ResolveInfo r1, ResolveInfo r2) {
12683            int v1 = r1.priority;
12684            int v2 = r2.priority;
12685            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12686            if (v1 != v2) {
12687                return (v1 > v2) ? -1 : 1;
12688            }
12689            v1 = r1.preferredOrder;
12690            v2 = r2.preferredOrder;
12691            if (v1 != v2) {
12692                return (v1 > v2) ? -1 : 1;
12693            }
12694            if (r1.isDefault != r2.isDefault) {
12695                return r1.isDefault ? -1 : 1;
12696            }
12697            v1 = r1.match;
12698            v2 = r2.match;
12699            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12700            if (v1 != v2) {
12701                return (v1 > v2) ? -1 : 1;
12702            }
12703            if (r1.system != r2.system) {
12704                return r1.system ? -1 : 1;
12705            }
12706            if (r1.activityInfo != null) {
12707                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12708            }
12709            if (r1.serviceInfo != null) {
12710                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12711            }
12712            if (r1.providerInfo != null) {
12713                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12714            }
12715            return 0;
12716        }
12717    };
12718
12719    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12720            new Comparator<ProviderInfo>() {
12721        public int compare(ProviderInfo p1, ProviderInfo p2) {
12722            final int v1 = p1.initOrder;
12723            final int v2 = p2.initOrder;
12724            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12725        }
12726    };
12727
12728    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12729            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12730            final int[] userIds) {
12731        mHandler.post(new Runnable() {
12732            @Override
12733            public void run() {
12734                try {
12735                    final IActivityManager am = ActivityManager.getService();
12736                    if (am == null) return;
12737                    final int[] resolvedUserIds;
12738                    if (userIds == null) {
12739                        resolvedUserIds = am.getRunningUserIds();
12740                    } else {
12741                        resolvedUserIds = userIds;
12742                    }
12743                    for (int id : resolvedUserIds) {
12744                        final Intent intent = new Intent(action,
12745                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12746                        if (extras != null) {
12747                            intent.putExtras(extras);
12748                        }
12749                        if (targetPkg != null) {
12750                            intent.setPackage(targetPkg);
12751                        }
12752                        // Modify the UID when posting to other users
12753                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12754                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12755                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12756                            intent.putExtra(Intent.EXTRA_UID, uid);
12757                        }
12758                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12759                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12760                        if (DEBUG_BROADCASTS) {
12761                            RuntimeException here = new RuntimeException("here");
12762                            here.fillInStackTrace();
12763                            Slog.d(TAG, "Sending to user " + id + ": "
12764                                    + intent.toShortString(false, true, false, false)
12765                                    + " " + intent.getExtras(), here);
12766                        }
12767                        am.broadcastIntent(null, intent, null, finishedReceiver,
12768                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12769                                null, finishedReceiver != null, false, id);
12770                    }
12771                } catch (RemoteException ex) {
12772                }
12773            }
12774        });
12775    }
12776
12777    /**
12778     * Check if the external storage media is available. This is true if there
12779     * is a mounted external storage medium or if the external storage is
12780     * emulated.
12781     */
12782    private boolean isExternalMediaAvailable() {
12783        return mMediaMounted || Environment.isExternalStorageEmulated();
12784    }
12785
12786    @Override
12787    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12788        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
12789            return null;
12790        }
12791        // writer
12792        synchronized (mPackages) {
12793            if (!isExternalMediaAvailable()) {
12794                // If the external storage is no longer mounted at this point,
12795                // the caller may not have been able to delete all of this
12796                // packages files and can not delete any more.  Bail.
12797                return null;
12798            }
12799            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12800            if (lastPackage != null) {
12801                pkgs.remove(lastPackage);
12802            }
12803            if (pkgs.size() > 0) {
12804                return pkgs.get(0);
12805            }
12806        }
12807        return null;
12808    }
12809
12810    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12811        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12812                userId, andCode ? 1 : 0, packageName);
12813        if (mSystemReady) {
12814            msg.sendToTarget();
12815        } else {
12816            if (mPostSystemReadyMessages == null) {
12817                mPostSystemReadyMessages = new ArrayList<>();
12818            }
12819            mPostSystemReadyMessages.add(msg);
12820        }
12821    }
12822
12823    void startCleaningPackages() {
12824        // reader
12825        if (!isExternalMediaAvailable()) {
12826            return;
12827        }
12828        synchronized (mPackages) {
12829            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12830                return;
12831            }
12832        }
12833        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12834        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12835        IActivityManager am = ActivityManager.getService();
12836        if (am != null) {
12837            int dcsUid = -1;
12838            synchronized (mPackages) {
12839                if (!mDefaultContainerWhitelisted) {
12840                    mDefaultContainerWhitelisted = true;
12841                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
12842                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
12843                }
12844            }
12845            try {
12846                if (dcsUid > 0) {
12847                    am.backgroundWhitelistUid(dcsUid);
12848                }
12849                am.startService(null, intent, null, false, mContext.getOpPackageName(),
12850                        UserHandle.USER_SYSTEM);
12851            } catch (RemoteException e) {
12852            }
12853        }
12854    }
12855
12856    @Override
12857    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12858            int installFlags, String installerPackageName, int userId) {
12859        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12860
12861        final int callingUid = Binder.getCallingUid();
12862        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
12863                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12864
12865        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12866            try {
12867                if (observer != null) {
12868                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12869                }
12870            } catch (RemoteException re) {
12871            }
12872            return;
12873        }
12874
12875        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12876            installFlags |= PackageManager.INSTALL_FROM_ADB;
12877
12878        } else {
12879            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12880            // about installerPackageName.
12881
12882            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12883            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12884        }
12885
12886        UserHandle user;
12887        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12888            user = UserHandle.ALL;
12889        } else {
12890            user = new UserHandle(userId);
12891        }
12892
12893        // Only system components can circumvent runtime permissions when installing.
12894        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12895                && mContext.checkCallingOrSelfPermission(Manifest.permission
12896                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12897            throw new SecurityException("You need the "
12898                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12899                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12900        }
12901
12902        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12903                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12904            throw new IllegalArgumentException(
12905                    "New installs into ASEC containers no longer supported");
12906        }
12907
12908        final File originFile = new File(originPath);
12909        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12910
12911        final Message msg = mHandler.obtainMessage(INIT_COPY);
12912        final VerificationInfo verificationInfo = new VerificationInfo(
12913                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12914        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12915                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12916                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12917                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12918        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12919        msg.obj = params;
12920
12921        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12922                System.identityHashCode(msg.obj));
12923        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12924                System.identityHashCode(msg.obj));
12925
12926        mHandler.sendMessage(msg);
12927    }
12928
12929
12930    /**
12931     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12932     * it is acting on behalf on an enterprise or the user).
12933     *
12934     * Note that the ordering of the conditionals in this method is important. The checks we perform
12935     * are as follows, in this order:
12936     *
12937     * 1) If the install is being performed by a system app, we can trust the app to have set the
12938     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12939     *    what it is.
12940     * 2) If the install is being performed by a device or profile owner app, the install reason
12941     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12942     *    set the install reason correctly. If the app targets an older SDK version where install
12943     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12944     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12945     * 3) In all other cases, the install is being performed by a regular app that is neither part
12946     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12947     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12948     *    set to enterprise policy and if so, change it to unknown instead.
12949     */
12950    private int fixUpInstallReason(String installerPackageName, int installerUid,
12951            int installReason) {
12952        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12953                == PERMISSION_GRANTED) {
12954            // If the install is being performed by a system app, we trust that app to have set the
12955            // install reason correctly.
12956            return installReason;
12957        }
12958
12959        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12960            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12961        if (dpm != null) {
12962            ComponentName owner = null;
12963            try {
12964                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12965                if (owner == null) {
12966                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12967                }
12968            } catch (RemoteException e) {
12969            }
12970            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12971                // If the install is being performed by a device or profile owner, the install
12972                // reason should be enterprise policy.
12973                return PackageManager.INSTALL_REASON_POLICY;
12974            }
12975        }
12976
12977        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12978            // If the install is being performed by a regular app (i.e. neither system app nor
12979            // device or profile owner), we have no reason to believe that the app is acting on
12980            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12981            // change it to unknown instead.
12982            return PackageManager.INSTALL_REASON_UNKNOWN;
12983        }
12984
12985        // If the install is being performed by a regular app and the install reason was set to any
12986        // value but enterprise policy, leave the install reason unchanged.
12987        return installReason;
12988    }
12989
12990    void installStage(String packageName, File stagedDir,
12991            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12992            String installerPackageName, int installerUid, UserHandle user,
12993            Certificate[][] certificates) {
12994        if (DEBUG_EPHEMERAL) {
12995            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
12996                Slog.d(TAG, "Ephemeral install of " + packageName);
12997            }
12998        }
12999        final VerificationInfo verificationInfo = new VerificationInfo(
13000                sessionParams.originatingUri, sessionParams.referrerUri,
13001                sessionParams.originatingUid, installerUid);
13002
13003        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13004
13005        final Message msg = mHandler.obtainMessage(INIT_COPY);
13006        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13007                sessionParams.installReason);
13008        final InstallParams params = new InstallParams(origin, null, observer,
13009                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13010                verificationInfo, user, sessionParams.abiOverride,
13011                sessionParams.grantedRuntimePermissions, certificates, installReason);
13012        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13013        msg.obj = params;
13014
13015        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13016                System.identityHashCode(msg.obj));
13017        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13018                System.identityHashCode(msg.obj));
13019
13020        mHandler.sendMessage(msg);
13021    }
13022
13023    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13024            int userId) {
13025        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13026        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13027                false /*startReceiver*/, pkgSetting.appId, userId);
13028
13029        // Send a session commit broadcast
13030        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13031        info.installReason = pkgSetting.getInstallReason(userId);
13032        info.appPackageName = packageName;
13033        sendSessionCommitBroadcast(info, userId);
13034    }
13035
13036    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13037            boolean includeStopped, int appId, int... userIds) {
13038        if (ArrayUtils.isEmpty(userIds)) {
13039            return;
13040        }
13041        Bundle extras = new Bundle(1);
13042        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13043        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13044
13045        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13046                packageName, extras, 0, null, null, userIds);
13047        if (sendBootCompleted) {
13048            mHandler.post(() -> {
13049                        for (int userId : userIds) {
13050                            sendBootCompletedBroadcastToSystemApp(
13051                                    packageName, includeStopped, userId);
13052                        }
13053                    }
13054            );
13055        }
13056    }
13057
13058    /**
13059     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13060     * automatically without needing an explicit launch.
13061     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13062     */
13063    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13064            int userId) {
13065        // If user is not running, the app didn't miss any broadcast
13066        if (!mUserManagerInternal.isUserRunning(userId)) {
13067            return;
13068        }
13069        final IActivityManager am = ActivityManager.getService();
13070        try {
13071            // Deliver LOCKED_BOOT_COMPLETED first
13072            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13073                    .setPackage(packageName);
13074            if (includeStopped) {
13075                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13076            }
13077            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13078            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13079                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13080
13081            // Deliver BOOT_COMPLETED only if user is unlocked
13082            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13083                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13084                if (includeStopped) {
13085                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13086                }
13087                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13088                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13089            }
13090        } catch (RemoteException e) {
13091            throw e.rethrowFromSystemServer();
13092        }
13093    }
13094
13095    @Override
13096    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13097            int userId) {
13098        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13099        PackageSetting pkgSetting;
13100        final int callingUid = Binder.getCallingUid();
13101        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13102                true /* requireFullPermission */, true /* checkShell */,
13103                "setApplicationHiddenSetting for user " + userId);
13104
13105        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13106            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13107            return false;
13108        }
13109
13110        long callingId = Binder.clearCallingIdentity();
13111        try {
13112            boolean sendAdded = false;
13113            boolean sendRemoved = false;
13114            // writer
13115            synchronized (mPackages) {
13116                pkgSetting = mSettings.mPackages.get(packageName);
13117                if (pkgSetting == null) {
13118                    return false;
13119                }
13120                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13121                    return false;
13122                }
13123                // Do not allow "android" is being disabled
13124                if ("android".equals(packageName)) {
13125                    Slog.w(TAG, "Cannot hide package: android");
13126                    return false;
13127                }
13128                // Cannot hide static shared libs as they are considered
13129                // a part of the using app (emulating static linking). Also
13130                // static libs are installed always on internal storage.
13131                PackageParser.Package pkg = mPackages.get(packageName);
13132                if (pkg != null && pkg.staticSharedLibName != null) {
13133                    Slog.w(TAG, "Cannot hide package: " + packageName
13134                            + " providing static shared library: "
13135                            + pkg.staticSharedLibName);
13136                    return false;
13137                }
13138                // Only allow protected packages to hide themselves.
13139                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13140                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13141                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13142                    return false;
13143                }
13144
13145                if (pkgSetting.getHidden(userId) != hidden) {
13146                    pkgSetting.setHidden(hidden, userId);
13147                    mSettings.writePackageRestrictionsLPr(userId);
13148                    if (hidden) {
13149                        sendRemoved = true;
13150                    } else {
13151                        sendAdded = true;
13152                    }
13153                }
13154            }
13155            if (sendAdded) {
13156                sendPackageAddedForUser(packageName, pkgSetting, userId);
13157                return true;
13158            }
13159            if (sendRemoved) {
13160                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13161                        "hiding pkg");
13162                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13163                return true;
13164            }
13165        } finally {
13166            Binder.restoreCallingIdentity(callingId);
13167        }
13168        return false;
13169    }
13170
13171    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13172            int userId) {
13173        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13174        info.removedPackage = packageName;
13175        info.installerPackageName = pkgSetting.installerPackageName;
13176        info.removedUsers = new int[] {userId};
13177        info.broadcastUsers = new int[] {userId};
13178        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13179        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13180    }
13181
13182    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13183        if (pkgList.length > 0) {
13184            Bundle extras = new Bundle(1);
13185            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13186
13187            sendPackageBroadcast(
13188                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13189                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13190                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13191                    new int[] {userId});
13192        }
13193    }
13194
13195    /**
13196     * Returns true if application is not found or there was an error. Otherwise it returns
13197     * the hidden state of the package for the given user.
13198     */
13199    @Override
13200    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13201        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13202        final int callingUid = Binder.getCallingUid();
13203        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13204                true /* requireFullPermission */, false /* checkShell */,
13205                "getApplicationHidden for user " + userId);
13206        PackageSetting ps;
13207        long callingId = Binder.clearCallingIdentity();
13208        try {
13209            // writer
13210            synchronized (mPackages) {
13211                ps = mSettings.mPackages.get(packageName);
13212                if (ps == null) {
13213                    return true;
13214                }
13215                if (filterAppAccessLPr(ps, callingUid, userId)) {
13216                    return true;
13217                }
13218                return ps.getHidden(userId);
13219            }
13220        } finally {
13221            Binder.restoreCallingIdentity(callingId);
13222        }
13223    }
13224
13225    /**
13226     * @hide
13227     */
13228    @Override
13229    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13230            int installReason) {
13231        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13232                null);
13233        PackageSetting pkgSetting;
13234        final int callingUid = Binder.getCallingUid();
13235        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13236                true /* requireFullPermission */, true /* checkShell */,
13237                "installExistingPackage for user " + userId);
13238        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13239            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13240        }
13241
13242        long callingId = Binder.clearCallingIdentity();
13243        try {
13244            boolean installed = false;
13245            final boolean instantApp =
13246                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13247            final boolean fullApp =
13248                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13249
13250            // writer
13251            synchronized (mPackages) {
13252                pkgSetting = mSettings.mPackages.get(packageName);
13253                if (pkgSetting == null) {
13254                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13255                }
13256                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13257                    // only allow the existing package to be used if it's installed as a full
13258                    // application for at least one user
13259                    boolean installAllowed = false;
13260                    for (int checkUserId : sUserManager.getUserIds()) {
13261                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13262                        if (installAllowed) {
13263                            break;
13264                        }
13265                    }
13266                    if (!installAllowed) {
13267                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13268                    }
13269                }
13270                if (!pkgSetting.getInstalled(userId)) {
13271                    pkgSetting.setInstalled(true, userId);
13272                    pkgSetting.setHidden(false, userId);
13273                    pkgSetting.setInstallReason(installReason, userId);
13274                    mSettings.writePackageRestrictionsLPr(userId);
13275                    mSettings.writeKernelMappingLPr(pkgSetting);
13276                    installed = true;
13277                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13278                    // upgrade app from instant to full; we don't allow app downgrade
13279                    installed = true;
13280                }
13281                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13282            }
13283
13284            if (installed) {
13285                if (pkgSetting.pkg != null) {
13286                    synchronized (mInstallLock) {
13287                        // We don't need to freeze for a brand new install
13288                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13289                    }
13290                }
13291                sendPackageAddedForUser(packageName, pkgSetting, userId);
13292                synchronized (mPackages) {
13293                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13294                }
13295            }
13296        } finally {
13297            Binder.restoreCallingIdentity(callingId);
13298        }
13299
13300        return PackageManager.INSTALL_SUCCEEDED;
13301    }
13302
13303    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13304            boolean instantApp, boolean fullApp) {
13305        // no state specified; do nothing
13306        if (!instantApp && !fullApp) {
13307            return;
13308        }
13309        if (userId != UserHandle.USER_ALL) {
13310            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13311                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13312            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13313                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13314            }
13315        } else {
13316            for (int currentUserId : sUserManager.getUserIds()) {
13317                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13318                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13319                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13320                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13321                }
13322            }
13323        }
13324    }
13325
13326    boolean isUserRestricted(int userId, String restrictionKey) {
13327        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13328        if (restrictions.getBoolean(restrictionKey, false)) {
13329            Log.w(TAG, "User is restricted: " + restrictionKey);
13330            return true;
13331        }
13332        return false;
13333    }
13334
13335    @Override
13336    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13337            int userId) {
13338        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13339        final int callingUid = Binder.getCallingUid();
13340        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13341                true /* requireFullPermission */, true /* checkShell */,
13342                "setPackagesSuspended for user " + userId);
13343
13344        if (ArrayUtils.isEmpty(packageNames)) {
13345            return packageNames;
13346        }
13347
13348        // List of package names for whom the suspended state has changed.
13349        List<String> changedPackages = new ArrayList<>(packageNames.length);
13350        // List of package names for whom the suspended state is not set as requested in this
13351        // method.
13352        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13353        long callingId = Binder.clearCallingIdentity();
13354        try {
13355            for (int i = 0; i < packageNames.length; i++) {
13356                String packageName = packageNames[i];
13357                boolean changed = false;
13358                final int appId;
13359                synchronized (mPackages) {
13360                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13361                    if (pkgSetting == null
13362                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13363                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13364                                + "\". Skipping suspending/un-suspending.");
13365                        unactionedPackages.add(packageName);
13366                        continue;
13367                    }
13368                    appId = pkgSetting.appId;
13369                    if (pkgSetting.getSuspended(userId) != suspended) {
13370                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13371                            unactionedPackages.add(packageName);
13372                            continue;
13373                        }
13374                        pkgSetting.setSuspended(suspended, userId);
13375                        mSettings.writePackageRestrictionsLPr(userId);
13376                        changed = true;
13377                        changedPackages.add(packageName);
13378                    }
13379                }
13380
13381                if (changed && suspended) {
13382                    killApplication(packageName, UserHandle.getUid(userId, appId),
13383                            "suspending package");
13384                }
13385            }
13386        } finally {
13387            Binder.restoreCallingIdentity(callingId);
13388        }
13389
13390        if (!changedPackages.isEmpty()) {
13391            sendPackagesSuspendedForUser(changedPackages.toArray(
13392                    new String[changedPackages.size()]), userId, suspended);
13393        }
13394
13395        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13396    }
13397
13398    @Override
13399    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13400        final int callingUid = Binder.getCallingUid();
13401        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13402                true /* requireFullPermission */, false /* checkShell */,
13403                "isPackageSuspendedForUser for user " + userId);
13404        synchronized (mPackages) {
13405            final PackageSetting ps = mSettings.mPackages.get(packageName);
13406            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13407                throw new IllegalArgumentException("Unknown target package: " + packageName);
13408            }
13409            return ps.getSuspended(userId);
13410        }
13411    }
13412
13413    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13414        if (isPackageDeviceAdmin(packageName, userId)) {
13415            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13416                    + "\": has an active device admin");
13417            return false;
13418        }
13419
13420        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13421        if (packageName.equals(activeLauncherPackageName)) {
13422            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13423                    + "\": contains the active launcher");
13424            return false;
13425        }
13426
13427        if (packageName.equals(mRequiredInstallerPackage)) {
13428            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13429                    + "\": required for package installation");
13430            return false;
13431        }
13432
13433        if (packageName.equals(mRequiredUninstallerPackage)) {
13434            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13435                    + "\": required for package uninstallation");
13436            return false;
13437        }
13438
13439        if (packageName.equals(mRequiredVerifierPackage)) {
13440            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13441                    + "\": required for package verification");
13442            return false;
13443        }
13444
13445        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13446            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13447                    + "\": is the default dialer");
13448            return false;
13449        }
13450
13451        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13452            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13453                    + "\": protected package");
13454            return false;
13455        }
13456
13457        // Cannot suspend static shared libs as they are considered
13458        // a part of the using app (emulating static linking). Also
13459        // static libs are installed always on internal storage.
13460        PackageParser.Package pkg = mPackages.get(packageName);
13461        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13462            Slog.w(TAG, "Cannot suspend package: " + packageName
13463                    + " providing static shared library: "
13464                    + pkg.staticSharedLibName);
13465            return false;
13466        }
13467
13468        return true;
13469    }
13470
13471    private String getActiveLauncherPackageName(int userId) {
13472        Intent intent = new Intent(Intent.ACTION_MAIN);
13473        intent.addCategory(Intent.CATEGORY_HOME);
13474        ResolveInfo resolveInfo = resolveIntent(
13475                intent,
13476                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13477                PackageManager.MATCH_DEFAULT_ONLY,
13478                userId);
13479
13480        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13481    }
13482
13483    private String getDefaultDialerPackageName(int userId) {
13484        synchronized (mPackages) {
13485            return mSettings.getDefaultDialerPackageNameLPw(userId);
13486        }
13487    }
13488
13489    @Override
13490    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13491        mContext.enforceCallingOrSelfPermission(
13492                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13493                "Only package verification agents can verify applications");
13494
13495        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13496        final PackageVerificationResponse response = new PackageVerificationResponse(
13497                verificationCode, Binder.getCallingUid());
13498        msg.arg1 = id;
13499        msg.obj = response;
13500        mHandler.sendMessage(msg);
13501    }
13502
13503    @Override
13504    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13505            long millisecondsToDelay) {
13506        mContext.enforceCallingOrSelfPermission(
13507                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13508                "Only package verification agents can extend verification timeouts");
13509
13510        final PackageVerificationState state = mPendingVerification.get(id);
13511        final PackageVerificationResponse response = new PackageVerificationResponse(
13512                verificationCodeAtTimeout, Binder.getCallingUid());
13513
13514        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13515            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13516        }
13517        if (millisecondsToDelay < 0) {
13518            millisecondsToDelay = 0;
13519        }
13520        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13521                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13522            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13523        }
13524
13525        if ((state != null) && !state.timeoutExtended()) {
13526            state.extendTimeout();
13527
13528            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13529            msg.arg1 = id;
13530            msg.obj = response;
13531            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13532        }
13533    }
13534
13535    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13536            int verificationCode, UserHandle user) {
13537        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13538        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13539        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13540        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13541        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13542
13543        mContext.sendBroadcastAsUser(intent, user,
13544                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13545    }
13546
13547    private ComponentName matchComponentForVerifier(String packageName,
13548            List<ResolveInfo> receivers) {
13549        ActivityInfo targetReceiver = null;
13550
13551        final int NR = receivers.size();
13552        for (int i = 0; i < NR; i++) {
13553            final ResolveInfo info = receivers.get(i);
13554            if (info.activityInfo == null) {
13555                continue;
13556            }
13557
13558            if (packageName.equals(info.activityInfo.packageName)) {
13559                targetReceiver = info.activityInfo;
13560                break;
13561            }
13562        }
13563
13564        if (targetReceiver == null) {
13565            return null;
13566        }
13567
13568        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13569    }
13570
13571    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13572            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13573        if (pkgInfo.verifiers.length == 0) {
13574            return null;
13575        }
13576
13577        final int N = pkgInfo.verifiers.length;
13578        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13579        for (int i = 0; i < N; i++) {
13580            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13581
13582            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13583                    receivers);
13584            if (comp == null) {
13585                continue;
13586            }
13587
13588            final int verifierUid = getUidForVerifier(verifierInfo);
13589            if (verifierUid == -1) {
13590                continue;
13591            }
13592
13593            if (DEBUG_VERIFY) {
13594                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13595                        + " with the correct signature");
13596            }
13597            sufficientVerifiers.add(comp);
13598            verificationState.addSufficientVerifier(verifierUid);
13599        }
13600
13601        return sufficientVerifiers;
13602    }
13603
13604    private int getUidForVerifier(VerifierInfo verifierInfo) {
13605        synchronized (mPackages) {
13606            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13607            if (pkg == null) {
13608                return -1;
13609            } else if (pkg.mSignatures.length != 1) {
13610                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13611                        + " has more than one signature; ignoring");
13612                return -1;
13613            }
13614
13615            /*
13616             * If the public key of the package's signature does not match
13617             * our expected public key, then this is a different package and
13618             * we should skip.
13619             */
13620
13621            final byte[] expectedPublicKey;
13622            try {
13623                final Signature verifierSig = pkg.mSignatures[0];
13624                final PublicKey publicKey = verifierSig.getPublicKey();
13625                expectedPublicKey = publicKey.getEncoded();
13626            } catch (CertificateException e) {
13627                return -1;
13628            }
13629
13630            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13631
13632            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13633                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13634                        + " does not have the expected public key; ignoring");
13635                return -1;
13636            }
13637
13638            return pkg.applicationInfo.uid;
13639        }
13640    }
13641
13642    @Override
13643    public void finishPackageInstall(int token, boolean didLaunch) {
13644        enforceSystemOrRoot("Only the system is allowed to finish installs");
13645
13646        if (DEBUG_INSTALL) {
13647            Slog.v(TAG, "BM finishing package install for " + token);
13648        }
13649        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13650
13651        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13652        mHandler.sendMessage(msg);
13653    }
13654
13655    /**
13656     * Get the verification agent timeout.  Used for both the APK verifier and the
13657     * intent filter verifier.
13658     *
13659     * @return verification timeout in milliseconds
13660     */
13661    private long getVerificationTimeout() {
13662        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13663                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13664                DEFAULT_VERIFICATION_TIMEOUT);
13665    }
13666
13667    /**
13668     * Get the default verification agent response code.
13669     *
13670     * @return default verification response code
13671     */
13672    private int getDefaultVerificationResponse(UserHandle user) {
13673        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
13674            return PackageManager.VERIFICATION_REJECT;
13675        }
13676        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13677                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13678                DEFAULT_VERIFICATION_RESPONSE);
13679    }
13680
13681    /**
13682     * Check whether or not package verification has been enabled.
13683     *
13684     * @return true if verification should be performed
13685     */
13686    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
13687        if (!DEFAULT_VERIFY_ENABLE) {
13688            return false;
13689        }
13690
13691        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13692
13693        // Check if installing from ADB
13694        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13695            // Do not run verification in a test harness environment
13696            if (ActivityManager.isRunningInTestHarness()) {
13697                return false;
13698            }
13699            if (ensureVerifyAppsEnabled) {
13700                return true;
13701            }
13702            // Check if the developer does not want package verification for ADB installs
13703            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13704                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13705                return false;
13706            }
13707        } else {
13708            // only when not installed from ADB, skip verification for instant apps when
13709            // the installer and verifier are the same.
13710            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13711                if (mInstantAppInstallerActivity != null
13712                        && mInstantAppInstallerActivity.packageName.equals(
13713                                mRequiredVerifierPackage)) {
13714                    try {
13715                        mContext.getSystemService(AppOpsManager.class)
13716                                .checkPackage(installerUid, mRequiredVerifierPackage);
13717                        if (DEBUG_VERIFY) {
13718                            Slog.i(TAG, "disable verification for instant app");
13719                        }
13720                        return false;
13721                    } catch (SecurityException ignore) { }
13722                }
13723            }
13724        }
13725
13726        if (ensureVerifyAppsEnabled) {
13727            return true;
13728        }
13729
13730        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13731                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13732    }
13733
13734    @Override
13735    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13736            throws RemoteException {
13737        mContext.enforceCallingOrSelfPermission(
13738                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13739                "Only intentfilter verification agents can verify applications");
13740
13741        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13742        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13743                Binder.getCallingUid(), verificationCode, failedDomains);
13744        msg.arg1 = id;
13745        msg.obj = response;
13746        mHandler.sendMessage(msg);
13747    }
13748
13749    @Override
13750    public int getIntentVerificationStatus(String packageName, int userId) {
13751        final int callingUid = Binder.getCallingUid();
13752        if (UserHandle.getUserId(callingUid) != userId) {
13753            mContext.enforceCallingOrSelfPermission(
13754                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13755                    "getIntentVerificationStatus" + userId);
13756        }
13757        if (getInstantAppPackageName(callingUid) != null) {
13758            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13759        }
13760        synchronized (mPackages) {
13761            final PackageSetting ps = mSettings.mPackages.get(packageName);
13762            if (ps == null
13763                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13764                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
13765            }
13766            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13767        }
13768    }
13769
13770    @Override
13771    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13772        mContext.enforceCallingOrSelfPermission(
13773                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13774
13775        boolean result = false;
13776        synchronized (mPackages) {
13777            final PackageSetting ps = mSettings.mPackages.get(packageName);
13778            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13779                return false;
13780            }
13781            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13782        }
13783        if (result) {
13784            scheduleWritePackageRestrictionsLocked(userId);
13785        }
13786        return result;
13787    }
13788
13789    @Override
13790    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13791            String packageName) {
13792        final int callingUid = Binder.getCallingUid();
13793        if (getInstantAppPackageName(callingUid) != null) {
13794            return ParceledListSlice.emptyList();
13795        }
13796        synchronized (mPackages) {
13797            final PackageSetting ps = mSettings.mPackages.get(packageName);
13798            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
13799                return ParceledListSlice.emptyList();
13800            }
13801            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13802        }
13803    }
13804
13805    @Override
13806    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13807        if (TextUtils.isEmpty(packageName)) {
13808            return ParceledListSlice.emptyList();
13809        }
13810        final int callingUid = Binder.getCallingUid();
13811        final int callingUserId = UserHandle.getUserId(callingUid);
13812        synchronized (mPackages) {
13813            PackageParser.Package pkg = mPackages.get(packageName);
13814            if (pkg == null || pkg.activities == null) {
13815                return ParceledListSlice.emptyList();
13816            }
13817            if (pkg.mExtras == null) {
13818                return ParceledListSlice.emptyList();
13819            }
13820            final PackageSetting ps = (PackageSetting) pkg.mExtras;
13821            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
13822                return ParceledListSlice.emptyList();
13823            }
13824            final int count = pkg.activities.size();
13825            ArrayList<IntentFilter> result = new ArrayList<>();
13826            for (int n=0; n<count; n++) {
13827                PackageParser.Activity activity = pkg.activities.get(n);
13828                if (activity.intents != null && activity.intents.size() > 0) {
13829                    result.addAll(activity.intents);
13830                }
13831            }
13832            return new ParceledListSlice<>(result);
13833        }
13834    }
13835
13836    @Override
13837    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13838        mContext.enforceCallingOrSelfPermission(
13839                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13840        if (UserHandle.getCallingUserId() != userId) {
13841            mContext.enforceCallingOrSelfPermission(
13842                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13843        }
13844
13845        synchronized (mPackages) {
13846            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13847            if (packageName != null) {
13848                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
13849                        packageName, userId);
13850            }
13851            return result;
13852        }
13853    }
13854
13855    @Override
13856    public String getDefaultBrowserPackageName(int userId) {
13857        if (UserHandle.getCallingUserId() != userId) {
13858            mContext.enforceCallingOrSelfPermission(
13859                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13860        }
13861        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13862            return null;
13863        }
13864        synchronized (mPackages) {
13865            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13866        }
13867    }
13868
13869    /**
13870     * Get the "allow unknown sources" setting.
13871     *
13872     * @return the current "allow unknown sources" setting
13873     */
13874    private int getUnknownSourcesSettings() {
13875        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13876                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13877                -1);
13878    }
13879
13880    @Override
13881    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13882        final int callingUid = Binder.getCallingUid();
13883        if (getInstantAppPackageName(callingUid) != null) {
13884            return;
13885        }
13886        // writer
13887        synchronized (mPackages) {
13888            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13889            if (targetPackageSetting == null
13890                    || filterAppAccessLPr(
13891                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
13892                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13893            }
13894
13895            PackageSetting installerPackageSetting;
13896            if (installerPackageName != null) {
13897                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13898                if (installerPackageSetting == null) {
13899                    throw new IllegalArgumentException("Unknown installer package: "
13900                            + installerPackageName);
13901                }
13902            } else {
13903                installerPackageSetting = null;
13904            }
13905
13906            Signature[] callerSignature;
13907            Object obj = mSettings.getUserIdLPr(callingUid);
13908            if (obj != null) {
13909                if (obj instanceof SharedUserSetting) {
13910                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13911                } else if (obj instanceof PackageSetting) {
13912                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13913                } else {
13914                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
13915                }
13916            } else {
13917                throw new SecurityException("Unknown calling UID: " + callingUid);
13918            }
13919
13920            // Verify: can't set installerPackageName to a package that is
13921            // not signed with the same cert as the caller.
13922            if (installerPackageSetting != null) {
13923                if (compareSignatures(callerSignature,
13924                        installerPackageSetting.signatures.mSignatures)
13925                        != PackageManager.SIGNATURE_MATCH) {
13926                    throw new SecurityException(
13927                            "Caller does not have same cert as new installer package "
13928                            + installerPackageName);
13929                }
13930            }
13931
13932            // Verify: if target already has an installer package, it must
13933            // be signed with the same cert as the caller.
13934            if (targetPackageSetting.installerPackageName != null) {
13935                PackageSetting setting = mSettings.mPackages.get(
13936                        targetPackageSetting.installerPackageName);
13937                // If the currently set package isn't valid, then it's always
13938                // okay to change it.
13939                if (setting != null) {
13940                    if (compareSignatures(callerSignature,
13941                            setting.signatures.mSignatures)
13942                            != PackageManager.SIGNATURE_MATCH) {
13943                        throw new SecurityException(
13944                                "Caller does not have same cert as old installer package "
13945                                + targetPackageSetting.installerPackageName);
13946                    }
13947                }
13948            }
13949
13950            // Okay!
13951            targetPackageSetting.installerPackageName = installerPackageName;
13952            if (installerPackageName != null) {
13953                mSettings.mInstallerPackages.add(installerPackageName);
13954            }
13955            scheduleWriteSettingsLocked();
13956        }
13957    }
13958
13959    @Override
13960    public void setApplicationCategoryHint(String packageName, int categoryHint,
13961            String callerPackageName) {
13962        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13963            throw new SecurityException("Instant applications don't have access to this method");
13964        }
13965        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13966                callerPackageName);
13967        synchronized (mPackages) {
13968            PackageSetting ps = mSettings.mPackages.get(packageName);
13969            if (ps == null) {
13970                throw new IllegalArgumentException("Unknown target package " + packageName);
13971            }
13972            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
13973                throw new IllegalArgumentException("Unknown target package " + packageName);
13974            }
13975            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13976                throw new IllegalArgumentException("Calling package " + callerPackageName
13977                        + " is not installer for " + packageName);
13978            }
13979
13980            if (ps.categoryHint != categoryHint) {
13981                ps.categoryHint = categoryHint;
13982                scheduleWriteSettingsLocked();
13983            }
13984        }
13985    }
13986
13987    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13988        // Queue up an async operation since the package installation may take a little while.
13989        mHandler.post(new Runnable() {
13990            public void run() {
13991                mHandler.removeCallbacks(this);
13992                 // Result object to be returned
13993                PackageInstalledInfo res = new PackageInstalledInfo();
13994                res.setReturnCode(currentStatus);
13995                res.uid = -1;
13996                res.pkg = null;
13997                res.removedInfo = null;
13998                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13999                    args.doPreInstall(res.returnCode);
14000                    synchronized (mInstallLock) {
14001                        installPackageTracedLI(args, res);
14002                    }
14003                    args.doPostInstall(res.returnCode, res.uid);
14004                }
14005
14006                // A restore should be performed at this point if (a) the install
14007                // succeeded, (b) the operation is not an update, and (c) the new
14008                // package has not opted out of backup participation.
14009                final boolean update = res.removedInfo != null
14010                        && res.removedInfo.removedPackage != null;
14011                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14012                boolean doRestore = !update
14013                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14014
14015                // Set up the post-install work request bookkeeping.  This will be used
14016                // and cleaned up by the post-install event handling regardless of whether
14017                // there's a restore pass performed.  Token values are >= 1.
14018                int token;
14019                if (mNextInstallToken < 0) mNextInstallToken = 1;
14020                token = mNextInstallToken++;
14021
14022                PostInstallData data = new PostInstallData(args, res);
14023                mRunningInstalls.put(token, data);
14024                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14025
14026                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14027                    // Pass responsibility to the Backup Manager.  It will perform a
14028                    // restore if appropriate, then pass responsibility back to the
14029                    // Package Manager to run the post-install observer callbacks
14030                    // and broadcasts.
14031                    IBackupManager bm = IBackupManager.Stub.asInterface(
14032                            ServiceManager.getService(Context.BACKUP_SERVICE));
14033                    if (bm != null) {
14034                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14035                                + " to BM for possible restore");
14036                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14037                        try {
14038                            // TODO: http://b/22388012
14039                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14040                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14041                            } else {
14042                                doRestore = false;
14043                            }
14044                        } catch (RemoteException e) {
14045                            // can't happen; the backup manager is local
14046                        } catch (Exception e) {
14047                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14048                            doRestore = false;
14049                        }
14050                    } else {
14051                        Slog.e(TAG, "Backup Manager not found!");
14052                        doRestore = false;
14053                    }
14054                }
14055
14056                if (!doRestore) {
14057                    // No restore possible, or the Backup Manager was mysteriously not
14058                    // available -- just fire the post-install work request directly.
14059                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14060
14061                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14062
14063                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14064                    mHandler.sendMessage(msg);
14065                }
14066            }
14067        });
14068    }
14069
14070    /**
14071     * Callback from PackageSettings whenever an app is first transitioned out of the
14072     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14073     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14074     * here whether the app is the target of an ongoing install, and only send the
14075     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14076     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14077     * handling.
14078     */
14079    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14080        // Serialize this with the rest of the install-process message chain.  In the
14081        // restore-at-install case, this Runnable will necessarily run before the
14082        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14083        // are coherent.  In the non-restore case, the app has already completed install
14084        // and been launched through some other means, so it is not in a problematic
14085        // state for observers to see the FIRST_LAUNCH signal.
14086        mHandler.post(new Runnable() {
14087            @Override
14088            public void run() {
14089                for (int i = 0; i < mRunningInstalls.size(); i++) {
14090                    final PostInstallData data = mRunningInstalls.valueAt(i);
14091                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14092                        continue;
14093                    }
14094                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14095                        // right package; but is it for the right user?
14096                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14097                            if (userId == data.res.newUsers[uIndex]) {
14098                                if (DEBUG_BACKUP) {
14099                                    Slog.i(TAG, "Package " + pkgName
14100                                            + " being restored so deferring FIRST_LAUNCH");
14101                                }
14102                                return;
14103                            }
14104                        }
14105                    }
14106                }
14107                // didn't find it, so not being restored
14108                if (DEBUG_BACKUP) {
14109                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14110                }
14111                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14112            }
14113        });
14114    }
14115
14116    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14117        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14118                installerPkg, null, userIds);
14119    }
14120
14121    private abstract class HandlerParams {
14122        private static final int MAX_RETRIES = 4;
14123
14124        /**
14125         * Number of times startCopy() has been attempted and had a non-fatal
14126         * error.
14127         */
14128        private int mRetries = 0;
14129
14130        /** User handle for the user requesting the information or installation. */
14131        private final UserHandle mUser;
14132        String traceMethod;
14133        int traceCookie;
14134
14135        HandlerParams(UserHandle user) {
14136            mUser = user;
14137        }
14138
14139        UserHandle getUser() {
14140            return mUser;
14141        }
14142
14143        HandlerParams setTraceMethod(String traceMethod) {
14144            this.traceMethod = traceMethod;
14145            return this;
14146        }
14147
14148        HandlerParams setTraceCookie(int traceCookie) {
14149            this.traceCookie = traceCookie;
14150            return this;
14151        }
14152
14153        final boolean startCopy() {
14154            boolean res;
14155            try {
14156                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14157
14158                if (++mRetries > MAX_RETRIES) {
14159                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14160                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14161                    handleServiceError();
14162                    return false;
14163                } else {
14164                    handleStartCopy();
14165                    res = true;
14166                }
14167            } catch (RemoteException e) {
14168                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14169                mHandler.sendEmptyMessage(MCS_RECONNECT);
14170                res = false;
14171            }
14172            handleReturnCode();
14173            return res;
14174        }
14175
14176        final void serviceError() {
14177            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14178            handleServiceError();
14179            handleReturnCode();
14180        }
14181
14182        abstract void handleStartCopy() throws RemoteException;
14183        abstract void handleServiceError();
14184        abstract void handleReturnCode();
14185    }
14186
14187    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14188        for (File path : paths) {
14189            try {
14190                mcs.clearDirectory(path.getAbsolutePath());
14191            } catch (RemoteException e) {
14192            }
14193        }
14194    }
14195
14196    static class OriginInfo {
14197        /**
14198         * Location where install is coming from, before it has been
14199         * copied/renamed into place. This could be a single monolithic APK
14200         * file, or a cluster directory. This location may be untrusted.
14201         */
14202        final File file;
14203
14204        /**
14205         * Flag indicating that {@link #file} or {@link #cid} has already been
14206         * staged, meaning downstream users don't need to defensively copy the
14207         * contents.
14208         */
14209        final boolean staged;
14210
14211        /**
14212         * Flag indicating that {@link #file} or {@link #cid} is an already
14213         * installed app that is being moved.
14214         */
14215        final boolean existing;
14216
14217        final String resolvedPath;
14218        final File resolvedFile;
14219
14220        static OriginInfo fromNothing() {
14221            return new OriginInfo(null, false, false);
14222        }
14223
14224        static OriginInfo fromUntrustedFile(File file) {
14225            return new OriginInfo(file, false, false);
14226        }
14227
14228        static OriginInfo fromExistingFile(File file) {
14229            return new OriginInfo(file, false, true);
14230        }
14231
14232        static OriginInfo fromStagedFile(File file) {
14233            return new OriginInfo(file, true, false);
14234        }
14235
14236        private OriginInfo(File file, boolean staged, boolean existing) {
14237            this.file = file;
14238            this.staged = staged;
14239            this.existing = existing;
14240
14241            if (file != null) {
14242                resolvedPath = file.getAbsolutePath();
14243                resolvedFile = file;
14244            } else {
14245                resolvedPath = null;
14246                resolvedFile = null;
14247            }
14248        }
14249    }
14250
14251    static class MoveInfo {
14252        final int moveId;
14253        final String fromUuid;
14254        final String toUuid;
14255        final String packageName;
14256        final String dataAppName;
14257        final int appId;
14258        final String seinfo;
14259        final int targetSdkVersion;
14260
14261        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14262                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14263            this.moveId = moveId;
14264            this.fromUuid = fromUuid;
14265            this.toUuid = toUuid;
14266            this.packageName = packageName;
14267            this.dataAppName = dataAppName;
14268            this.appId = appId;
14269            this.seinfo = seinfo;
14270            this.targetSdkVersion = targetSdkVersion;
14271        }
14272    }
14273
14274    static class VerificationInfo {
14275        /** A constant used to indicate that a uid value is not present. */
14276        public static final int NO_UID = -1;
14277
14278        /** URI referencing where the package was downloaded from. */
14279        final Uri originatingUri;
14280
14281        /** HTTP referrer URI associated with the originatingURI. */
14282        final Uri referrer;
14283
14284        /** UID of the application that the install request originated from. */
14285        final int originatingUid;
14286
14287        /** UID of application requesting the install */
14288        final int installerUid;
14289
14290        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14291            this.originatingUri = originatingUri;
14292            this.referrer = referrer;
14293            this.originatingUid = originatingUid;
14294            this.installerUid = installerUid;
14295        }
14296    }
14297
14298    class InstallParams extends HandlerParams {
14299        final OriginInfo origin;
14300        final MoveInfo move;
14301        final IPackageInstallObserver2 observer;
14302        int installFlags;
14303        final String installerPackageName;
14304        final String volumeUuid;
14305        private InstallArgs mArgs;
14306        private int mRet;
14307        final String packageAbiOverride;
14308        final String[] grantedRuntimePermissions;
14309        final VerificationInfo verificationInfo;
14310        final Certificate[][] certificates;
14311        final int installReason;
14312
14313        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14314                int installFlags, String installerPackageName, String volumeUuid,
14315                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14316                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14317            super(user);
14318            this.origin = origin;
14319            this.move = move;
14320            this.observer = observer;
14321            this.installFlags = installFlags;
14322            this.installerPackageName = installerPackageName;
14323            this.volumeUuid = volumeUuid;
14324            this.verificationInfo = verificationInfo;
14325            this.packageAbiOverride = packageAbiOverride;
14326            this.grantedRuntimePermissions = grantedPermissions;
14327            this.certificates = certificates;
14328            this.installReason = installReason;
14329        }
14330
14331        @Override
14332        public String toString() {
14333            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14334                    + " file=" + origin.file + "}";
14335        }
14336
14337        private int installLocationPolicy(PackageInfoLite pkgLite) {
14338            String packageName = pkgLite.packageName;
14339            int installLocation = pkgLite.installLocation;
14340            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14341            // reader
14342            synchronized (mPackages) {
14343                // Currently installed package which the new package is attempting to replace or
14344                // null if no such package is installed.
14345                PackageParser.Package installedPkg = mPackages.get(packageName);
14346                // Package which currently owns the data which the new package will own if installed.
14347                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14348                // will be null whereas dataOwnerPkg will contain information about the package
14349                // which was uninstalled while keeping its data.
14350                PackageParser.Package dataOwnerPkg = installedPkg;
14351                if (dataOwnerPkg  == null) {
14352                    PackageSetting ps = mSettings.mPackages.get(packageName);
14353                    if (ps != null) {
14354                        dataOwnerPkg = ps.pkg;
14355                    }
14356                }
14357
14358                if (dataOwnerPkg != null) {
14359                    // If installed, the package will get access to data left on the device by its
14360                    // predecessor. As a security measure, this is permited only if this is not a
14361                    // version downgrade or if the predecessor package is marked as debuggable and
14362                    // a downgrade is explicitly requested.
14363                    //
14364                    // On debuggable platform builds, downgrades are permitted even for
14365                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14366                    // not offer security guarantees and thus it's OK to disable some security
14367                    // mechanisms to make debugging/testing easier on those builds. However, even on
14368                    // debuggable builds downgrades of packages are permitted only if requested via
14369                    // installFlags. This is because we aim to keep the behavior of debuggable
14370                    // platform builds as close as possible to the behavior of non-debuggable
14371                    // platform builds.
14372                    final boolean downgradeRequested =
14373                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14374                    final boolean packageDebuggable =
14375                                (dataOwnerPkg.applicationInfo.flags
14376                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14377                    final boolean downgradePermitted =
14378                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14379                    if (!downgradePermitted) {
14380                        try {
14381                            checkDowngrade(dataOwnerPkg, pkgLite);
14382                        } catch (PackageManagerException e) {
14383                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14384                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14385                        }
14386                    }
14387                }
14388
14389                if (installedPkg != null) {
14390                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14391                        // Check for updated system application.
14392                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14393                            if (onSd) {
14394                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14395                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14396                            }
14397                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14398                        } else {
14399                            if (onSd) {
14400                                // Install flag overrides everything.
14401                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14402                            }
14403                            // If current upgrade specifies particular preference
14404                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14405                                // Application explicitly specified internal.
14406                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14407                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14408                                // App explictly prefers external. Let policy decide
14409                            } else {
14410                                // Prefer previous location
14411                                if (isExternal(installedPkg)) {
14412                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14413                                }
14414                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14415                            }
14416                        }
14417                    } else {
14418                        // Invalid install. Return error code
14419                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14420                    }
14421                }
14422            }
14423            // All the special cases have been taken care of.
14424            // Return result based on recommended install location.
14425            if (onSd) {
14426                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14427            }
14428            return pkgLite.recommendedInstallLocation;
14429        }
14430
14431        /*
14432         * Invoke remote method to get package information and install
14433         * location values. Override install location based on default
14434         * policy if needed and then create install arguments based
14435         * on the install location.
14436         */
14437        public void handleStartCopy() throws RemoteException {
14438            int ret = PackageManager.INSTALL_SUCCEEDED;
14439
14440            // If we're already staged, we've firmly committed to an install location
14441            if (origin.staged) {
14442                if (origin.file != null) {
14443                    installFlags |= PackageManager.INSTALL_INTERNAL;
14444                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14445                } else {
14446                    throw new IllegalStateException("Invalid stage location");
14447                }
14448            }
14449
14450            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14451            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14452            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14453            PackageInfoLite pkgLite = null;
14454
14455            if (onInt && onSd) {
14456                // Check if both bits are set.
14457                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14458                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14459            } else if (onSd && ephemeral) {
14460                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14461                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14462            } else {
14463                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14464                        packageAbiOverride);
14465
14466                if (DEBUG_EPHEMERAL && ephemeral) {
14467                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14468                }
14469
14470                /*
14471                 * If we have too little free space, try to free cache
14472                 * before giving up.
14473                 */
14474                if (!origin.staged && pkgLite.recommendedInstallLocation
14475                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14476                    // TODO: focus freeing disk space on the target device
14477                    final StorageManager storage = StorageManager.from(mContext);
14478                    final long lowThreshold = storage.getStorageLowBytes(
14479                            Environment.getDataDirectory());
14480
14481                    final long sizeBytes = mContainerService.calculateInstalledSize(
14482                            origin.resolvedPath, packageAbiOverride);
14483
14484                    try {
14485                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
14486                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14487                                installFlags, packageAbiOverride);
14488                    } catch (InstallerException e) {
14489                        Slog.w(TAG, "Failed to free cache", e);
14490                    }
14491
14492                    /*
14493                     * The cache free must have deleted the file we
14494                     * downloaded to install.
14495                     *
14496                     * TODO: fix the "freeCache" call to not delete
14497                     *       the file we care about.
14498                     */
14499                    if (pkgLite.recommendedInstallLocation
14500                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14501                        pkgLite.recommendedInstallLocation
14502                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14503                    }
14504                }
14505            }
14506
14507            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14508                int loc = pkgLite.recommendedInstallLocation;
14509                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14510                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14511                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14512                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14513                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14514                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14515                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14516                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14517                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14518                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14519                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14520                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14521                } else {
14522                    // Override with defaults if needed.
14523                    loc = installLocationPolicy(pkgLite);
14524                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14525                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14526                    } else if (!onSd && !onInt) {
14527                        // Override install location with flags
14528                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14529                            // Set the flag to install on external media.
14530                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14531                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14532                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14533                            if (DEBUG_EPHEMERAL) {
14534                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14535                            }
14536                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14537                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14538                                    |PackageManager.INSTALL_INTERNAL);
14539                        } else {
14540                            // Make sure the flag for installing on external
14541                            // media is unset
14542                            installFlags |= PackageManager.INSTALL_INTERNAL;
14543                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14544                        }
14545                    }
14546                }
14547            }
14548
14549            final InstallArgs args = createInstallArgs(this);
14550            mArgs = args;
14551
14552            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14553                // TODO: http://b/22976637
14554                // Apps installed for "all" users use the device owner to verify the app
14555                UserHandle verifierUser = getUser();
14556                if (verifierUser == UserHandle.ALL) {
14557                    verifierUser = UserHandle.SYSTEM;
14558                }
14559
14560                /*
14561                 * Determine if we have any installed package verifiers. If we
14562                 * do, then we'll defer to them to verify the packages.
14563                 */
14564                final int requiredUid = mRequiredVerifierPackage == null ? -1
14565                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14566                                verifierUser.getIdentifier());
14567                final int installerUid =
14568                        verificationInfo == null ? -1 : verificationInfo.installerUid;
14569                if (!origin.existing && requiredUid != -1
14570                        && isVerificationEnabled(
14571                                verifierUser.getIdentifier(), installFlags, installerUid)) {
14572                    final Intent verification = new Intent(
14573                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14574                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14575                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14576                            PACKAGE_MIME_TYPE);
14577                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14578
14579                    // Query all live verifiers based on current user state
14580                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14581                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
14582                            false /*allowDynamicSplits*/);
14583
14584                    if (DEBUG_VERIFY) {
14585                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14586                                + verification.toString() + " with " + pkgLite.verifiers.length
14587                                + " optional verifiers");
14588                    }
14589
14590                    final int verificationId = mPendingVerificationToken++;
14591
14592                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14593
14594                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14595                            installerPackageName);
14596
14597                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14598                            installFlags);
14599
14600                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14601                            pkgLite.packageName);
14602
14603                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14604                            pkgLite.versionCode);
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            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14998            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14999                    afterCodeFile, pkg.baseCodePath));
15000            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15001                    afterCodeFile, pkg.splitCodePaths));
15002
15003            // Reflect the rename in app info
15004            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15005            pkg.setApplicationInfoCodePath(pkg.codePath);
15006            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15007            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15008            pkg.setApplicationInfoResourcePath(pkg.codePath);
15009            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15010            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15011
15012            return true;
15013        }
15014
15015        int doPostInstall(int status, int uid) {
15016            if (status != PackageManager.INSTALL_SUCCEEDED) {
15017                cleanUp();
15018            }
15019            return status;
15020        }
15021
15022        @Override
15023        String getCodePath() {
15024            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15025        }
15026
15027        @Override
15028        String getResourcePath() {
15029            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15030        }
15031
15032        private boolean cleanUp() {
15033            if (codeFile == null || !codeFile.exists()) {
15034                return false;
15035            }
15036
15037            removeCodePathLI(codeFile);
15038
15039            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15040                resourceFile.delete();
15041            }
15042
15043            return true;
15044        }
15045
15046        void cleanUpResourcesLI() {
15047            // Try enumerating all code paths before deleting
15048            List<String> allCodePaths = Collections.EMPTY_LIST;
15049            if (codeFile != null && codeFile.exists()) {
15050                try {
15051                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15052                    allCodePaths = pkg.getAllCodePaths();
15053                } catch (PackageParserException e) {
15054                    // Ignored; we tried our best
15055                }
15056            }
15057
15058            cleanUp();
15059            removeDexFiles(allCodePaths, instructionSets);
15060        }
15061
15062        boolean doPostDeleteLI(boolean delete) {
15063            // XXX err, shouldn't we respect the delete flag?
15064            cleanUpResourcesLI();
15065            return true;
15066        }
15067    }
15068
15069    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15070            PackageManagerException {
15071        if (copyRet < 0) {
15072            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15073                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15074                throw new PackageManagerException(copyRet, message);
15075            }
15076        }
15077    }
15078
15079    /**
15080     * Extract the StorageManagerService "container ID" from the full code path of an
15081     * .apk.
15082     */
15083    static String cidFromCodePath(String fullCodePath) {
15084        int eidx = fullCodePath.lastIndexOf("/");
15085        String subStr1 = fullCodePath.substring(0, eidx);
15086        int sidx = subStr1.lastIndexOf("/");
15087        return subStr1.substring(sidx+1, eidx);
15088    }
15089
15090    /**
15091     * Logic to handle movement of existing installed applications.
15092     */
15093    class MoveInstallArgs extends InstallArgs {
15094        private File codeFile;
15095        private File resourceFile;
15096
15097        /** New install */
15098        MoveInstallArgs(InstallParams params) {
15099            super(params.origin, params.move, params.observer, params.installFlags,
15100                    params.installerPackageName, params.volumeUuid,
15101                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15102                    params.grantedRuntimePermissions,
15103                    params.traceMethod, params.traceCookie, params.certificates,
15104                    params.installReason);
15105        }
15106
15107        int copyApk(IMediaContainerService imcs, boolean temp) {
15108            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15109                    + move.fromUuid + " to " + move.toUuid);
15110            synchronized (mInstaller) {
15111                try {
15112                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15113                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15114                } catch (InstallerException e) {
15115                    Slog.w(TAG, "Failed to move app", e);
15116                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15117                }
15118            }
15119
15120            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15121            resourceFile = codeFile;
15122            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15123
15124            return PackageManager.INSTALL_SUCCEEDED;
15125        }
15126
15127        int doPreInstall(int status) {
15128            if (status != PackageManager.INSTALL_SUCCEEDED) {
15129                cleanUp(move.toUuid);
15130            }
15131            return status;
15132        }
15133
15134        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15135            if (status != PackageManager.INSTALL_SUCCEEDED) {
15136                cleanUp(move.toUuid);
15137                return false;
15138            }
15139
15140            // Reflect the move in app info
15141            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15142            pkg.setApplicationInfoCodePath(pkg.codePath);
15143            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15144            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15145            pkg.setApplicationInfoResourcePath(pkg.codePath);
15146            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15147            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15148
15149            return true;
15150        }
15151
15152        int doPostInstall(int status, int uid) {
15153            if (status == PackageManager.INSTALL_SUCCEEDED) {
15154                cleanUp(move.fromUuid);
15155            } else {
15156                cleanUp(move.toUuid);
15157            }
15158            return status;
15159        }
15160
15161        @Override
15162        String getCodePath() {
15163            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15164        }
15165
15166        @Override
15167        String getResourcePath() {
15168            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15169        }
15170
15171        private boolean cleanUp(String volumeUuid) {
15172            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15173                    move.dataAppName);
15174            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15175            final int[] userIds = sUserManager.getUserIds();
15176            synchronized (mInstallLock) {
15177                // Clean up both app data and code
15178                // All package moves are frozen until finished
15179                for (int userId : userIds) {
15180                    try {
15181                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15182                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15183                    } catch (InstallerException e) {
15184                        Slog.w(TAG, String.valueOf(e));
15185                    }
15186                }
15187                removeCodePathLI(codeFile);
15188            }
15189            return true;
15190        }
15191
15192        void cleanUpResourcesLI() {
15193            throw new UnsupportedOperationException();
15194        }
15195
15196        boolean doPostDeleteLI(boolean delete) {
15197            throw new UnsupportedOperationException();
15198        }
15199    }
15200
15201    static String getAsecPackageName(String packageCid) {
15202        int idx = packageCid.lastIndexOf("-");
15203        if (idx == -1) {
15204            return packageCid;
15205        }
15206        return packageCid.substring(0, idx);
15207    }
15208
15209    // Utility method used to create code paths based on package name and available index.
15210    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15211        String idxStr = "";
15212        int idx = 1;
15213        // Fall back to default value of idx=1 if prefix is not
15214        // part of oldCodePath
15215        if (oldCodePath != null) {
15216            String subStr = oldCodePath;
15217            // Drop the suffix right away
15218            if (suffix != null && subStr.endsWith(suffix)) {
15219                subStr = subStr.substring(0, subStr.length() - suffix.length());
15220            }
15221            // If oldCodePath already contains prefix find out the
15222            // ending index to either increment or decrement.
15223            int sidx = subStr.lastIndexOf(prefix);
15224            if (sidx != -1) {
15225                subStr = subStr.substring(sidx + prefix.length());
15226                if (subStr != null) {
15227                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15228                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15229                    }
15230                    try {
15231                        idx = Integer.parseInt(subStr);
15232                        if (idx <= 1) {
15233                            idx++;
15234                        } else {
15235                            idx--;
15236                        }
15237                    } catch(NumberFormatException e) {
15238                    }
15239                }
15240            }
15241        }
15242        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15243        return prefix + idxStr;
15244    }
15245
15246    private File getNextCodePath(File targetDir, String packageName) {
15247        File result;
15248        SecureRandom random = new SecureRandom();
15249        byte[] bytes = new byte[16];
15250        do {
15251            random.nextBytes(bytes);
15252            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15253            result = new File(targetDir, packageName + "-" + suffix);
15254        } while (result.exists());
15255        return result;
15256    }
15257
15258    // Utility method that returns the relative package path with respect
15259    // to the installation directory. Like say for /data/data/com.test-1.apk
15260    // string com.test-1 is returned.
15261    static String deriveCodePathName(String codePath) {
15262        if (codePath == null) {
15263            return null;
15264        }
15265        final File codeFile = new File(codePath);
15266        final String name = codeFile.getName();
15267        if (codeFile.isDirectory()) {
15268            return name;
15269        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15270            final int lastDot = name.lastIndexOf('.');
15271            return name.substring(0, lastDot);
15272        } else {
15273            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15274            return null;
15275        }
15276    }
15277
15278    static class PackageInstalledInfo {
15279        String name;
15280        int uid;
15281        // The set of users that originally had this package installed.
15282        int[] origUsers;
15283        // The set of users that now have this package installed.
15284        int[] newUsers;
15285        PackageParser.Package pkg;
15286        int returnCode;
15287        String returnMsg;
15288        String installerPackageName;
15289        PackageRemovedInfo removedInfo;
15290        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15291
15292        public void setError(int code, String msg) {
15293            setReturnCode(code);
15294            setReturnMessage(msg);
15295            Slog.w(TAG, msg);
15296        }
15297
15298        public void setError(String msg, PackageParserException e) {
15299            setReturnCode(e.error);
15300            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15301            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15302            for (int i = 0; i < childCount; i++) {
15303                addedChildPackages.valueAt(i).setError(msg, e);
15304            }
15305            Slog.w(TAG, msg, e);
15306        }
15307
15308        public void setError(String msg, PackageManagerException e) {
15309            returnCode = e.error;
15310            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15311            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15312            for (int i = 0; i < childCount; i++) {
15313                addedChildPackages.valueAt(i).setError(msg, e);
15314            }
15315            Slog.w(TAG, msg, e);
15316        }
15317
15318        public void setReturnCode(int returnCode) {
15319            this.returnCode = returnCode;
15320            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15321            for (int i = 0; i < childCount; i++) {
15322                addedChildPackages.valueAt(i).returnCode = returnCode;
15323            }
15324        }
15325
15326        private void setReturnMessage(String returnMsg) {
15327            this.returnMsg = returnMsg;
15328            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15329            for (int i = 0; i < childCount; i++) {
15330                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15331            }
15332        }
15333
15334        // In some error cases we want to convey more info back to the observer
15335        String origPackage;
15336        String origPermission;
15337    }
15338
15339    /*
15340     * Install a non-existing package.
15341     */
15342    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15343            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15344            String volumeUuid, PackageInstalledInfo res, int installReason) {
15345        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15346
15347        // Remember this for later, in case we need to rollback this install
15348        String pkgName = pkg.packageName;
15349
15350        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15351
15352        synchronized(mPackages) {
15353            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15354            if (renamedPackage != null) {
15355                // A package with the same name is already installed, though
15356                // it has been renamed to an older name.  The package we
15357                // are trying to install should be installed as an update to
15358                // the existing one, but that has not been requested, so bail.
15359                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15360                        + " without first uninstalling package running as "
15361                        + renamedPackage);
15362                return;
15363            }
15364            if (mPackages.containsKey(pkgName)) {
15365                // Don't allow installation over an existing package with the same name.
15366                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15367                        + " without first uninstalling.");
15368                return;
15369            }
15370        }
15371
15372        try {
15373            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
15374                    System.currentTimeMillis(), user);
15375
15376            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15377
15378            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15379                prepareAppDataAfterInstallLIF(newPackage);
15380
15381            } else {
15382                // Remove package from internal structures, but keep around any
15383                // data that might have already existed
15384                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15385                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15386            }
15387        } catch (PackageManagerException e) {
15388            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15389        }
15390
15391        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15392    }
15393
15394    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15395        try (DigestInputStream digestStream =
15396                new DigestInputStream(new FileInputStream(file), digest)) {
15397            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15398        }
15399    }
15400
15401    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
15402            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
15403            PackageInstalledInfo res, int installReason) {
15404        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15405
15406        final PackageParser.Package oldPackage;
15407        final PackageSetting ps;
15408        final String pkgName = pkg.packageName;
15409        final int[] allUsers;
15410        final int[] installedUsers;
15411
15412        synchronized(mPackages) {
15413            oldPackage = mPackages.get(pkgName);
15414            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15415
15416            // don't allow upgrade to target a release SDK from a pre-release SDK
15417            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15418                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15419            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15420                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15421            if (oldTargetsPreRelease
15422                    && !newTargetsPreRelease
15423                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15424                Slog.w(TAG, "Can't install package targeting released sdk");
15425                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15426                return;
15427            }
15428
15429            ps = mSettings.mPackages.get(pkgName);
15430
15431            // verify signatures are valid
15432            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
15433            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
15434                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
15435                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15436                            "New package not signed by keys specified by upgrade-keysets: "
15437                                    + pkgName);
15438                    return;
15439                }
15440            } else {
15441                // default to original signature matching
15442                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15443                        != PackageManager.SIGNATURE_MATCH) {
15444                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15445                            "New package has a different signature: " + pkgName);
15446                    return;
15447                }
15448            }
15449
15450            // don't allow a system upgrade unless the upgrade hash matches
15451            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
15452                byte[] digestBytes = null;
15453                try {
15454                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15455                    updateDigest(digest, new File(pkg.baseCodePath));
15456                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15457                        for (String path : pkg.splitCodePaths) {
15458                            updateDigest(digest, new File(path));
15459                        }
15460                    }
15461                    digestBytes = digest.digest();
15462                } catch (NoSuchAlgorithmException | IOException e) {
15463                    res.setError(INSTALL_FAILED_INVALID_APK,
15464                            "Could not compute hash: " + pkgName);
15465                    return;
15466                }
15467                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15468                    res.setError(INSTALL_FAILED_INVALID_APK,
15469                            "New package fails restrict-update check: " + pkgName);
15470                    return;
15471                }
15472                // retain upgrade restriction
15473                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15474            }
15475
15476            // Check for shared user id changes
15477            String invalidPackageName =
15478                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15479            if (invalidPackageName != null) {
15480                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15481                        "Package " + invalidPackageName + " tried to change user "
15482                                + oldPackage.mSharedUserId);
15483                return;
15484            }
15485
15486            // In case of rollback, remember per-user/profile install state
15487            allUsers = sUserManager.getUserIds();
15488            installedUsers = ps.queryInstalledUsers(allUsers, true);
15489
15490            // don't allow an upgrade from full to ephemeral
15491            if (isInstantApp) {
15492                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15493                    for (int currentUser : allUsers) {
15494                        if (!ps.getInstantApp(currentUser)) {
15495                            // can't downgrade from full to instant
15496                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15497                                    + " for user: " + currentUser);
15498                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15499                            return;
15500                        }
15501                    }
15502                } else if (!ps.getInstantApp(user.getIdentifier())) {
15503                    // can't downgrade from full to instant
15504                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15505                            + " for user: " + user.getIdentifier());
15506                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15507                    return;
15508                }
15509            }
15510        }
15511
15512        // Update what is removed
15513        res.removedInfo = new PackageRemovedInfo(this);
15514        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15515        res.removedInfo.removedPackage = oldPackage.packageName;
15516        res.removedInfo.installerPackageName = ps.installerPackageName;
15517        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15518        res.removedInfo.isUpdate = true;
15519        res.removedInfo.origUsers = installedUsers;
15520        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15521        for (int i = 0; i < installedUsers.length; i++) {
15522            final int userId = installedUsers[i];
15523            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15524        }
15525
15526        final int childCount = (oldPackage.childPackages != null)
15527                ? oldPackage.childPackages.size() : 0;
15528        for (int i = 0; i < childCount; i++) {
15529            boolean childPackageUpdated = false;
15530            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15531            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15532            if (res.addedChildPackages != null) {
15533                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15534                if (childRes != null) {
15535                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15536                    childRes.removedInfo.removedPackage = childPkg.packageName;
15537                    if (childPs != null) {
15538                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
15539                    }
15540                    childRes.removedInfo.isUpdate = true;
15541                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15542                    childPackageUpdated = true;
15543                }
15544            }
15545            if (!childPackageUpdated) {
15546                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
15547                childRemovedRes.removedPackage = childPkg.packageName;
15548                if (childPs != null) {
15549                    childRemovedRes.installerPackageName = childPs.installerPackageName;
15550                }
15551                childRemovedRes.isUpdate = false;
15552                childRemovedRes.dataRemoved = true;
15553                synchronized (mPackages) {
15554                    if (childPs != null) {
15555                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15556                    }
15557                }
15558                if (res.removedInfo.removedChildPackages == null) {
15559                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15560                }
15561                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15562            }
15563        }
15564
15565        boolean sysPkg = (isSystemApp(oldPackage));
15566        if (sysPkg) {
15567            // Set the system/privileged/oem flags as needed
15568            final boolean privileged =
15569                    (oldPackage.applicationInfo.privateFlags
15570                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15571            final boolean oem =
15572                    (oldPackage.applicationInfo.privateFlags
15573                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
15574            final @ParseFlags int systemParseFlags = parseFlags;
15575            final @ScanFlags int systemScanFlags = scanFlags
15576                    | SCAN_AS_SYSTEM
15577                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
15578                    | (oem ? SCAN_AS_OEM : 0);
15579
15580            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
15581                    user, allUsers, installerPackageName, res, installReason);
15582        } else {
15583            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
15584                    user, allUsers, installerPackageName, res, installReason);
15585        }
15586    }
15587
15588    @Override
15589    public List<String> getPreviousCodePaths(String packageName) {
15590        final int callingUid = Binder.getCallingUid();
15591        final List<String> result = new ArrayList<>();
15592        if (getInstantAppPackageName(callingUid) != null) {
15593            return result;
15594        }
15595        final PackageSetting ps = mSettings.mPackages.get(packageName);
15596        if (ps != null
15597                && ps.oldCodePaths != null
15598                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15599            result.addAll(ps.oldCodePaths);
15600        }
15601        return result;
15602    }
15603
15604    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15605            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15606            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
15607            String installerPackageName, PackageInstalledInfo res, int installReason) {
15608        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15609                + deletedPackage);
15610
15611        String pkgName = deletedPackage.packageName;
15612        boolean deletedPkg = true;
15613        boolean addedPkg = false;
15614        boolean updatedSettings = false;
15615        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15616        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15617                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15618
15619        final long origUpdateTime = (pkg.mExtras != null)
15620                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15621
15622        // First delete the existing package while retaining the data directory
15623        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15624                res.removedInfo, true, pkg)) {
15625            // If the existing package wasn't successfully deleted
15626            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15627            deletedPkg = false;
15628        } else {
15629            // Successfully deleted the old package; proceed with replace.
15630
15631            // If deleted package lived in a container, give users a chance to
15632            // relinquish resources before killing.
15633            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15634                if (DEBUG_INSTALL) {
15635                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15636                }
15637                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15638                final ArrayList<String> pkgList = new ArrayList<String>(1);
15639                pkgList.add(deletedPackage.applicationInfo.packageName);
15640                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15641            }
15642
15643            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15644                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15645            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15646
15647            try {
15648                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
15649                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15650                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15651                        installReason);
15652
15653                // Update the in-memory copy of the previous code paths.
15654                PackageSetting ps = mSettings.mPackages.get(pkgName);
15655                if (!killApp) {
15656                    if (ps.oldCodePaths == null) {
15657                        ps.oldCodePaths = new ArraySet<>();
15658                    }
15659                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15660                    if (deletedPackage.splitCodePaths != null) {
15661                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15662                    }
15663                } else {
15664                    ps.oldCodePaths = null;
15665                }
15666                if (ps.childPackageNames != null) {
15667                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15668                        final String childPkgName = ps.childPackageNames.get(i);
15669                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15670                        childPs.oldCodePaths = ps.oldCodePaths;
15671                    }
15672                }
15673                // set instant app status, but, only if it's explicitly specified
15674                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15675                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
15676                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
15677                prepareAppDataAfterInstallLIF(newPackage);
15678                addedPkg = true;
15679                mDexManager.notifyPackageUpdated(newPackage.packageName,
15680                        newPackage.baseCodePath, newPackage.splitCodePaths);
15681            } catch (PackageManagerException e) {
15682                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15683            }
15684        }
15685
15686        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15687            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15688
15689            // Revert all internal state mutations and added folders for the failed install
15690            if (addedPkg) {
15691                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15692                        res.removedInfo, true, null);
15693            }
15694
15695            // Restore the old package
15696            if (deletedPkg) {
15697                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15698                File restoreFile = new File(deletedPackage.codePath);
15699                // Parse old package
15700                boolean oldExternal = isExternal(deletedPackage);
15701                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15702                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15703                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15704                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15705                try {
15706                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15707                            null);
15708                } catch (PackageManagerException e) {
15709                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
15710                            + e.getMessage());
15711                    return;
15712                }
15713
15714                synchronized (mPackages) {
15715                    // Ensure the installer package name up to date
15716                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15717
15718                    // Update permissions for restored package
15719                    mPermissionManager.updatePermissions(
15720                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15721                            mPermissionCallback);
15722
15723                    mSettings.writeLPr();
15724                }
15725
15726                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
15727            }
15728        } else {
15729            synchronized (mPackages) {
15730                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
15731                if (ps != null) {
15732                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15733                    if (res.removedInfo.removedChildPackages != null) {
15734                        final int childCount = res.removedInfo.removedChildPackages.size();
15735                        // Iterate in reverse as we may modify the collection
15736                        for (int i = childCount - 1; i >= 0; i--) {
15737                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
15738                            if (res.addedChildPackages.containsKey(childPackageName)) {
15739                                res.removedInfo.removedChildPackages.removeAt(i);
15740                            } else {
15741                                PackageRemovedInfo childInfo = res.removedInfo
15742                                        .removedChildPackages.valueAt(i);
15743                                childInfo.removedForAllUsers = mPackages.get(
15744                                        childInfo.removedPackage) == null;
15745                            }
15746                        }
15747                    }
15748                }
15749            }
15750        }
15751    }
15752
15753    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
15754            PackageParser.Package pkg, final @ParseFlags int parseFlags,
15755            final @ScanFlags int scanFlags, UserHandle user,
15756            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15757            int installReason) {
15758        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
15759                + ", old=" + deletedPackage);
15760
15761        final boolean disabledSystem;
15762
15763        // Remove existing system package
15764        removePackageLI(deletedPackage, true);
15765
15766        synchronized (mPackages) {
15767            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
15768        }
15769        if (!disabledSystem) {
15770            // We didn't need to disable the .apk as a current system package,
15771            // which means we are replacing another update that is already
15772            // installed.  We need to make sure to delete the older one's .apk.
15773            res.removedInfo.args = createInstallArgsForExisting(0,
15774                    deletedPackage.applicationInfo.getCodePath(),
15775                    deletedPackage.applicationInfo.getResourcePath(),
15776                    getAppDexInstructionSets(deletedPackage.applicationInfo));
15777        } else {
15778            res.removedInfo.args = null;
15779        }
15780
15781        // Successfully disabled the old package. Now proceed with re-installation
15782        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15783                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15784        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15785
15786        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15787        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
15788                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
15789
15790        PackageParser.Package newPackage = null;
15791        try {
15792            // Add the package to the internal data structures
15793            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
15794
15795            // Set the update and install times
15796            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
15797            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
15798                    System.currentTimeMillis());
15799
15800            // Update the package dynamic state if succeeded
15801            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15802                // Now that the install succeeded make sure we remove data
15803                // directories for any child package the update removed.
15804                final int deletedChildCount = (deletedPackage.childPackages != null)
15805                        ? deletedPackage.childPackages.size() : 0;
15806                final int newChildCount = (newPackage.childPackages != null)
15807                        ? newPackage.childPackages.size() : 0;
15808                for (int i = 0; i < deletedChildCount; i++) {
15809                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
15810                    boolean childPackageDeleted = true;
15811                    for (int j = 0; j < newChildCount; j++) {
15812                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
15813                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
15814                            childPackageDeleted = false;
15815                            break;
15816                        }
15817                    }
15818                    if (childPackageDeleted) {
15819                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
15820                                deletedChildPkg.packageName);
15821                        if (ps != null && res.removedInfo.removedChildPackages != null) {
15822                            PackageRemovedInfo removedChildRes = res.removedInfo
15823                                    .removedChildPackages.get(deletedChildPkg.packageName);
15824                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
15825                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
15826                        }
15827                    }
15828                }
15829
15830                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15831                        installReason);
15832                prepareAppDataAfterInstallLIF(newPackage);
15833
15834                mDexManager.notifyPackageUpdated(newPackage.packageName,
15835                            newPackage.baseCodePath, newPackage.splitCodePaths);
15836            }
15837        } catch (PackageManagerException e) {
15838            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
15839            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15840        }
15841
15842        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15843            // Re installation failed. Restore old information
15844            // Remove new pkg information
15845            if (newPackage != null) {
15846                removeInstalledPackageLI(newPackage, true);
15847            }
15848            // Add back the old system package
15849            try {
15850                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
15851            } catch (PackageManagerException e) {
15852                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
15853            }
15854
15855            synchronized (mPackages) {
15856                if (disabledSystem) {
15857                    enableSystemPackageLPw(deletedPackage);
15858                }
15859
15860                // Ensure the installer package name up to date
15861                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
15862
15863                // Update permissions for restored package
15864                mPermissionManager.updatePermissions(
15865                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
15866                        mPermissionCallback);
15867
15868                mSettings.writeLPr();
15869            }
15870
15871            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
15872                    + " after failed upgrade");
15873        }
15874    }
15875
15876    /**
15877     * Checks whether the parent or any of the child packages have a change shared
15878     * user. For a package to be a valid update the shred users of the parent and
15879     * the children should match. We may later support changing child shared users.
15880     * @param oldPkg The updated package.
15881     * @param newPkg The update package.
15882     * @return The shared user that change between the versions.
15883     */
15884    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
15885            PackageParser.Package newPkg) {
15886        // Check parent shared user
15887        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
15888            return newPkg.packageName;
15889        }
15890        // Check child shared users
15891        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15892        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
15893        for (int i = 0; i < newChildCount; i++) {
15894            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
15895            // If this child was present, did it have the same shared user?
15896            for (int j = 0; j < oldChildCount; j++) {
15897                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
15898                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
15899                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
15900                    return newChildPkg.packageName;
15901                }
15902            }
15903        }
15904        return null;
15905    }
15906
15907    private void removeNativeBinariesLI(PackageSetting ps) {
15908        // Remove the lib path for the parent package
15909        if (ps != null) {
15910            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
15911            // Remove the lib path for the child packages
15912            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15913            for (int i = 0; i < childCount; i++) {
15914                PackageSetting childPs = null;
15915                synchronized (mPackages) {
15916                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
15917                }
15918                if (childPs != null) {
15919                    NativeLibraryHelper.removeNativeBinariesLI(childPs
15920                            .legacyNativeLibraryPathString);
15921                }
15922            }
15923        }
15924    }
15925
15926    private void enableSystemPackageLPw(PackageParser.Package pkg) {
15927        // Enable the parent package
15928        mSettings.enableSystemPackageLPw(pkg.packageName);
15929        // Enable the child packages
15930        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15931        for (int i = 0; i < childCount; i++) {
15932            PackageParser.Package childPkg = pkg.childPackages.get(i);
15933            mSettings.enableSystemPackageLPw(childPkg.packageName);
15934        }
15935    }
15936
15937    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
15938            PackageParser.Package newPkg) {
15939        // Disable the parent package (parent always replaced)
15940        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
15941        // Disable the child packages
15942        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
15943        for (int i = 0; i < childCount; i++) {
15944            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
15945            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
15946            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
15947        }
15948        return disabled;
15949    }
15950
15951    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
15952            String installerPackageName) {
15953        // Enable the parent package
15954        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
15955        // Enable the child packages
15956        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15957        for (int i = 0; i < childCount; i++) {
15958            PackageParser.Package childPkg = pkg.childPackages.get(i);
15959            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
15960        }
15961    }
15962
15963    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
15964            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
15965        // Update the parent package setting
15966        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
15967                res, user, installReason);
15968        // Update the child packages setting
15969        final int childCount = (newPackage.childPackages != null)
15970                ? newPackage.childPackages.size() : 0;
15971        for (int i = 0; i < childCount; i++) {
15972            PackageParser.Package childPackage = newPackage.childPackages.get(i);
15973            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
15974            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
15975                    childRes.origUsers, childRes, user, installReason);
15976        }
15977    }
15978
15979    private void updateSettingsInternalLI(PackageParser.Package pkg,
15980            String installerPackageName, int[] allUsers, int[] installedForUsers,
15981            PackageInstalledInfo res, UserHandle user, int installReason) {
15982        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
15983
15984        String pkgName = pkg.packageName;
15985        synchronized (mPackages) {
15986            //write settings. the installStatus will be incomplete at this stage.
15987            //note that the new package setting would have already been
15988            //added to mPackages. It hasn't been persisted yet.
15989            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
15990            // TODO: Remove this write? It's also written at the end of this method
15991            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
15992            mSettings.writeLPr();
15993            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15994        }
15995
15996        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
15997        synchronized (mPackages) {
15998// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
15999            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16000                    mPermissionCallback);
16001            // For system-bundled packages, we assume that installing an upgraded version
16002            // of the package implies that the user actually wants to run that new code,
16003            // so we enable the package.
16004            PackageSetting ps = mSettings.mPackages.get(pkgName);
16005            final int userId = user.getIdentifier();
16006            if (ps != null) {
16007                if (isSystemApp(pkg)) {
16008                    if (DEBUG_INSTALL) {
16009                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16010                    }
16011                    // Enable system package for requested users
16012                    if (res.origUsers != null) {
16013                        for (int origUserId : res.origUsers) {
16014                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16015                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16016                                        origUserId, installerPackageName);
16017                            }
16018                        }
16019                    }
16020                    // Also convey the prior install/uninstall state
16021                    if (allUsers != null && installedForUsers != null) {
16022                        for (int currentUserId : allUsers) {
16023                            final boolean installed = ArrayUtils.contains(
16024                                    installedForUsers, currentUserId);
16025                            if (DEBUG_INSTALL) {
16026                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16027                            }
16028                            ps.setInstalled(installed, currentUserId);
16029                        }
16030                        // these install state changes will be persisted in the
16031                        // upcoming call to mSettings.writeLPr().
16032                    }
16033                }
16034                // It's implied that when a user requests installation, they want the app to be
16035                // installed and enabled.
16036                if (userId != UserHandle.USER_ALL) {
16037                    ps.setInstalled(true, userId);
16038                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16039                }
16040
16041                // When replacing an existing package, preserve the original install reason for all
16042                // users that had the package installed before.
16043                final Set<Integer> previousUserIds = new ArraySet<>();
16044                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16045                    final int installReasonCount = res.removedInfo.installReasons.size();
16046                    for (int i = 0; i < installReasonCount; i++) {
16047                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16048                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16049                        ps.setInstallReason(previousInstallReason, previousUserId);
16050                        previousUserIds.add(previousUserId);
16051                    }
16052                }
16053
16054                // Set install reason for users that are having the package newly installed.
16055                if (userId == UserHandle.USER_ALL) {
16056                    for (int currentUserId : sUserManager.getUserIds()) {
16057                        if (!previousUserIds.contains(currentUserId)) {
16058                            ps.setInstallReason(installReason, currentUserId);
16059                        }
16060                    }
16061                } else if (!previousUserIds.contains(userId)) {
16062                    ps.setInstallReason(installReason, userId);
16063                }
16064                mSettings.writeKernelMappingLPr(ps);
16065            }
16066            res.name = pkgName;
16067            res.uid = pkg.applicationInfo.uid;
16068            res.pkg = pkg;
16069            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16070            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16071            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16072            //to update install status
16073            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16074            mSettings.writeLPr();
16075            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16076        }
16077
16078        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16079    }
16080
16081    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16082        try {
16083            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16084            installPackageLI(args, res);
16085        } finally {
16086            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16087        }
16088    }
16089
16090    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16091        final int installFlags = args.installFlags;
16092        final String installerPackageName = args.installerPackageName;
16093        final String volumeUuid = args.volumeUuid;
16094        final File tmpPackageFile = new File(args.getCodePath());
16095        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16096        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16097                || (args.volumeUuid != null));
16098        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16099        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16100        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16101        final boolean virtualPreload =
16102                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16103        boolean replace = false;
16104        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16105        if (args.move != null) {
16106            // moving a complete application; perform an initial scan on the new install location
16107            scanFlags |= SCAN_INITIAL;
16108        }
16109        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16110            scanFlags |= SCAN_DONT_KILL_APP;
16111        }
16112        if (instantApp) {
16113            scanFlags |= SCAN_AS_INSTANT_APP;
16114        }
16115        if (fullApp) {
16116            scanFlags |= SCAN_AS_FULL_APP;
16117        }
16118        if (virtualPreload) {
16119            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16120        }
16121
16122        // Result object to be returned
16123        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16124        res.installerPackageName = installerPackageName;
16125
16126        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16127
16128        // Sanity check
16129        if (instantApp && (forwardLocked || onExternal)) {
16130            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16131                    + " external=" + onExternal);
16132            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16133            return;
16134        }
16135
16136        // Retrieve PackageSettings and parse package
16137        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16138                | PackageParser.PARSE_ENFORCE_CODE
16139                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16140                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16141                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16142                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16143        PackageParser pp = new PackageParser();
16144        pp.setSeparateProcesses(mSeparateProcesses);
16145        pp.setDisplayMetrics(mMetrics);
16146        pp.setCallback(mPackageParserCallback);
16147
16148        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16149        final PackageParser.Package pkg;
16150        try {
16151            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16152        } catch (PackageParserException e) {
16153            res.setError("Failed parse during installPackageLI", e);
16154            return;
16155        } finally {
16156            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16157        }
16158
16159        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16160        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16161            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
16162            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16163                    "Instant app package must target O");
16164            return;
16165        }
16166        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16167            Slog.w(TAG, "Instant app package " + pkg.packageName
16168                    + " does not target targetSandboxVersion 2");
16169            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16170                    "Instant app package must use targetSanboxVersion 2");
16171            return;
16172        }
16173
16174        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16175            // Static shared libraries have synthetic package names
16176            renameStaticSharedLibraryPackage(pkg);
16177
16178            // No static shared libs on external storage
16179            if (onExternal) {
16180                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16181                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16182                        "Packages declaring static-shared libs cannot be updated");
16183                return;
16184            }
16185        }
16186
16187        // If we are installing a clustered package add results for the children
16188        if (pkg.childPackages != null) {
16189            synchronized (mPackages) {
16190                final int childCount = pkg.childPackages.size();
16191                for (int i = 0; i < childCount; i++) {
16192                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16193                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16194                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16195                    childRes.pkg = childPkg;
16196                    childRes.name = childPkg.packageName;
16197                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16198                    if (childPs != null) {
16199                        childRes.origUsers = childPs.queryInstalledUsers(
16200                                sUserManager.getUserIds(), true);
16201                    }
16202                    if ((mPackages.containsKey(childPkg.packageName))) {
16203                        childRes.removedInfo = new PackageRemovedInfo(this);
16204                        childRes.removedInfo.removedPackage = childPkg.packageName;
16205                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16206                    }
16207                    if (res.addedChildPackages == null) {
16208                        res.addedChildPackages = new ArrayMap<>();
16209                    }
16210                    res.addedChildPackages.put(childPkg.packageName, childRes);
16211                }
16212            }
16213        }
16214
16215        // If package doesn't declare API override, mark that we have an install
16216        // time CPU ABI override.
16217        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16218            pkg.cpuAbiOverride = args.abiOverride;
16219        }
16220
16221        String pkgName = res.name = pkg.packageName;
16222        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16223            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16224                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16225                return;
16226            }
16227        }
16228
16229        try {
16230            // either use what we've been given or parse directly from the APK
16231            if (args.certificates != null) {
16232                try {
16233                    PackageParser.populateCertificates(pkg, args.certificates);
16234                } catch (PackageParserException e) {
16235                    // there was something wrong with the certificates we were given;
16236                    // try to pull them from the APK
16237                    PackageParser.collectCertificates(pkg, parseFlags);
16238                }
16239            } else {
16240                PackageParser.collectCertificates(pkg, parseFlags);
16241            }
16242        } catch (PackageParserException e) {
16243            res.setError("Failed collect during installPackageLI", e);
16244            return;
16245        }
16246
16247        // Get rid of all references to package scan path via parser.
16248        pp = null;
16249        String oldCodePath = null;
16250        boolean systemApp = false;
16251        synchronized (mPackages) {
16252            // Check if installing already existing package
16253            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16254                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16255                if (pkg.mOriginalPackages != null
16256                        && pkg.mOriginalPackages.contains(oldName)
16257                        && mPackages.containsKey(oldName)) {
16258                    // This package is derived from an original package,
16259                    // and this device has been updating from that original
16260                    // name.  We must continue using the original name, so
16261                    // rename the new package here.
16262                    pkg.setPackageName(oldName);
16263                    pkgName = pkg.packageName;
16264                    replace = true;
16265                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16266                            + oldName + " pkgName=" + pkgName);
16267                } else if (mPackages.containsKey(pkgName)) {
16268                    // This package, under its official name, already exists
16269                    // on the device; we should replace it.
16270                    replace = true;
16271                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16272                }
16273
16274                // Child packages are installed through the parent package
16275                if (pkg.parentPackage != null) {
16276                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16277                            "Package " + pkg.packageName + " is child of package "
16278                                    + pkg.parentPackage.parentPackage + ". Child packages "
16279                                    + "can be updated only through the parent package.");
16280                    return;
16281                }
16282
16283                if (replace) {
16284                    // Prevent apps opting out from runtime permissions
16285                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16286                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16287                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16288                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16289                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16290                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16291                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16292                                        + " doesn't support runtime permissions but the old"
16293                                        + " target SDK " + oldTargetSdk + " does.");
16294                        return;
16295                    }
16296                    // Prevent apps from downgrading their targetSandbox.
16297                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16298                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16299                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16300                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16301                                "Package " + pkg.packageName + " new target sandbox "
16302                                + newTargetSandbox + " is incompatible with the previous value of"
16303                                + oldTargetSandbox + ".");
16304                        return;
16305                    }
16306
16307                    // Prevent installing of child packages
16308                    if (oldPackage.parentPackage != null) {
16309                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16310                                "Package " + pkg.packageName + " is child of package "
16311                                        + oldPackage.parentPackage + ". Child packages "
16312                                        + "can be updated only through the parent package.");
16313                        return;
16314                    }
16315                }
16316            }
16317
16318            PackageSetting ps = mSettings.mPackages.get(pkgName);
16319            if (ps != null) {
16320                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16321
16322                // Static shared libs have same package with different versions where
16323                // we internally use a synthetic package name to allow multiple versions
16324                // of the same package, therefore we need to compare signatures against
16325                // the package setting for the latest library version.
16326                PackageSetting signatureCheckPs = ps;
16327                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16328                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16329                    if (libraryEntry != null) {
16330                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16331                    }
16332                }
16333
16334                // Quick sanity check that we're signed correctly if updating;
16335                // we'll check this again later when scanning, but we want to
16336                // bail early here before tripping over redefined permissions.
16337                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16338                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16339                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16340                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16341                                + pkg.packageName + " upgrade keys do not match the "
16342                                + "previously installed version");
16343                        return;
16344                    }
16345                } else {
16346                    try {
16347                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
16348                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
16349                        final boolean compatMatch = verifySignatures(
16350                                signatureCheckPs, pkg.mSignatures, compareCompat, compareRecover);
16351                        // The new KeySets will be re-added later in the scanning process.
16352                        if (compatMatch) {
16353                            synchronized (mPackages) {
16354                                ksms.removeAppKeySetDataLPw(pkg.packageName);
16355                            }
16356                        }
16357                    } catch (PackageManagerException e) {
16358                        res.setError(e.error, e.getMessage());
16359                        return;
16360                    }
16361                }
16362
16363                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16364                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16365                    systemApp = (ps.pkg.applicationInfo.flags &
16366                            ApplicationInfo.FLAG_SYSTEM) != 0;
16367                }
16368                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16369            }
16370
16371            int N = pkg.permissions.size();
16372            for (int i = N-1; i >= 0; i--) {
16373                final PackageParser.Permission perm = pkg.permissions.get(i);
16374                final BasePermission bp =
16375                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
16376
16377                // Don't allow anyone but the system to define ephemeral permissions.
16378                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
16379                        && !systemApp) {
16380                    Slog.w(TAG, "Non-System package " + pkg.packageName
16381                            + " attempting to delcare ephemeral permission "
16382                            + perm.info.name + "; Removing ephemeral.");
16383                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
16384                }
16385
16386                // Check whether the newly-scanned package wants to define an already-defined perm
16387                if (bp != null) {
16388                    // If the defining package is signed with our cert, it's okay.  This
16389                    // also includes the "updating the same package" case, of course.
16390                    // "updating same package" could also involve key-rotation.
16391                    final boolean sigsOk;
16392                    final String sourcePackageName = bp.getSourcePackageName();
16393                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
16394                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16395                    if (sourcePackageName.equals(pkg.packageName)
16396                            && (ksms.shouldCheckUpgradeKeySetLocked(
16397                                    sourcePackageSetting, scanFlags))) {
16398                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
16399                    } else {
16400                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
16401                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16402                    }
16403                    if (!sigsOk) {
16404                        // If the owning package is the system itself, we log but allow
16405                        // install to proceed; we fail the install on all other permission
16406                        // redefinitions.
16407                        if (!sourcePackageName.equals("android")) {
16408                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16409                                    + pkg.packageName + " attempting to redeclare permission "
16410                                    + perm.info.name + " already owned by " + sourcePackageName);
16411                            res.origPermission = perm.info.name;
16412                            res.origPackage = sourcePackageName;
16413                            return;
16414                        } else {
16415                            Slog.w(TAG, "Package " + pkg.packageName
16416                                    + " attempting to redeclare system permission "
16417                                    + perm.info.name + "; ignoring new declaration");
16418                            pkg.permissions.remove(i);
16419                        }
16420                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16421                        // Prevent apps to change protection level to dangerous from any other
16422                        // type as this would allow a privilege escalation where an app adds a
16423                        // normal/signature permission in other app's group and later redefines
16424                        // it as dangerous leading to the group auto-grant.
16425                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16426                                == PermissionInfo.PROTECTION_DANGEROUS) {
16427                            if (bp != null && !bp.isRuntime()) {
16428                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16429                                        + "non-runtime permission " + perm.info.name
16430                                        + " to runtime; keeping old protection level");
16431                                perm.info.protectionLevel = bp.getProtectionLevel();
16432                            }
16433                        }
16434                    }
16435                }
16436            }
16437        }
16438
16439        if (systemApp) {
16440            if (onExternal) {
16441                // Abort update; system app can't be replaced with app on sdcard
16442                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16443                        "Cannot install updates to system apps on sdcard");
16444                return;
16445            } else if (instantApp) {
16446                // Abort update; system app can't be replaced with an instant app
16447                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16448                        "Cannot update a system app with an instant app");
16449                return;
16450            }
16451        }
16452
16453        if (args.move != null) {
16454            // We did an in-place move, so dex is ready to roll
16455            scanFlags |= SCAN_NO_DEX;
16456            scanFlags |= SCAN_MOVE;
16457
16458            synchronized (mPackages) {
16459                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16460                if (ps == null) {
16461                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16462                            "Missing settings for moved package " + pkgName);
16463                }
16464
16465                // We moved the entire application as-is, so bring over the
16466                // previously derived ABI information.
16467                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16468                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16469            }
16470
16471        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16472            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16473            scanFlags |= SCAN_NO_DEX;
16474
16475            try {
16476                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16477                    args.abiOverride : pkg.cpuAbiOverride);
16478                final boolean extractNativeLibs = !pkg.isLibrary();
16479                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16480                        extractNativeLibs, mAppLib32InstallDir);
16481            } catch (PackageManagerException pme) {
16482                Slog.e(TAG, "Error deriving application ABI", pme);
16483                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16484                return;
16485            }
16486
16487            // Shared libraries for the package need to be updated.
16488            synchronized (mPackages) {
16489                try {
16490                    updateSharedLibrariesLPr(pkg, null);
16491                } catch (PackageManagerException e) {
16492                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16493                }
16494            }
16495        }
16496
16497        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16498            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16499            return;
16500        }
16501
16502        // Verify if we need to dexopt the app.
16503        //
16504        // NOTE: it is *important* to call dexopt after doRename which will sync the
16505        // package data from PackageParser.Package and its corresponding ApplicationInfo.
16506        //
16507        // We only need to dexopt if the package meets ALL of the following conditions:
16508        //   1) it is not forward locked.
16509        //   2) it is not on on an external ASEC container.
16510        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
16511        //
16512        // Note that we do not dexopt instant apps by default. dexopt can take some time to
16513        // complete, so we skip this step during installation. Instead, we'll take extra time
16514        // the first time the instant app starts. It's preferred to do it this way to provide
16515        // continuous progress to the useur instead of mysteriously blocking somewhere in the
16516        // middle of running an instant app. The default behaviour can be overridden
16517        // via gservices.
16518        final boolean performDexopt = !forwardLocked
16519            && !pkg.applicationInfo.isExternalAsec()
16520            && (!instantApp || Global.getInt(mContext.getContentResolver(),
16521                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
16522
16523        if (performDexopt) {
16524            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16525            // Do not run PackageDexOptimizer through the local performDexOpt
16526            // method because `pkg` may not be in `mPackages` yet.
16527            //
16528            // Also, don't fail application installs if the dexopt step fails.
16529            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
16530                REASON_INSTALL,
16531                DexoptOptions.DEXOPT_BOOT_COMPLETE);
16532            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16533                null /* instructionSets */,
16534                getOrCreateCompilerPackageStats(pkg),
16535                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
16536                dexoptOptions);
16537            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16538        }
16539
16540        // Notify BackgroundDexOptService that the package has been changed.
16541        // If this is an update of a package which used to fail to compile,
16542        // BackgroundDexOptService will remove it from its blacklist.
16543        // TODO: Layering violation
16544        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16545
16546        if (!instantApp) {
16547            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16548        } else {
16549            if (DEBUG_DOMAIN_VERIFICATION) {
16550                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
16551            }
16552        }
16553
16554        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16555                "installPackageLI")) {
16556            if (replace) {
16557                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16558                    // Static libs have a synthetic package name containing the version
16559                    // and cannot be updated as an update would get a new package name,
16560                    // unless this is the exact same version code which is useful for
16561                    // development.
16562                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16563                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16564                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16565                                + "static-shared libs cannot be updated");
16566                        return;
16567                    }
16568                }
16569                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
16570                        installerPackageName, res, args.installReason);
16571            } else {
16572                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16573                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16574            }
16575        }
16576
16577        synchronized (mPackages) {
16578            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16579            if (ps != null) {
16580                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16581                ps.setUpdateAvailable(false /*updateAvailable*/);
16582            }
16583
16584            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16585            for (int i = 0; i < childCount; i++) {
16586                PackageParser.Package childPkg = pkg.childPackages.get(i);
16587                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16588                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16589                if (childPs != null) {
16590                    childRes.newUsers = childPs.queryInstalledUsers(
16591                            sUserManager.getUserIds(), true);
16592                }
16593            }
16594
16595            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16596                updateSequenceNumberLP(ps, res.newUsers);
16597                updateInstantAppInstallerLocked(pkgName);
16598            }
16599        }
16600    }
16601
16602    private void startIntentFilterVerifications(int userId, boolean replacing,
16603            PackageParser.Package pkg) {
16604        if (mIntentFilterVerifierComponent == null) {
16605            Slog.w(TAG, "No IntentFilter verification will not be done as "
16606                    + "there is no IntentFilterVerifier available!");
16607            return;
16608        }
16609
16610        final int verifierUid = getPackageUid(
16611                mIntentFilterVerifierComponent.getPackageName(),
16612                MATCH_DEBUG_TRIAGED_MISSING,
16613                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16614
16615        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16616        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16617        mHandler.sendMessage(msg);
16618
16619        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16620        for (int i = 0; i < childCount; i++) {
16621            PackageParser.Package childPkg = pkg.childPackages.get(i);
16622            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16623            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16624            mHandler.sendMessage(msg);
16625        }
16626    }
16627
16628    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16629            PackageParser.Package pkg) {
16630        int size = pkg.activities.size();
16631        if (size == 0) {
16632            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16633                    "No activity, so no need to verify any IntentFilter!");
16634            return;
16635        }
16636
16637        final boolean hasDomainURLs = hasDomainURLs(pkg);
16638        if (!hasDomainURLs) {
16639            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16640                    "No domain URLs, so no need to verify any IntentFilter!");
16641            return;
16642        }
16643
16644        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16645                + " if any IntentFilter from the " + size
16646                + " Activities needs verification ...");
16647
16648        int count = 0;
16649        final String packageName = pkg.packageName;
16650
16651        synchronized (mPackages) {
16652            // If this is a new install and we see that we've already run verification for this
16653            // package, we have nothing to do: it means the state was restored from backup.
16654            if (!replacing) {
16655                IntentFilterVerificationInfo ivi =
16656                        mSettings.getIntentFilterVerificationLPr(packageName);
16657                if (ivi != null) {
16658                    if (DEBUG_DOMAIN_VERIFICATION) {
16659                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16660                                + ivi.getStatusString());
16661                    }
16662                    return;
16663                }
16664            }
16665
16666            // If any filters need to be verified, then all need to be.
16667            boolean needToVerify = false;
16668            for (PackageParser.Activity a : pkg.activities) {
16669                for (ActivityIntentInfo filter : a.intents) {
16670                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16671                        if (DEBUG_DOMAIN_VERIFICATION) {
16672                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16673                        }
16674                        needToVerify = true;
16675                        break;
16676                    }
16677                }
16678            }
16679
16680            if (needToVerify) {
16681                final int verificationId = mIntentFilterVerificationToken++;
16682                for (PackageParser.Activity a : pkg.activities) {
16683                    for (ActivityIntentInfo filter : a.intents) {
16684                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16685                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16686                                    "Verification needed for IntentFilter:" + filter.toString());
16687                            mIntentFilterVerifier.addOneIntentFilterVerification(
16688                                    verifierUid, userId, verificationId, filter, packageName);
16689                            count++;
16690                        }
16691                    }
16692                }
16693            }
16694        }
16695
16696        if (count > 0) {
16697            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16698                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16699                    +  " for userId:" + userId);
16700            mIntentFilterVerifier.startVerifications(userId);
16701        } else {
16702            if (DEBUG_DOMAIN_VERIFICATION) {
16703                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16704            }
16705        }
16706    }
16707
16708    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16709        final ComponentName cn  = filter.activity.getComponentName();
16710        final String packageName = cn.getPackageName();
16711
16712        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16713                packageName);
16714        if (ivi == null) {
16715            return true;
16716        }
16717        int status = ivi.getStatus();
16718        switch (status) {
16719            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16720            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16721                return true;
16722
16723            default:
16724                // Nothing to do
16725                return false;
16726        }
16727    }
16728
16729    private static boolean isMultiArch(ApplicationInfo info) {
16730        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16731    }
16732
16733    private static boolean isExternal(PackageParser.Package pkg) {
16734        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16735    }
16736
16737    private static boolean isExternal(PackageSetting ps) {
16738        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16739    }
16740
16741    private static boolean isSystemApp(PackageParser.Package pkg) {
16742        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16743    }
16744
16745    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16746        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16747    }
16748
16749    private static boolean isOemApp(PackageParser.Package pkg) {
16750        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16751    }
16752
16753    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16754        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16755    }
16756
16757    private static boolean isSystemApp(PackageSetting ps) {
16758        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
16759    }
16760
16761    private static boolean isUpdatedSystemApp(PackageSetting ps) {
16762        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
16763    }
16764
16765    private int packageFlagsToInstallFlags(PackageSetting ps) {
16766        int installFlags = 0;
16767        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
16768            // This existing package was an external ASEC install when we have
16769            // the external flag without a UUID
16770            installFlags |= PackageManager.INSTALL_EXTERNAL;
16771        }
16772        if (ps.isForwardLocked()) {
16773            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
16774        }
16775        return installFlags;
16776    }
16777
16778    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
16779        if (isExternal(pkg)) {
16780            if (TextUtils.isEmpty(pkg.volumeUuid)) {
16781                return mSettings.getExternalVersion();
16782            } else {
16783                return mSettings.findOrCreateVersion(pkg.volumeUuid);
16784            }
16785        } else {
16786            return mSettings.getInternalVersion();
16787        }
16788    }
16789
16790    private void deleteTempPackageFiles() {
16791        final FilenameFilter filter = new FilenameFilter() {
16792            public boolean accept(File dir, String name) {
16793                return name.startsWith("vmdl") && name.endsWith(".tmp");
16794            }
16795        };
16796        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
16797            file.delete();
16798        }
16799    }
16800
16801    @Override
16802    public void deletePackageAsUser(String packageName, int versionCode,
16803            IPackageDeleteObserver observer, int userId, int flags) {
16804        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
16805                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
16806    }
16807
16808    @Override
16809    public void deletePackageVersioned(VersionedPackage versionedPackage,
16810            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
16811        final int callingUid = Binder.getCallingUid();
16812        mContext.enforceCallingOrSelfPermission(
16813                android.Manifest.permission.DELETE_PACKAGES, null);
16814        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
16815        Preconditions.checkNotNull(versionedPackage);
16816        Preconditions.checkNotNull(observer);
16817        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
16818                PackageManager.VERSION_CODE_HIGHEST,
16819                Integer.MAX_VALUE, "versionCode must be >= -1");
16820
16821        final String packageName = versionedPackage.getPackageName();
16822        final int versionCode = versionedPackage.getVersionCode();
16823        final String internalPackageName;
16824        synchronized (mPackages) {
16825            // Normalize package name to handle renamed packages and static libs
16826            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
16827                    versionedPackage.getVersionCode());
16828        }
16829
16830        final int uid = Binder.getCallingUid();
16831        if (!isOrphaned(internalPackageName)
16832                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
16833            try {
16834                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
16835                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
16836                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
16837                observer.onUserActionRequired(intent);
16838            } catch (RemoteException re) {
16839            }
16840            return;
16841        }
16842        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
16843        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
16844        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
16845            mContext.enforceCallingOrSelfPermission(
16846                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
16847                    "deletePackage for user " + userId);
16848        }
16849
16850        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
16851            try {
16852                observer.onPackageDeleted(packageName,
16853                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
16854            } catch (RemoteException re) {
16855            }
16856            return;
16857        }
16858
16859        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
16860            try {
16861                observer.onPackageDeleted(packageName,
16862                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
16863            } catch (RemoteException re) {
16864            }
16865            return;
16866        }
16867
16868        if (DEBUG_REMOVE) {
16869            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
16870                    + " deleteAllUsers: " + deleteAllUsers + " version="
16871                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
16872                    ? "VERSION_CODE_HIGHEST" : versionCode));
16873        }
16874        // Queue up an async operation since the package deletion may take a little while.
16875        mHandler.post(new Runnable() {
16876            public void run() {
16877                mHandler.removeCallbacks(this);
16878                int returnCode;
16879                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
16880                boolean doDeletePackage = true;
16881                if (ps != null) {
16882                    final boolean targetIsInstantApp =
16883                            ps.getInstantApp(UserHandle.getUserId(callingUid));
16884                    doDeletePackage = !targetIsInstantApp
16885                            || canViewInstantApps;
16886                }
16887                if (doDeletePackage) {
16888                    if (!deleteAllUsers) {
16889                        returnCode = deletePackageX(internalPackageName, versionCode,
16890                                userId, deleteFlags);
16891                    } else {
16892                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
16893                                internalPackageName, users);
16894                        // If nobody is blocking uninstall, proceed with delete for all users
16895                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
16896                            returnCode = deletePackageX(internalPackageName, versionCode,
16897                                    userId, deleteFlags);
16898                        } else {
16899                            // Otherwise uninstall individually for users with blockUninstalls=false
16900                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
16901                            for (int userId : users) {
16902                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
16903                                    returnCode = deletePackageX(internalPackageName, versionCode,
16904                                            userId, userFlags);
16905                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
16906                                        Slog.w(TAG, "Package delete failed for user " + userId
16907                                                + ", returnCode " + returnCode);
16908                                    }
16909                                }
16910                            }
16911                            // The app has only been marked uninstalled for certain users.
16912                            // We still need to report that delete was blocked
16913                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
16914                        }
16915                    }
16916                } else {
16917                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
16918                }
16919                try {
16920                    observer.onPackageDeleted(packageName, returnCode, null);
16921                } catch (RemoteException e) {
16922                    Log.i(TAG, "Observer no longer exists.");
16923                } //end catch
16924            } //end run
16925        });
16926    }
16927
16928    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
16929        if (pkg.staticSharedLibName != null) {
16930            return pkg.manifestPackageName;
16931        }
16932        return pkg.packageName;
16933    }
16934
16935    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
16936        // Handle renamed packages
16937        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
16938        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
16939
16940        // Is this a static library?
16941        SparseArray<SharedLibraryEntry> versionedLib =
16942                mStaticLibsByDeclaringPackage.get(packageName);
16943        if (versionedLib == null || versionedLib.size() <= 0) {
16944            return packageName;
16945        }
16946
16947        // Figure out which lib versions the caller can see
16948        SparseIntArray versionsCallerCanSee = null;
16949        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
16950        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
16951                && callingAppId != Process.ROOT_UID) {
16952            versionsCallerCanSee = new SparseIntArray();
16953            String libName = versionedLib.valueAt(0).info.getName();
16954            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
16955            if (uidPackages != null) {
16956                for (String uidPackage : uidPackages) {
16957                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
16958                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
16959                    if (libIdx >= 0) {
16960                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
16961                        versionsCallerCanSee.append(libVersion, libVersion);
16962                    }
16963                }
16964            }
16965        }
16966
16967        // Caller can see nothing - done
16968        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
16969            return packageName;
16970        }
16971
16972        // Find the version the caller can see and the app version code
16973        SharedLibraryEntry highestVersion = null;
16974        final int versionCount = versionedLib.size();
16975        for (int i = 0; i < versionCount; i++) {
16976            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
16977            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
16978                    libEntry.info.getVersion()) < 0) {
16979                continue;
16980            }
16981            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
16982            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
16983                if (libVersionCode == versionCode) {
16984                    return libEntry.apk;
16985                }
16986            } else if (highestVersion == null) {
16987                highestVersion = libEntry;
16988            } else if (libVersionCode  > highestVersion.info
16989                    .getDeclaringPackage().getVersionCode()) {
16990                highestVersion = libEntry;
16991            }
16992        }
16993
16994        if (highestVersion != null) {
16995            return highestVersion.apk;
16996        }
16997
16998        return packageName;
16999    }
17000
17001    boolean isCallerVerifier(int callingUid) {
17002        final int callingUserId = UserHandle.getUserId(callingUid);
17003        return mRequiredVerifierPackage != null &&
17004                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17005    }
17006
17007    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17008        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17009              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17010            return true;
17011        }
17012        final int callingUserId = UserHandle.getUserId(callingUid);
17013        // If the caller installed the pkgName, then allow it to silently uninstall.
17014        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17015            return true;
17016        }
17017
17018        // Allow package verifier to silently uninstall.
17019        if (mRequiredVerifierPackage != null &&
17020                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17021            return true;
17022        }
17023
17024        // Allow package uninstaller to silently uninstall.
17025        if (mRequiredUninstallerPackage != null &&
17026                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17027            return true;
17028        }
17029
17030        // Allow storage manager to silently uninstall.
17031        if (mStorageManagerPackage != null &&
17032                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17033            return true;
17034        }
17035
17036        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17037        // uninstall for device owner provisioning.
17038        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17039                == PERMISSION_GRANTED) {
17040            return true;
17041        }
17042
17043        return false;
17044    }
17045
17046    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17047        int[] result = EMPTY_INT_ARRAY;
17048        for (int userId : userIds) {
17049            if (getBlockUninstallForUser(packageName, userId)) {
17050                result = ArrayUtils.appendInt(result, userId);
17051            }
17052        }
17053        return result;
17054    }
17055
17056    @Override
17057    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17058        final int callingUid = Binder.getCallingUid();
17059        if (getInstantAppPackageName(callingUid) != null
17060                && !isCallerSameApp(packageName, callingUid)) {
17061            return false;
17062        }
17063        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17064    }
17065
17066    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17067        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17068                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17069        try {
17070            if (dpm != null) {
17071                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17072                        /* callingUserOnly =*/ false);
17073                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17074                        : deviceOwnerComponentName.getPackageName();
17075                // Does the package contains the device owner?
17076                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17077                // this check is probably not needed, since DO should be registered as a device
17078                // admin on some user too. (Original bug for this: b/17657954)
17079                if (packageName.equals(deviceOwnerPackageName)) {
17080                    return true;
17081                }
17082                // Does it contain a device admin for any user?
17083                int[] users;
17084                if (userId == UserHandle.USER_ALL) {
17085                    users = sUserManager.getUserIds();
17086                } else {
17087                    users = new int[]{userId};
17088                }
17089                for (int i = 0; i < users.length; ++i) {
17090                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17091                        return true;
17092                    }
17093                }
17094            }
17095        } catch (RemoteException e) {
17096        }
17097        return false;
17098    }
17099
17100    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17101        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17102    }
17103
17104    /**
17105     *  This method is an internal method that could be get invoked either
17106     *  to delete an installed package or to clean up a failed installation.
17107     *  After deleting an installed package, a broadcast is sent to notify any
17108     *  listeners that the package has been removed. For cleaning up a failed
17109     *  installation, the broadcast is not necessary since the package's
17110     *  installation wouldn't have sent the initial broadcast either
17111     *  The key steps in deleting a package are
17112     *  deleting the package information in internal structures like mPackages,
17113     *  deleting the packages base directories through installd
17114     *  updating mSettings to reflect current status
17115     *  persisting settings for later use
17116     *  sending a broadcast if necessary
17117     */
17118    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17119        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17120        final boolean res;
17121
17122        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17123                ? UserHandle.USER_ALL : userId;
17124
17125        if (isPackageDeviceAdmin(packageName, removeUser)) {
17126            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17127            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17128        }
17129
17130        PackageSetting uninstalledPs = null;
17131        PackageParser.Package pkg = null;
17132
17133        // for the uninstall-updates case and restricted profiles, remember the per-
17134        // user handle installed state
17135        int[] allUsers;
17136        synchronized (mPackages) {
17137            uninstalledPs = mSettings.mPackages.get(packageName);
17138            if (uninstalledPs == null) {
17139                Slog.w(TAG, "Not removing non-existent package " + packageName);
17140                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17141            }
17142
17143            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17144                    && uninstalledPs.versionCode != versionCode) {
17145                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17146                        + uninstalledPs.versionCode + " != " + versionCode);
17147                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17148            }
17149
17150            // Static shared libs can be declared by any package, so let us not
17151            // allow removing a package if it provides a lib others depend on.
17152            pkg = mPackages.get(packageName);
17153
17154            allUsers = sUserManager.getUserIds();
17155
17156            if (pkg != null && pkg.staticSharedLibName != null) {
17157                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17158                        pkg.staticSharedLibVersion);
17159                if (libEntry != null) {
17160                    for (int currUserId : allUsers) {
17161                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17162                            continue;
17163                        }
17164                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17165                                libEntry.info, 0, currUserId);
17166                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17167                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17168                                    + " hosting lib " + libEntry.info.getName() + " version "
17169                                    + libEntry.info.getVersion() + " used by " + libClientPackages
17170                                    + " for user " + currUserId);
17171                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17172                        }
17173                    }
17174                }
17175            }
17176
17177            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17178        }
17179
17180        final int freezeUser;
17181        if (isUpdatedSystemApp(uninstalledPs)
17182                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17183            // We're downgrading a system app, which will apply to all users, so
17184            // freeze them all during the downgrade
17185            freezeUser = UserHandle.USER_ALL;
17186        } else {
17187            freezeUser = removeUser;
17188        }
17189
17190        synchronized (mInstallLock) {
17191            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17192            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17193                    deleteFlags, "deletePackageX")) {
17194                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17195                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17196            }
17197            synchronized (mPackages) {
17198                if (res) {
17199                    if (pkg != null) {
17200                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17201                    }
17202                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
17203                    updateInstantAppInstallerLocked(packageName);
17204                }
17205            }
17206        }
17207
17208        if (res) {
17209            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17210            info.sendPackageRemovedBroadcasts(killApp);
17211            info.sendSystemPackageUpdatedBroadcasts();
17212            info.sendSystemPackageAppearedBroadcasts();
17213        }
17214        // Force a gc here.
17215        Runtime.getRuntime().gc();
17216        // Delete the resources here after sending the broadcast to let
17217        // other processes clean up before deleting resources.
17218        if (info.args != null) {
17219            synchronized (mInstallLock) {
17220                info.args.doPostDeleteLI(true);
17221            }
17222        }
17223
17224        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17225    }
17226
17227    static class PackageRemovedInfo {
17228        final PackageSender packageSender;
17229        String removedPackage;
17230        String installerPackageName;
17231        int uid = -1;
17232        int removedAppId = -1;
17233        int[] origUsers;
17234        int[] removedUsers = null;
17235        int[] broadcastUsers = null;
17236        SparseArray<Integer> installReasons;
17237        boolean isRemovedPackageSystemUpdate = false;
17238        boolean isUpdate;
17239        boolean dataRemoved;
17240        boolean removedForAllUsers;
17241        boolean isStaticSharedLib;
17242        // Clean up resources deleted packages.
17243        InstallArgs args = null;
17244        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17245        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17246
17247        PackageRemovedInfo(PackageSender packageSender) {
17248            this.packageSender = packageSender;
17249        }
17250
17251        void sendPackageRemovedBroadcasts(boolean killApp) {
17252            sendPackageRemovedBroadcastInternal(killApp);
17253            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17254            for (int i = 0; i < childCount; i++) {
17255                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17256                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17257            }
17258        }
17259
17260        void sendSystemPackageUpdatedBroadcasts() {
17261            if (isRemovedPackageSystemUpdate) {
17262                sendSystemPackageUpdatedBroadcastsInternal();
17263                final int childCount = (removedChildPackages != null)
17264                        ? removedChildPackages.size() : 0;
17265                for (int i = 0; i < childCount; i++) {
17266                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17267                    if (childInfo.isRemovedPackageSystemUpdate) {
17268                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17269                    }
17270                }
17271            }
17272        }
17273
17274        void sendSystemPackageAppearedBroadcasts() {
17275            final int packageCount = (appearedChildPackages != null)
17276                    ? appearedChildPackages.size() : 0;
17277            for (int i = 0; i < packageCount; i++) {
17278                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17279                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
17280                    true /*sendBootCompleted*/, false /*startReceiver*/,
17281                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17282            }
17283        }
17284
17285        private void sendSystemPackageUpdatedBroadcastsInternal() {
17286            Bundle extras = new Bundle(2);
17287            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17288            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17289            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17290                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17291            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17292                removedPackage, extras, 0, null /*targetPackage*/, null, null);
17293            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
17294                null, null, 0, removedPackage, null, null);
17295            if (installerPackageName != null) {
17296                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
17297                        removedPackage, extras, 0 /*flags*/,
17298                        installerPackageName, null, null);
17299                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
17300                        removedPackage, extras, 0 /*flags*/,
17301                        installerPackageName, null, null);
17302            }
17303        }
17304
17305        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17306            // Don't send static shared library removal broadcasts as these
17307            // libs are visible only the the apps that depend on them an one
17308            // cannot remove the library if it has a dependency.
17309            if (isStaticSharedLib) {
17310                return;
17311            }
17312            Bundle extras = new Bundle(2);
17313            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17314            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17315            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17316            if (isUpdate || isRemovedPackageSystemUpdate) {
17317                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17318            }
17319            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17320            if (removedPackage != null) {
17321                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17322                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
17323                if (installerPackageName != null) {
17324                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
17325                            removedPackage, extras, 0 /*flags*/,
17326                            installerPackageName, null, broadcastUsers);
17327                }
17328                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17329                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17330                        removedPackage, extras,
17331                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17332                        null, null, broadcastUsers);
17333                }
17334            }
17335            if (removedAppId >= 0) {
17336                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
17337                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17338                    null, null, broadcastUsers);
17339            }
17340        }
17341
17342        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
17343            removedUsers = userIds;
17344            if (removedUsers == null) {
17345                broadcastUsers = null;
17346                return;
17347            }
17348
17349            broadcastUsers = EMPTY_INT_ARRAY;
17350            for (int i = userIds.length - 1; i >= 0; --i) {
17351                final int userId = userIds[i];
17352                if (deletedPackageSetting.getInstantApp(userId)) {
17353                    continue;
17354                }
17355                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
17356            }
17357        }
17358    }
17359
17360    /*
17361     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17362     * flag is not set, the data directory is removed as well.
17363     * make sure this flag is set for partially installed apps. If not its meaningless to
17364     * delete a partially installed application.
17365     */
17366    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17367            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17368        String packageName = ps.name;
17369        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17370        // Retrieve object to delete permissions for shared user later on
17371        final PackageParser.Package deletedPkg;
17372        final PackageSetting deletedPs;
17373        // reader
17374        synchronized (mPackages) {
17375            deletedPkg = mPackages.get(packageName);
17376            deletedPs = mSettings.mPackages.get(packageName);
17377            if (outInfo != null) {
17378                outInfo.removedPackage = packageName;
17379                outInfo.installerPackageName = ps.installerPackageName;
17380                outInfo.isStaticSharedLib = deletedPkg != null
17381                        && deletedPkg.staticSharedLibName != null;
17382                outInfo.populateUsers(deletedPs == null ? null
17383                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
17384            }
17385        }
17386
17387        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
17388
17389        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17390            final PackageParser.Package resolvedPkg;
17391            if (deletedPkg != null) {
17392                resolvedPkg = deletedPkg;
17393            } else {
17394                // We don't have a parsed package when it lives on an ejected
17395                // adopted storage device, so fake something together
17396                resolvedPkg = new PackageParser.Package(ps.name);
17397                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17398            }
17399            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17400                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17401            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17402            if (outInfo != null) {
17403                outInfo.dataRemoved = true;
17404            }
17405            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17406        }
17407
17408        int removedAppId = -1;
17409
17410        // writer
17411        synchronized (mPackages) {
17412            boolean installedStateChanged = false;
17413            if (deletedPs != null) {
17414                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17415                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17416                    clearDefaultBrowserIfNeeded(packageName);
17417                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17418                    removedAppId = mSettings.removePackageLPw(packageName);
17419                    if (outInfo != null) {
17420                        outInfo.removedAppId = removedAppId;
17421                    }
17422                    mPermissionManager.updatePermissions(
17423                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
17424                    if (deletedPs.sharedUser != null) {
17425                        // Remove permissions associated with package. Since runtime
17426                        // permissions are per user we have to kill the removed package
17427                        // or packages running under the shared user of the removed
17428                        // package if revoking the permissions requested only by the removed
17429                        // package is successful and this causes a change in gids.
17430                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17431                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17432                                    userId);
17433                            if (userIdToKill == UserHandle.USER_ALL
17434                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17435                                // If gids changed for this user, kill all affected packages.
17436                                mHandler.post(new Runnable() {
17437                                    @Override
17438                                    public void run() {
17439                                        // This has to happen with no lock held.
17440                                        killApplication(deletedPs.name, deletedPs.appId,
17441                                                KILL_APP_REASON_GIDS_CHANGED);
17442                                    }
17443                                });
17444                                break;
17445                            }
17446                        }
17447                    }
17448                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17449                }
17450                // make sure to preserve per-user disabled state if this removal was just
17451                // a downgrade of a system app to the factory package
17452                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17453                    if (DEBUG_REMOVE) {
17454                        Slog.d(TAG, "Propagating install state across downgrade");
17455                    }
17456                    for (int userId : allUserHandles) {
17457                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17458                        if (DEBUG_REMOVE) {
17459                            Slog.d(TAG, "    user " + userId + " => " + installed);
17460                        }
17461                        if (installed != ps.getInstalled(userId)) {
17462                            installedStateChanged = true;
17463                        }
17464                        ps.setInstalled(installed, userId);
17465                    }
17466                }
17467            }
17468            // can downgrade to reader
17469            if (writeSettings) {
17470                // Save settings now
17471                mSettings.writeLPr();
17472            }
17473            if (installedStateChanged) {
17474                mSettings.writeKernelMappingLPr(ps);
17475            }
17476        }
17477        if (removedAppId != -1) {
17478            // A user ID was deleted here. Go through all users and remove it
17479            // from KeyStore.
17480            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17481        }
17482    }
17483
17484    static boolean locationIsPrivileged(File path) {
17485        try {
17486            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17487                    .getCanonicalPath();
17488            return path.getCanonicalPath().startsWith(privilegedAppDir);
17489        } catch (IOException e) {
17490            Slog.e(TAG, "Unable to access code path " + path);
17491        }
17492        return false;
17493    }
17494
17495    static boolean locationIsOem(File path) {
17496        try {
17497            return path.getCanonicalPath().startsWith(
17498                    Environment.getOemDirectory().getCanonicalPath());
17499        } catch (IOException e) {
17500            Slog.e(TAG, "Unable to access code path " + path);
17501        }
17502        return false;
17503    }
17504
17505    /*
17506     * Tries to delete system package.
17507     */
17508    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17509            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17510            boolean writeSettings) {
17511        if (deletedPs.parentPackageName != null) {
17512            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17513            return false;
17514        }
17515
17516        final boolean applyUserRestrictions
17517                = (allUserHandles != null) && (outInfo.origUsers != null);
17518        final PackageSetting disabledPs;
17519        // Confirm if the system package has been updated
17520        // An updated system app can be deleted. This will also have to restore
17521        // the system pkg from system partition
17522        // reader
17523        synchronized (mPackages) {
17524            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17525        }
17526
17527        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17528                + " disabledPs=" + disabledPs);
17529
17530        if (disabledPs == null) {
17531            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17532            return false;
17533        } else if (DEBUG_REMOVE) {
17534            Slog.d(TAG, "Deleting system pkg from data partition");
17535        }
17536
17537        if (DEBUG_REMOVE) {
17538            if (applyUserRestrictions) {
17539                Slog.d(TAG, "Remembering install states:");
17540                for (int userId : allUserHandles) {
17541                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17542                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17543                }
17544            }
17545        }
17546
17547        // Delete the updated package
17548        outInfo.isRemovedPackageSystemUpdate = true;
17549        if (outInfo.removedChildPackages != null) {
17550            final int childCount = (deletedPs.childPackageNames != null)
17551                    ? deletedPs.childPackageNames.size() : 0;
17552            for (int i = 0; i < childCount; i++) {
17553                String childPackageName = deletedPs.childPackageNames.get(i);
17554                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17555                        .contains(childPackageName)) {
17556                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17557                            childPackageName);
17558                    if (childInfo != null) {
17559                        childInfo.isRemovedPackageSystemUpdate = true;
17560                    }
17561                }
17562            }
17563        }
17564
17565        if (disabledPs.versionCode < deletedPs.versionCode) {
17566            // Delete data for downgrades
17567            flags &= ~PackageManager.DELETE_KEEP_DATA;
17568        } else {
17569            // Preserve data by setting flag
17570            flags |= PackageManager.DELETE_KEEP_DATA;
17571        }
17572
17573        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17574                outInfo, writeSettings, disabledPs.pkg);
17575        if (!ret) {
17576            return false;
17577        }
17578
17579        // writer
17580        synchronized (mPackages) {
17581            // NOTE: The system package always needs to be enabled; even if it's for
17582            // a compressed stub. If we don't, installing the system package fails
17583            // during scan [scanning checks the disabled packages]. We will reverse
17584            // this later, after we've "installed" the stub.
17585            // Reinstate the old system package
17586            enableSystemPackageLPw(disabledPs.pkg);
17587            // Remove any native libraries from the upgraded package.
17588            removeNativeBinariesLI(deletedPs);
17589        }
17590
17591        // Install the system package
17592        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17593        try {
17594            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
17595                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
17596        } catch (PackageManagerException e) {
17597            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17598                    + e.getMessage());
17599            return false;
17600        } finally {
17601            if (disabledPs.pkg.isStub) {
17602                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
17603            }
17604        }
17605        return true;
17606    }
17607
17608    /**
17609     * Installs a package that's already on the system partition.
17610     */
17611    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
17612            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
17613            @Nullable PermissionsState origPermissionState, boolean writeSettings)
17614                    throws PackageManagerException {
17615        @ParseFlags int parseFlags =
17616                mDefParseFlags
17617                | PackageParser.PARSE_MUST_BE_APK
17618                | PackageParser.PARSE_IS_SYSTEM_DIR;
17619        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
17620        if (isPrivileged || locationIsPrivileged(codePath)) {
17621            scanFlags |= SCAN_AS_PRIVILEGED;
17622        }
17623        if (locationIsOem(codePath)) {
17624            scanFlags |= SCAN_AS_OEM;
17625        }
17626
17627        final PackageParser.Package pkg =
17628                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
17629
17630        try {
17631            // update shared libraries for the newly re-installed system package
17632            updateSharedLibrariesLPr(pkg, null);
17633        } catch (PackageManagerException e) {
17634            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17635        }
17636
17637        prepareAppDataAfterInstallLIF(pkg);
17638
17639        // writer
17640        synchronized (mPackages) {
17641            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
17642
17643            // Propagate the permissions state as we do not want to drop on the floor
17644            // runtime permissions. The update permissions method below will take
17645            // care of removing obsolete permissions and grant install permissions.
17646            if (origPermissionState != null) {
17647                ps.getPermissionsState().copyFrom(origPermissionState);
17648            }
17649            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
17650                    mPermissionCallback);
17651
17652            final boolean applyUserRestrictions
17653                    = (allUserHandles != null) && (origUserHandles != null);
17654            if (applyUserRestrictions) {
17655                boolean installedStateChanged = false;
17656                if (DEBUG_REMOVE) {
17657                    Slog.d(TAG, "Propagating install state across reinstall");
17658                }
17659                for (int userId : allUserHandles) {
17660                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
17661                    if (DEBUG_REMOVE) {
17662                        Slog.d(TAG, "    user " + userId + " => " + installed);
17663                    }
17664                    if (installed != ps.getInstalled(userId)) {
17665                        installedStateChanged = true;
17666                    }
17667                    ps.setInstalled(installed, userId);
17668
17669                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17670                }
17671                // Regardless of writeSettings we need to ensure that this restriction
17672                // state propagation is persisted
17673                mSettings.writeAllUsersPackageRestrictionsLPr();
17674                if (installedStateChanged) {
17675                    mSettings.writeKernelMappingLPr(ps);
17676                }
17677            }
17678            // can downgrade to reader here
17679            if (writeSettings) {
17680                mSettings.writeLPr();
17681            }
17682        }
17683        return pkg;
17684    }
17685
17686    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17687            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17688            PackageRemovedInfo outInfo, boolean writeSettings,
17689            PackageParser.Package replacingPackage) {
17690        synchronized (mPackages) {
17691            if (outInfo != null) {
17692                outInfo.uid = ps.appId;
17693            }
17694
17695            if (outInfo != null && outInfo.removedChildPackages != null) {
17696                final int childCount = (ps.childPackageNames != null)
17697                        ? ps.childPackageNames.size() : 0;
17698                for (int i = 0; i < childCount; i++) {
17699                    String childPackageName = ps.childPackageNames.get(i);
17700                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17701                    if (childPs == null) {
17702                        return false;
17703                    }
17704                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17705                            childPackageName);
17706                    if (childInfo != null) {
17707                        childInfo.uid = childPs.appId;
17708                    }
17709                }
17710            }
17711        }
17712
17713        // Delete package data from internal structures and also remove data if flag is set
17714        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17715
17716        // Delete the child packages data
17717        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17718        for (int i = 0; i < childCount; i++) {
17719            PackageSetting childPs;
17720            synchronized (mPackages) {
17721                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17722            }
17723            if (childPs != null) {
17724                PackageRemovedInfo childOutInfo = (outInfo != null
17725                        && outInfo.removedChildPackages != null)
17726                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17727                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17728                        && (replacingPackage != null
17729                        && !replacingPackage.hasChildPackage(childPs.name))
17730                        ? flags & ~DELETE_KEEP_DATA : flags;
17731                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17732                        deleteFlags, writeSettings);
17733            }
17734        }
17735
17736        // Delete application code and resources only for parent packages
17737        if (ps.parentPackageName == null) {
17738            if (deleteCodeAndResources && (outInfo != null)) {
17739                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17740                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17741                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17742            }
17743        }
17744
17745        return true;
17746    }
17747
17748    @Override
17749    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17750            int userId) {
17751        mContext.enforceCallingOrSelfPermission(
17752                android.Manifest.permission.DELETE_PACKAGES, null);
17753        synchronized (mPackages) {
17754            // Cannot block uninstall of static shared libs as they are
17755            // considered a part of the using app (emulating static linking).
17756            // Also static libs are installed always on internal storage.
17757            PackageParser.Package pkg = mPackages.get(packageName);
17758            if (pkg != null && pkg.staticSharedLibName != null) {
17759                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17760                        + " providing static shared library: " + pkg.staticSharedLibName);
17761                return false;
17762            }
17763            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
17764            mSettings.writePackageRestrictionsLPr(userId);
17765        }
17766        return true;
17767    }
17768
17769    @Override
17770    public boolean getBlockUninstallForUser(String packageName, int userId) {
17771        synchronized (mPackages) {
17772            final PackageSetting ps = mSettings.mPackages.get(packageName);
17773            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
17774                return false;
17775            }
17776            return mSettings.getBlockUninstallLPr(userId, packageName);
17777        }
17778    }
17779
17780    @Override
17781    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17782        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
17783        synchronized (mPackages) {
17784            PackageSetting ps = mSettings.mPackages.get(packageName);
17785            if (ps == null) {
17786                Log.w(TAG, "Package doesn't exist: " + packageName);
17787                return false;
17788            }
17789            if (systemUserApp) {
17790                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17791            } else {
17792                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17793            }
17794            mSettings.writeLPr();
17795        }
17796        return true;
17797    }
17798
17799    /*
17800     * This method handles package deletion in general
17801     */
17802    private boolean deletePackageLIF(String packageName, UserHandle user,
17803            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17804            PackageRemovedInfo outInfo, boolean writeSettings,
17805            PackageParser.Package replacingPackage) {
17806        if (packageName == null) {
17807            Slog.w(TAG, "Attempt to delete null packageName.");
17808            return false;
17809        }
17810
17811        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17812
17813        PackageSetting ps;
17814        synchronized (mPackages) {
17815            ps = mSettings.mPackages.get(packageName);
17816            if (ps == null) {
17817                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17818                return false;
17819            }
17820
17821            if (ps.parentPackageName != null && (!isSystemApp(ps)
17822                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17823                if (DEBUG_REMOVE) {
17824                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17825                            + ((user == null) ? UserHandle.USER_ALL : user));
17826                }
17827                final int removedUserId = (user != null) ? user.getIdentifier()
17828                        : UserHandle.USER_ALL;
17829                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17830                    return false;
17831                }
17832                markPackageUninstalledForUserLPw(ps, user);
17833                scheduleWritePackageRestrictionsLocked(user);
17834                return true;
17835            }
17836        }
17837
17838        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17839                && user.getIdentifier() != UserHandle.USER_ALL)) {
17840            // The caller is asking that the package only be deleted for a single
17841            // user.  To do this, we just mark its uninstalled state and delete
17842            // its data. If this is a system app, we only allow this to happen if
17843            // they have set the special DELETE_SYSTEM_APP which requests different
17844            // semantics than normal for uninstalling system apps.
17845            markPackageUninstalledForUserLPw(ps, user);
17846
17847            if (!isSystemApp(ps)) {
17848                // Do not uninstall the APK if an app should be cached
17849                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17850                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17851                    // Other user still have this package installed, so all
17852                    // we need to do is clear this user's data and save that
17853                    // it is uninstalled.
17854                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17855                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17856                        return false;
17857                    }
17858                    scheduleWritePackageRestrictionsLocked(user);
17859                    return true;
17860                } else {
17861                    // We need to set it back to 'installed' so the uninstall
17862                    // broadcasts will be sent correctly.
17863                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
17864                    ps.setInstalled(true, user.getIdentifier());
17865                    mSettings.writeKernelMappingLPr(ps);
17866                }
17867            } else {
17868                // This is a system app, so we assume that the
17869                // other users still have this package installed, so all
17870                // we need to do is clear this user's data and save that
17871                // it is uninstalled.
17872                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
17873                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17874                    return false;
17875                }
17876                scheduleWritePackageRestrictionsLocked(user);
17877                return true;
17878            }
17879        }
17880
17881        // If we are deleting a composite package for all users, keep track
17882        // of result for each child.
17883        if (ps.childPackageNames != null && outInfo != null) {
17884            synchronized (mPackages) {
17885                final int childCount = ps.childPackageNames.size();
17886                outInfo.removedChildPackages = new ArrayMap<>(childCount);
17887                for (int i = 0; i < childCount; i++) {
17888                    String childPackageName = ps.childPackageNames.get(i);
17889                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
17890                    childInfo.removedPackage = childPackageName;
17891                    childInfo.installerPackageName = ps.installerPackageName;
17892                    outInfo.removedChildPackages.put(childPackageName, childInfo);
17893                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17894                    if (childPs != null) {
17895                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
17896                    }
17897                }
17898            }
17899        }
17900
17901        boolean ret = false;
17902        if (isSystemApp(ps)) {
17903            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
17904            // When an updated system application is deleted we delete the existing resources
17905            // as well and fall back to existing code in system partition
17906            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
17907        } else {
17908            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
17909            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
17910                    outInfo, writeSettings, replacingPackage);
17911        }
17912
17913        // Take a note whether we deleted the package for all users
17914        if (outInfo != null) {
17915            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17916            if (outInfo.removedChildPackages != null) {
17917                synchronized (mPackages) {
17918                    final int childCount = outInfo.removedChildPackages.size();
17919                    for (int i = 0; i < childCount; i++) {
17920                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
17921                        if (childInfo != null) {
17922                            childInfo.removedForAllUsers = mPackages.get(
17923                                    childInfo.removedPackage) == null;
17924                        }
17925                    }
17926                }
17927            }
17928            // If we uninstalled an update to a system app there may be some
17929            // child packages that appeared as they are declared in the system
17930            // app but were not declared in the update.
17931            if (isSystemApp(ps)) {
17932                synchronized (mPackages) {
17933                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
17934                    final int childCount = (updatedPs.childPackageNames != null)
17935                            ? updatedPs.childPackageNames.size() : 0;
17936                    for (int i = 0; i < childCount; i++) {
17937                        String childPackageName = updatedPs.childPackageNames.get(i);
17938                        if (outInfo.removedChildPackages == null
17939                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
17940                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
17941                            if (childPs == null) {
17942                                continue;
17943                            }
17944                            PackageInstalledInfo installRes = new PackageInstalledInfo();
17945                            installRes.name = childPackageName;
17946                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
17947                            installRes.pkg = mPackages.get(childPackageName);
17948                            installRes.uid = childPs.pkg.applicationInfo.uid;
17949                            if (outInfo.appearedChildPackages == null) {
17950                                outInfo.appearedChildPackages = new ArrayMap<>();
17951                            }
17952                            outInfo.appearedChildPackages.put(childPackageName, installRes);
17953                        }
17954                    }
17955                }
17956            }
17957        }
17958
17959        return ret;
17960    }
17961
17962    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
17963        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
17964                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
17965        for (int nextUserId : userIds) {
17966            if (DEBUG_REMOVE) {
17967                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
17968            }
17969            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
17970                    false /*installed*/,
17971                    true /*stopped*/,
17972                    true /*notLaunched*/,
17973                    false /*hidden*/,
17974                    false /*suspended*/,
17975                    false /*instantApp*/,
17976                    false /*virtualPreload*/,
17977                    null /*lastDisableAppCaller*/,
17978                    null /*enabledComponents*/,
17979                    null /*disabledComponents*/,
17980                    ps.readUserState(nextUserId).domainVerificationStatus,
17981                    0, PackageManager.INSTALL_REASON_UNKNOWN);
17982        }
17983        mSettings.writeKernelMappingLPr(ps);
17984    }
17985
17986    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
17987            PackageRemovedInfo outInfo) {
17988        final PackageParser.Package pkg;
17989        synchronized (mPackages) {
17990            pkg = mPackages.get(ps.name);
17991        }
17992
17993        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
17994                : new int[] {userId};
17995        for (int nextUserId : userIds) {
17996            if (DEBUG_REMOVE) {
17997                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
17998                        + nextUserId);
17999            }
18000
18001            destroyAppDataLIF(pkg, userId,
18002                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18003            destroyAppProfilesLIF(pkg, userId);
18004            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18005            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18006            schedulePackageCleaning(ps.name, nextUserId, false);
18007            synchronized (mPackages) {
18008                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18009                    scheduleWritePackageRestrictionsLocked(nextUserId);
18010                }
18011                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18012            }
18013        }
18014
18015        if (outInfo != null) {
18016            outInfo.removedPackage = ps.name;
18017            outInfo.installerPackageName = ps.installerPackageName;
18018            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18019            outInfo.removedAppId = ps.appId;
18020            outInfo.removedUsers = userIds;
18021            outInfo.broadcastUsers = userIds;
18022        }
18023
18024        return true;
18025    }
18026
18027    private final class ClearStorageConnection implements ServiceConnection {
18028        IMediaContainerService mContainerService;
18029
18030        @Override
18031        public void onServiceConnected(ComponentName name, IBinder service) {
18032            synchronized (this) {
18033                mContainerService = IMediaContainerService.Stub
18034                        .asInterface(Binder.allowBlocking(service));
18035                notifyAll();
18036            }
18037        }
18038
18039        @Override
18040        public void onServiceDisconnected(ComponentName name) {
18041        }
18042    }
18043
18044    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18045        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18046
18047        final boolean mounted;
18048        if (Environment.isExternalStorageEmulated()) {
18049            mounted = true;
18050        } else {
18051            final String status = Environment.getExternalStorageState();
18052
18053            mounted = status.equals(Environment.MEDIA_MOUNTED)
18054                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18055        }
18056
18057        if (!mounted) {
18058            return;
18059        }
18060
18061        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18062        int[] users;
18063        if (userId == UserHandle.USER_ALL) {
18064            users = sUserManager.getUserIds();
18065        } else {
18066            users = new int[] { userId };
18067        }
18068        final ClearStorageConnection conn = new ClearStorageConnection();
18069        if (mContext.bindServiceAsUser(
18070                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18071            try {
18072                for (int curUser : users) {
18073                    long timeout = SystemClock.uptimeMillis() + 5000;
18074                    synchronized (conn) {
18075                        long now;
18076                        while (conn.mContainerService == null &&
18077                                (now = SystemClock.uptimeMillis()) < timeout) {
18078                            try {
18079                                conn.wait(timeout - now);
18080                            } catch (InterruptedException e) {
18081                            }
18082                        }
18083                    }
18084                    if (conn.mContainerService == null) {
18085                        return;
18086                    }
18087
18088                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18089                    clearDirectory(conn.mContainerService,
18090                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18091                    if (allData) {
18092                        clearDirectory(conn.mContainerService,
18093                                userEnv.buildExternalStorageAppDataDirs(packageName));
18094                        clearDirectory(conn.mContainerService,
18095                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18096                    }
18097                }
18098            } finally {
18099                mContext.unbindService(conn);
18100            }
18101        }
18102    }
18103
18104    @Override
18105    public void clearApplicationProfileData(String packageName) {
18106        enforceSystemOrRoot("Only the system can clear all profile data");
18107
18108        final PackageParser.Package pkg;
18109        synchronized (mPackages) {
18110            pkg = mPackages.get(packageName);
18111        }
18112
18113        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18114            synchronized (mInstallLock) {
18115                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18116            }
18117        }
18118    }
18119
18120    @Override
18121    public void clearApplicationUserData(final String packageName,
18122            final IPackageDataObserver observer, final int userId) {
18123        mContext.enforceCallingOrSelfPermission(
18124                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18125
18126        final int callingUid = Binder.getCallingUid();
18127        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18128                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18129
18130        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18131        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18132        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18133            throw new SecurityException("Cannot clear data for a protected package: "
18134                    + packageName);
18135        }
18136        // Queue up an async operation since the package deletion may take a little while.
18137        mHandler.post(new Runnable() {
18138            public void run() {
18139                mHandler.removeCallbacks(this);
18140                final boolean succeeded;
18141                if (!filterApp) {
18142                    try (PackageFreezer freezer = freezePackage(packageName,
18143                            "clearApplicationUserData")) {
18144                        synchronized (mInstallLock) {
18145                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18146                        }
18147                        clearExternalStorageDataSync(packageName, userId, true);
18148                        synchronized (mPackages) {
18149                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18150                                    packageName, userId);
18151                        }
18152                    }
18153                    if (succeeded) {
18154                        // invoke DeviceStorageMonitor's update method to clear any notifications
18155                        DeviceStorageMonitorInternal dsm = LocalServices
18156                                .getService(DeviceStorageMonitorInternal.class);
18157                        if (dsm != null) {
18158                            dsm.checkMemory();
18159                        }
18160                    }
18161                } else {
18162                    succeeded = false;
18163                }
18164                if (observer != null) {
18165                    try {
18166                        observer.onRemoveCompleted(packageName, succeeded);
18167                    } catch (RemoteException e) {
18168                        Log.i(TAG, "Observer no longer exists.");
18169                    }
18170                } //end if observer
18171            } //end run
18172        });
18173    }
18174
18175    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18176        if (packageName == null) {
18177            Slog.w(TAG, "Attempt to delete null packageName.");
18178            return false;
18179        }
18180
18181        // Try finding details about the requested package
18182        PackageParser.Package pkg;
18183        synchronized (mPackages) {
18184            pkg = mPackages.get(packageName);
18185            if (pkg == null) {
18186                final PackageSetting ps = mSettings.mPackages.get(packageName);
18187                if (ps != null) {
18188                    pkg = ps.pkg;
18189                }
18190            }
18191
18192            if (pkg == null) {
18193                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18194                return false;
18195            }
18196
18197            PackageSetting ps = (PackageSetting) pkg.mExtras;
18198            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18199        }
18200
18201        clearAppDataLIF(pkg, userId,
18202                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18203
18204        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18205        removeKeystoreDataIfNeeded(userId, appId);
18206
18207        UserManagerInternal umInternal = getUserManagerInternal();
18208        final int flags;
18209        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18210            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18211        } else if (umInternal.isUserRunning(userId)) {
18212            flags = StorageManager.FLAG_STORAGE_DE;
18213        } else {
18214            flags = 0;
18215        }
18216        prepareAppDataContentsLIF(pkg, userId, flags);
18217
18218        return true;
18219    }
18220
18221    /**
18222     * Reverts user permission state changes (permissions and flags) in
18223     * all packages for a given user.
18224     *
18225     * @param userId The device user for which to do a reset.
18226     */
18227    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18228        final int packageCount = mPackages.size();
18229        for (int i = 0; i < packageCount; i++) {
18230            PackageParser.Package pkg = mPackages.valueAt(i);
18231            PackageSetting ps = (PackageSetting) pkg.mExtras;
18232            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18233        }
18234    }
18235
18236    private void resetNetworkPolicies(int userId) {
18237        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18238    }
18239
18240    /**
18241     * Reverts user permission state changes (permissions and flags).
18242     *
18243     * @param ps The package for which to reset.
18244     * @param userId The device user for which to do a reset.
18245     */
18246    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18247            final PackageSetting ps, final int userId) {
18248        if (ps.pkg == null) {
18249            return;
18250        }
18251
18252        // These are flags that can change base on user actions.
18253        final int userSettableMask = FLAG_PERMISSION_USER_SET
18254                | FLAG_PERMISSION_USER_FIXED
18255                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18256                | FLAG_PERMISSION_REVIEW_REQUIRED;
18257
18258        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18259                | FLAG_PERMISSION_POLICY_FIXED;
18260
18261        boolean writeInstallPermissions = false;
18262        boolean writeRuntimePermissions = false;
18263
18264        final int permissionCount = ps.pkg.requestedPermissions.size();
18265        for (int i = 0; i < permissionCount; i++) {
18266            final String permName = ps.pkg.requestedPermissions.get(i);
18267            final BasePermission bp =
18268                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
18269            if (bp == null) {
18270                continue;
18271            }
18272
18273            // If shared user we just reset the state to which only this app contributed.
18274            if (ps.sharedUser != null) {
18275                boolean used = false;
18276                final int packageCount = ps.sharedUser.packages.size();
18277                for (int j = 0; j < packageCount; j++) {
18278                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18279                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18280                            && pkg.pkg.requestedPermissions.contains(permName)) {
18281                        used = true;
18282                        break;
18283                    }
18284                }
18285                if (used) {
18286                    continue;
18287                }
18288            }
18289
18290            final PermissionsState permissionsState = ps.getPermissionsState();
18291
18292            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
18293
18294            // Always clear the user settable flags.
18295            final boolean hasInstallState =
18296                    permissionsState.getInstallPermissionState(permName) != null;
18297            // If permission review is enabled and this is a legacy app, mark the
18298            // permission as requiring a review as this is the initial state.
18299            int flags = 0;
18300            if (mSettings.mPermissions.mPermissionReviewRequired
18301                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18302                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18303            }
18304            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18305                if (hasInstallState) {
18306                    writeInstallPermissions = true;
18307                } else {
18308                    writeRuntimePermissions = true;
18309                }
18310            }
18311
18312            // Below is only runtime permission handling.
18313            if (!bp.isRuntime()) {
18314                continue;
18315            }
18316
18317            // Never clobber system or policy.
18318            if ((oldFlags & policyOrSystemFlags) != 0) {
18319                continue;
18320            }
18321
18322            // If this permission was granted by default, make sure it is.
18323            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18324                if (permissionsState.grantRuntimePermission(bp, userId)
18325                        != PERMISSION_OPERATION_FAILURE) {
18326                    writeRuntimePermissions = true;
18327                }
18328            // If permission review is enabled the permissions for a legacy apps
18329            // are represented as constantly granted runtime ones, so don't revoke.
18330            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18331                // Otherwise, reset the permission.
18332                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18333                switch (revokeResult) {
18334                    case PERMISSION_OPERATION_SUCCESS:
18335                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18336                        writeRuntimePermissions = true;
18337                        final int appId = ps.appId;
18338                        mHandler.post(new Runnable() {
18339                            @Override
18340                            public void run() {
18341                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18342                            }
18343                        });
18344                    } break;
18345                }
18346            }
18347        }
18348
18349        // Synchronously write as we are taking permissions away.
18350        if (writeRuntimePermissions) {
18351            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18352        }
18353
18354        // Synchronously write as we are taking permissions away.
18355        if (writeInstallPermissions) {
18356            mSettings.writeLPr();
18357        }
18358    }
18359
18360    /**
18361     * Remove entries from the keystore daemon. Will only remove it if the
18362     * {@code appId} is valid.
18363     */
18364    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18365        if (appId < 0) {
18366            return;
18367        }
18368
18369        final KeyStore keyStore = KeyStore.getInstance();
18370        if (keyStore != null) {
18371            if (userId == UserHandle.USER_ALL) {
18372                for (final int individual : sUserManager.getUserIds()) {
18373                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18374                }
18375            } else {
18376                keyStore.clearUid(UserHandle.getUid(userId, appId));
18377            }
18378        } else {
18379            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18380        }
18381    }
18382
18383    @Override
18384    public void deleteApplicationCacheFiles(final String packageName,
18385            final IPackageDataObserver observer) {
18386        final int userId = UserHandle.getCallingUserId();
18387        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18388    }
18389
18390    @Override
18391    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18392            final IPackageDataObserver observer) {
18393        final int callingUid = Binder.getCallingUid();
18394        mContext.enforceCallingOrSelfPermission(
18395                android.Manifest.permission.DELETE_CACHE_FILES, null);
18396        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18397                /* requireFullPermission= */ true, /* checkShell= */ false,
18398                "delete application cache files");
18399        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18400                android.Manifest.permission.ACCESS_INSTANT_APPS);
18401
18402        final PackageParser.Package pkg;
18403        synchronized (mPackages) {
18404            pkg = mPackages.get(packageName);
18405        }
18406
18407        // Queue up an async operation since the package deletion may take a little while.
18408        mHandler.post(new Runnable() {
18409            public void run() {
18410                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
18411                boolean doClearData = true;
18412                if (ps != null) {
18413                    final boolean targetIsInstantApp =
18414                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18415                    doClearData = !targetIsInstantApp
18416                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18417                }
18418                if (doClearData) {
18419                    synchronized (mInstallLock) {
18420                        final int flags = StorageManager.FLAG_STORAGE_DE
18421                                | StorageManager.FLAG_STORAGE_CE;
18422                        // We're only clearing cache files, so we don't care if the
18423                        // app is unfrozen and still able to run
18424                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18425                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18426                    }
18427                    clearExternalStorageDataSync(packageName, userId, false);
18428                }
18429                if (observer != null) {
18430                    try {
18431                        observer.onRemoveCompleted(packageName, true);
18432                    } catch (RemoteException e) {
18433                        Log.i(TAG, "Observer no longer exists.");
18434                    }
18435                }
18436            }
18437        });
18438    }
18439
18440    @Override
18441    public void getPackageSizeInfo(final String packageName, int userHandle,
18442            final IPackageStatsObserver observer) {
18443        throw new UnsupportedOperationException(
18444                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18445    }
18446
18447    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18448        final PackageSetting ps;
18449        synchronized (mPackages) {
18450            ps = mSettings.mPackages.get(packageName);
18451            if (ps == null) {
18452                Slog.w(TAG, "Failed to find settings for " + packageName);
18453                return false;
18454            }
18455        }
18456
18457        final String[] packageNames = { packageName };
18458        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18459        final String[] codePaths = { ps.codePathString };
18460
18461        try {
18462            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18463                    ps.appId, ceDataInodes, codePaths, stats);
18464
18465            // For now, ignore code size of packages on system partition
18466            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18467                stats.codeSize = 0;
18468            }
18469
18470            // External clients expect these to be tracked separately
18471            stats.dataSize -= stats.cacheSize;
18472
18473        } catch (InstallerException e) {
18474            Slog.w(TAG, String.valueOf(e));
18475            return false;
18476        }
18477
18478        return true;
18479    }
18480
18481    private int getUidTargetSdkVersionLockedLPr(int uid) {
18482        Object obj = mSettings.getUserIdLPr(uid);
18483        if (obj instanceof SharedUserSetting) {
18484            final SharedUserSetting sus = (SharedUserSetting) obj;
18485            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18486            final Iterator<PackageSetting> it = sus.packages.iterator();
18487            while (it.hasNext()) {
18488                final PackageSetting ps = it.next();
18489                if (ps.pkg != null) {
18490                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18491                    if (v < vers) vers = v;
18492                }
18493            }
18494            return vers;
18495        } else if (obj instanceof PackageSetting) {
18496            final PackageSetting ps = (PackageSetting) obj;
18497            if (ps.pkg != null) {
18498                return ps.pkg.applicationInfo.targetSdkVersion;
18499            }
18500        }
18501        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18502    }
18503
18504    @Override
18505    public void addPreferredActivity(IntentFilter filter, int match,
18506            ComponentName[] set, ComponentName activity, int userId) {
18507        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18508                "Adding preferred");
18509    }
18510
18511    private void addPreferredActivityInternal(IntentFilter filter, int match,
18512            ComponentName[] set, ComponentName activity, boolean always, int userId,
18513            String opname) {
18514        // writer
18515        int callingUid = Binder.getCallingUid();
18516        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18517                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18518        if (filter.countActions() == 0) {
18519            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18520            return;
18521        }
18522        synchronized (mPackages) {
18523            if (mContext.checkCallingOrSelfPermission(
18524                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18525                    != PackageManager.PERMISSION_GRANTED) {
18526                if (getUidTargetSdkVersionLockedLPr(callingUid)
18527                        < Build.VERSION_CODES.FROYO) {
18528                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18529                            + callingUid);
18530                    return;
18531                }
18532                mContext.enforceCallingOrSelfPermission(
18533                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18534            }
18535
18536            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18537            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18538                    + userId + ":");
18539            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18540            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18541            scheduleWritePackageRestrictionsLocked(userId);
18542            postPreferredActivityChangedBroadcast(userId);
18543        }
18544    }
18545
18546    private void postPreferredActivityChangedBroadcast(int userId) {
18547        mHandler.post(() -> {
18548            final IActivityManager am = ActivityManager.getService();
18549            if (am == null) {
18550                return;
18551            }
18552
18553            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18554            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18555            try {
18556                am.broadcastIntent(null, intent, null, null,
18557                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18558                        null, false, false, userId);
18559            } catch (RemoteException e) {
18560            }
18561        });
18562    }
18563
18564    @Override
18565    public void replacePreferredActivity(IntentFilter filter, int match,
18566            ComponentName[] set, ComponentName activity, int userId) {
18567        if (filter.countActions() != 1) {
18568            throw new IllegalArgumentException(
18569                    "replacePreferredActivity expects filter to have only 1 action.");
18570        }
18571        if (filter.countDataAuthorities() != 0
18572                || filter.countDataPaths() != 0
18573                || filter.countDataSchemes() > 1
18574                || filter.countDataTypes() != 0) {
18575            throw new IllegalArgumentException(
18576                    "replacePreferredActivity expects filter to have no data authorities, " +
18577                    "paths, or types; and at most one scheme.");
18578        }
18579
18580        final int callingUid = Binder.getCallingUid();
18581        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18582                true /* requireFullPermission */, false /* checkShell */,
18583                "replace preferred activity");
18584        synchronized (mPackages) {
18585            if (mContext.checkCallingOrSelfPermission(
18586                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18587                    != PackageManager.PERMISSION_GRANTED) {
18588                if (getUidTargetSdkVersionLockedLPr(callingUid)
18589                        < Build.VERSION_CODES.FROYO) {
18590                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18591                            + Binder.getCallingUid());
18592                    return;
18593                }
18594                mContext.enforceCallingOrSelfPermission(
18595                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18596            }
18597
18598            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18599            if (pir != null) {
18600                // Get all of the existing entries that exactly match this filter.
18601                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18602                if (existing != null && existing.size() == 1) {
18603                    PreferredActivity cur = existing.get(0);
18604                    if (DEBUG_PREFERRED) {
18605                        Slog.i(TAG, "Checking replace of preferred:");
18606                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18607                        if (!cur.mPref.mAlways) {
18608                            Slog.i(TAG, "  -- CUR; not mAlways!");
18609                        } else {
18610                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18611                            Slog.i(TAG, "  -- CUR: mSet="
18612                                    + Arrays.toString(cur.mPref.mSetComponents));
18613                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18614                            Slog.i(TAG, "  -- NEW: mMatch="
18615                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18616                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18617                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18618                        }
18619                    }
18620                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18621                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18622                            && cur.mPref.sameSet(set)) {
18623                        // Setting the preferred activity to what it happens to be already
18624                        if (DEBUG_PREFERRED) {
18625                            Slog.i(TAG, "Replacing with same preferred activity "
18626                                    + cur.mPref.mShortComponent + " for user "
18627                                    + userId + ":");
18628                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18629                        }
18630                        return;
18631                    }
18632                }
18633
18634                if (existing != null) {
18635                    if (DEBUG_PREFERRED) {
18636                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18637                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18638                    }
18639                    for (int i = 0; i < existing.size(); i++) {
18640                        PreferredActivity pa = existing.get(i);
18641                        if (DEBUG_PREFERRED) {
18642                            Slog.i(TAG, "Removing existing preferred activity "
18643                                    + pa.mPref.mComponent + ":");
18644                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18645                        }
18646                        pir.removeFilter(pa);
18647                    }
18648                }
18649            }
18650            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18651                    "Replacing preferred");
18652        }
18653    }
18654
18655    @Override
18656    public void clearPackagePreferredActivities(String packageName) {
18657        final int callingUid = Binder.getCallingUid();
18658        if (getInstantAppPackageName(callingUid) != null) {
18659            return;
18660        }
18661        // writer
18662        synchronized (mPackages) {
18663            PackageParser.Package pkg = mPackages.get(packageName);
18664            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
18665                if (mContext.checkCallingOrSelfPermission(
18666                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18667                        != PackageManager.PERMISSION_GRANTED) {
18668                    if (getUidTargetSdkVersionLockedLPr(callingUid)
18669                            < Build.VERSION_CODES.FROYO) {
18670                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18671                                + callingUid);
18672                        return;
18673                    }
18674                    mContext.enforceCallingOrSelfPermission(
18675                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18676                }
18677            }
18678            final PackageSetting ps = mSettings.getPackageLPr(packageName);
18679            if (ps != null
18680                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
18681                return;
18682            }
18683            int user = UserHandle.getCallingUserId();
18684            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18685                scheduleWritePackageRestrictionsLocked(user);
18686            }
18687        }
18688    }
18689
18690    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18691    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18692        ArrayList<PreferredActivity> removed = null;
18693        boolean changed = false;
18694        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18695            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18696            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18697            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18698                continue;
18699            }
18700            Iterator<PreferredActivity> it = pir.filterIterator();
18701            while (it.hasNext()) {
18702                PreferredActivity pa = it.next();
18703                // Mark entry for removal only if it matches the package name
18704                // and the entry is of type "always".
18705                if (packageName == null ||
18706                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18707                                && pa.mPref.mAlways)) {
18708                    if (removed == null) {
18709                        removed = new ArrayList<PreferredActivity>();
18710                    }
18711                    removed.add(pa);
18712                }
18713            }
18714            if (removed != null) {
18715                for (int j=0; j<removed.size(); j++) {
18716                    PreferredActivity pa = removed.get(j);
18717                    pir.removeFilter(pa);
18718                }
18719                changed = true;
18720            }
18721        }
18722        if (changed) {
18723            postPreferredActivityChangedBroadcast(userId);
18724        }
18725        return changed;
18726    }
18727
18728    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18729    private void clearIntentFilterVerificationsLPw(int userId) {
18730        final int packageCount = mPackages.size();
18731        for (int i = 0; i < packageCount; i++) {
18732            PackageParser.Package pkg = mPackages.valueAt(i);
18733            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18734        }
18735    }
18736
18737    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18738    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18739        if (userId == UserHandle.USER_ALL) {
18740            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18741                    sUserManager.getUserIds())) {
18742                for (int oneUserId : sUserManager.getUserIds()) {
18743                    scheduleWritePackageRestrictionsLocked(oneUserId);
18744                }
18745            }
18746        } else {
18747            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18748                scheduleWritePackageRestrictionsLocked(userId);
18749            }
18750        }
18751    }
18752
18753    /** Clears state for all users, and touches intent filter verification policy */
18754    void clearDefaultBrowserIfNeeded(String packageName) {
18755        for (int oneUserId : sUserManager.getUserIds()) {
18756            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
18757        }
18758    }
18759
18760    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
18761        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
18762        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
18763            if (packageName.equals(defaultBrowserPackageName)) {
18764                setDefaultBrowserPackageName(null, userId);
18765            }
18766        }
18767    }
18768
18769    @Override
18770    public void resetApplicationPreferences(int userId) {
18771        mContext.enforceCallingOrSelfPermission(
18772                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18773        final long identity = Binder.clearCallingIdentity();
18774        // writer
18775        try {
18776            synchronized (mPackages) {
18777                clearPackagePreferredActivitiesLPw(null, userId);
18778                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18779                // TODO: We have to reset the default SMS and Phone. This requires
18780                // significant refactoring to keep all default apps in the package
18781                // manager (cleaner but more work) or have the services provide
18782                // callbacks to the package manager to request a default app reset.
18783                applyFactoryDefaultBrowserLPw(userId);
18784                clearIntentFilterVerificationsLPw(userId);
18785                primeDomainVerificationsLPw(userId);
18786                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18787                scheduleWritePackageRestrictionsLocked(userId);
18788            }
18789            resetNetworkPolicies(userId);
18790        } finally {
18791            Binder.restoreCallingIdentity(identity);
18792        }
18793    }
18794
18795    @Override
18796    public int getPreferredActivities(List<IntentFilter> outFilters,
18797            List<ComponentName> outActivities, String packageName) {
18798        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
18799            return 0;
18800        }
18801        int num = 0;
18802        final int userId = UserHandle.getCallingUserId();
18803        // reader
18804        synchronized (mPackages) {
18805            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18806            if (pir != null) {
18807                final Iterator<PreferredActivity> it = pir.filterIterator();
18808                while (it.hasNext()) {
18809                    final PreferredActivity pa = it.next();
18810                    if (packageName == null
18811                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18812                                    && pa.mPref.mAlways)) {
18813                        if (outFilters != null) {
18814                            outFilters.add(new IntentFilter(pa));
18815                        }
18816                        if (outActivities != null) {
18817                            outActivities.add(pa.mPref.mComponent);
18818                        }
18819                    }
18820                }
18821            }
18822        }
18823
18824        return num;
18825    }
18826
18827    @Override
18828    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18829            int userId) {
18830        int callingUid = Binder.getCallingUid();
18831        if (callingUid != Process.SYSTEM_UID) {
18832            throw new SecurityException(
18833                    "addPersistentPreferredActivity can only be run by the system");
18834        }
18835        if (filter.countActions() == 0) {
18836            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18837            return;
18838        }
18839        synchronized (mPackages) {
18840            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18841                    ":");
18842            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18843            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18844                    new PersistentPreferredActivity(filter, activity));
18845            scheduleWritePackageRestrictionsLocked(userId);
18846            postPreferredActivityChangedBroadcast(userId);
18847        }
18848    }
18849
18850    @Override
18851    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18852        int callingUid = Binder.getCallingUid();
18853        if (callingUid != Process.SYSTEM_UID) {
18854            throw new SecurityException(
18855                    "clearPackagePersistentPreferredActivities can only be run by the system");
18856        }
18857        ArrayList<PersistentPreferredActivity> removed = null;
18858        boolean changed = false;
18859        synchronized (mPackages) {
18860            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18861                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18862                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18863                        .valueAt(i);
18864                if (userId != thisUserId) {
18865                    continue;
18866                }
18867                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18868                while (it.hasNext()) {
18869                    PersistentPreferredActivity ppa = it.next();
18870                    // Mark entry for removal only if it matches the package name.
18871                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18872                        if (removed == null) {
18873                            removed = new ArrayList<PersistentPreferredActivity>();
18874                        }
18875                        removed.add(ppa);
18876                    }
18877                }
18878                if (removed != null) {
18879                    for (int j=0; j<removed.size(); j++) {
18880                        PersistentPreferredActivity ppa = removed.get(j);
18881                        ppir.removeFilter(ppa);
18882                    }
18883                    changed = true;
18884                }
18885            }
18886
18887            if (changed) {
18888                scheduleWritePackageRestrictionsLocked(userId);
18889                postPreferredActivityChangedBroadcast(userId);
18890            }
18891        }
18892    }
18893
18894    /**
18895     * Common machinery for picking apart a restored XML blob and passing
18896     * it to a caller-supplied functor to be applied to the running system.
18897     */
18898    private void restoreFromXml(XmlPullParser parser, int userId,
18899            String expectedStartTag, BlobXmlRestorer functor)
18900            throws IOException, XmlPullParserException {
18901        int type;
18902        while ((type = parser.next()) != XmlPullParser.START_TAG
18903                && type != XmlPullParser.END_DOCUMENT) {
18904        }
18905        if (type != XmlPullParser.START_TAG) {
18906            // oops didn't find a start tag?!
18907            if (DEBUG_BACKUP) {
18908                Slog.e(TAG, "Didn't find start tag during restore");
18909            }
18910            return;
18911        }
18912Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
18913        // this is supposed to be TAG_PREFERRED_BACKUP
18914        if (!expectedStartTag.equals(parser.getName())) {
18915            if (DEBUG_BACKUP) {
18916                Slog.e(TAG, "Found unexpected tag " + parser.getName());
18917            }
18918            return;
18919        }
18920
18921        // skip interfering stuff, then we're aligned with the backing implementation
18922        while ((type = parser.next()) == XmlPullParser.TEXT) { }
18923Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
18924        functor.apply(parser, userId);
18925    }
18926
18927    private interface BlobXmlRestorer {
18928        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
18929    }
18930
18931    /**
18932     * Non-Binder method, support for the backup/restore mechanism: write the
18933     * full set of preferred activities in its canonical XML format.  Returns the
18934     * XML output as a byte array, or null if there is none.
18935     */
18936    @Override
18937    public byte[] getPreferredActivityBackup(int userId) {
18938        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18939            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
18940        }
18941
18942        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
18943        try {
18944            final XmlSerializer serializer = new FastXmlSerializer();
18945            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
18946            serializer.startDocument(null, true);
18947            serializer.startTag(null, TAG_PREFERRED_BACKUP);
18948
18949            synchronized (mPackages) {
18950                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
18951            }
18952
18953            serializer.endTag(null, TAG_PREFERRED_BACKUP);
18954            serializer.endDocument();
18955            serializer.flush();
18956        } catch (Exception e) {
18957            if (DEBUG_BACKUP) {
18958                Slog.e(TAG, "Unable to write preferred activities for backup", e);
18959            }
18960            return null;
18961        }
18962
18963        return dataStream.toByteArray();
18964    }
18965
18966    @Override
18967    public void restorePreferredActivities(byte[] backup, int userId) {
18968        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
18969            throw new SecurityException("Only the system may call restorePreferredActivities()");
18970        }
18971
18972        try {
18973            final XmlPullParser parser = Xml.newPullParser();
18974            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
18975            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
18976                    new BlobXmlRestorer() {
18977                        @Override
18978                        public void apply(XmlPullParser parser, int userId)
18979                                throws XmlPullParserException, IOException {
18980                            synchronized (mPackages) {
18981                                mSettings.readPreferredActivitiesLPw(parser, userId);
18982                            }
18983                        }
18984                    } );
18985        } catch (Exception e) {
18986            if (DEBUG_BACKUP) {
18987                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
18988            }
18989        }
18990    }
18991
18992    /**
18993     * Non-Binder method, support for the backup/restore mechanism: write the
18994     * default browser (etc) settings in its canonical XML format.  Returns the default
18995     * browser XML representation as a byte array, or null if there is none.
18996     */
18997    @Override
18998    public byte[] getDefaultAppsBackup(int userId) {
18999        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19000            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19001        }
19002
19003        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19004        try {
19005            final XmlSerializer serializer = new FastXmlSerializer();
19006            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19007            serializer.startDocument(null, true);
19008            serializer.startTag(null, TAG_DEFAULT_APPS);
19009
19010            synchronized (mPackages) {
19011                mSettings.writeDefaultAppsLPr(serializer, userId);
19012            }
19013
19014            serializer.endTag(null, TAG_DEFAULT_APPS);
19015            serializer.endDocument();
19016            serializer.flush();
19017        } catch (Exception e) {
19018            if (DEBUG_BACKUP) {
19019                Slog.e(TAG, "Unable to write default apps for backup", e);
19020            }
19021            return null;
19022        }
19023
19024        return dataStream.toByteArray();
19025    }
19026
19027    @Override
19028    public void restoreDefaultApps(byte[] backup, int userId) {
19029        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19030            throw new SecurityException("Only the system may call restoreDefaultApps()");
19031        }
19032
19033        try {
19034            final XmlPullParser parser = Xml.newPullParser();
19035            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19036            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19037                    new BlobXmlRestorer() {
19038                        @Override
19039                        public void apply(XmlPullParser parser, int userId)
19040                                throws XmlPullParserException, IOException {
19041                            synchronized (mPackages) {
19042                                mSettings.readDefaultAppsLPw(parser, userId);
19043                            }
19044                        }
19045                    } );
19046        } catch (Exception e) {
19047            if (DEBUG_BACKUP) {
19048                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19049            }
19050        }
19051    }
19052
19053    @Override
19054    public byte[] getIntentFilterVerificationBackup(int userId) {
19055        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19056            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19057        }
19058
19059        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19060        try {
19061            final XmlSerializer serializer = new FastXmlSerializer();
19062            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19063            serializer.startDocument(null, true);
19064            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19065
19066            synchronized (mPackages) {
19067                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19068            }
19069
19070            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19071            serializer.endDocument();
19072            serializer.flush();
19073        } catch (Exception e) {
19074            if (DEBUG_BACKUP) {
19075                Slog.e(TAG, "Unable to write default apps for backup", e);
19076            }
19077            return null;
19078        }
19079
19080        return dataStream.toByteArray();
19081    }
19082
19083    @Override
19084    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19085        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19086            throw new SecurityException("Only the system may call restorePreferredActivities()");
19087        }
19088
19089        try {
19090            final XmlPullParser parser = Xml.newPullParser();
19091            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19092            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19093                    new BlobXmlRestorer() {
19094                        @Override
19095                        public void apply(XmlPullParser parser, int userId)
19096                                throws XmlPullParserException, IOException {
19097                            synchronized (mPackages) {
19098                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19099                                mSettings.writeLPr();
19100                            }
19101                        }
19102                    } );
19103        } catch (Exception e) {
19104            if (DEBUG_BACKUP) {
19105                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19106            }
19107        }
19108    }
19109
19110    @Override
19111    public byte[] getPermissionGrantBackup(int userId) {
19112        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19113            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19114        }
19115
19116        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19117        try {
19118            final XmlSerializer serializer = new FastXmlSerializer();
19119            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19120            serializer.startDocument(null, true);
19121            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19122
19123            synchronized (mPackages) {
19124                serializeRuntimePermissionGrantsLPr(serializer, userId);
19125            }
19126
19127            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19128            serializer.endDocument();
19129            serializer.flush();
19130        } catch (Exception e) {
19131            if (DEBUG_BACKUP) {
19132                Slog.e(TAG, "Unable to write default apps for backup", e);
19133            }
19134            return null;
19135        }
19136
19137        return dataStream.toByteArray();
19138    }
19139
19140    @Override
19141    public void restorePermissionGrants(byte[] backup, int userId) {
19142        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19143            throw new SecurityException("Only the system may call restorePermissionGrants()");
19144        }
19145
19146        try {
19147            final XmlPullParser parser = Xml.newPullParser();
19148            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19149            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19150                    new BlobXmlRestorer() {
19151                        @Override
19152                        public void apply(XmlPullParser parser, int userId)
19153                                throws XmlPullParserException, IOException {
19154                            synchronized (mPackages) {
19155                                processRestoredPermissionGrantsLPr(parser, userId);
19156                            }
19157                        }
19158                    } );
19159        } catch (Exception e) {
19160            if (DEBUG_BACKUP) {
19161                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19162            }
19163        }
19164    }
19165
19166    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19167            throws IOException {
19168        serializer.startTag(null, TAG_ALL_GRANTS);
19169
19170        final int N = mSettings.mPackages.size();
19171        for (int i = 0; i < N; i++) {
19172            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19173            boolean pkgGrantsKnown = false;
19174
19175            PermissionsState packagePerms = ps.getPermissionsState();
19176
19177            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19178                final int grantFlags = state.getFlags();
19179                // only look at grants that are not system/policy fixed
19180                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19181                    final boolean isGranted = state.isGranted();
19182                    // And only back up the user-twiddled state bits
19183                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19184                        final String packageName = mSettings.mPackages.keyAt(i);
19185                        if (!pkgGrantsKnown) {
19186                            serializer.startTag(null, TAG_GRANT);
19187                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19188                            pkgGrantsKnown = true;
19189                        }
19190
19191                        final boolean userSet =
19192                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19193                        final boolean userFixed =
19194                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19195                        final boolean revoke =
19196                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19197
19198                        serializer.startTag(null, TAG_PERMISSION);
19199                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19200                        if (isGranted) {
19201                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19202                        }
19203                        if (userSet) {
19204                            serializer.attribute(null, ATTR_USER_SET, "true");
19205                        }
19206                        if (userFixed) {
19207                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19208                        }
19209                        if (revoke) {
19210                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19211                        }
19212                        serializer.endTag(null, TAG_PERMISSION);
19213                    }
19214                }
19215            }
19216
19217            if (pkgGrantsKnown) {
19218                serializer.endTag(null, TAG_GRANT);
19219            }
19220        }
19221
19222        serializer.endTag(null, TAG_ALL_GRANTS);
19223    }
19224
19225    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19226            throws XmlPullParserException, IOException {
19227        String pkgName = null;
19228        int outerDepth = parser.getDepth();
19229        int type;
19230        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19231                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19232            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19233                continue;
19234            }
19235
19236            final String tagName = parser.getName();
19237            if (tagName.equals(TAG_GRANT)) {
19238                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19239                if (DEBUG_BACKUP) {
19240                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19241                }
19242            } else if (tagName.equals(TAG_PERMISSION)) {
19243
19244                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19245                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19246
19247                int newFlagSet = 0;
19248                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19249                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19250                }
19251                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19252                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19253                }
19254                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19255                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19256                }
19257                if (DEBUG_BACKUP) {
19258                    Slog.v(TAG, "  + Restoring grant:"
19259                            + " pkg=" + pkgName
19260                            + " perm=" + permName
19261                            + " granted=" + isGranted
19262                            + " bits=0x" + Integer.toHexString(newFlagSet));
19263                }
19264                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19265                if (ps != null) {
19266                    // Already installed so we apply the grant immediately
19267                    if (DEBUG_BACKUP) {
19268                        Slog.v(TAG, "        + already installed; applying");
19269                    }
19270                    PermissionsState perms = ps.getPermissionsState();
19271                    BasePermission bp =
19272                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19273                    if (bp != null) {
19274                        if (isGranted) {
19275                            perms.grantRuntimePermission(bp, userId);
19276                        }
19277                        if (newFlagSet != 0) {
19278                            perms.updatePermissionFlags(
19279                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19280                        }
19281                    }
19282                } else {
19283                    // Need to wait for post-restore install to apply the grant
19284                    if (DEBUG_BACKUP) {
19285                        Slog.v(TAG, "        - not yet installed; saving for later");
19286                    }
19287                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19288                            isGranted, newFlagSet, userId);
19289                }
19290            } else {
19291                PackageManagerService.reportSettingsProblem(Log.WARN,
19292                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19293                XmlUtils.skipCurrentTag(parser);
19294            }
19295        }
19296
19297        scheduleWriteSettingsLocked();
19298        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19299    }
19300
19301    @Override
19302    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19303            int sourceUserId, int targetUserId, int flags) {
19304        mContext.enforceCallingOrSelfPermission(
19305                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19306        int callingUid = Binder.getCallingUid();
19307        enforceOwnerRights(ownerPackage, callingUid);
19308        PackageManagerServiceUtils.enforceShellRestriction(
19309                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19310        if (intentFilter.countActions() == 0) {
19311            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19312            return;
19313        }
19314        synchronized (mPackages) {
19315            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19316                    ownerPackage, targetUserId, flags);
19317            CrossProfileIntentResolver resolver =
19318                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19319            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19320            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19321            if (existing != null) {
19322                int size = existing.size();
19323                for (int i = 0; i < size; i++) {
19324                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19325                        return;
19326                    }
19327                }
19328            }
19329            resolver.addFilter(newFilter);
19330            scheduleWritePackageRestrictionsLocked(sourceUserId);
19331        }
19332    }
19333
19334    @Override
19335    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19336        mContext.enforceCallingOrSelfPermission(
19337                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19338        final int callingUid = Binder.getCallingUid();
19339        enforceOwnerRights(ownerPackage, callingUid);
19340        PackageManagerServiceUtils.enforceShellRestriction(
19341                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19342        synchronized (mPackages) {
19343            CrossProfileIntentResolver resolver =
19344                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19345            ArraySet<CrossProfileIntentFilter> set =
19346                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19347            for (CrossProfileIntentFilter filter : set) {
19348                if (filter.getOwnerPackage().equals(ownerPackage)) {
19349                    resolver.removeFilter(filter);
19350                }
19351            }
19352            scheduleWritePackageRestrictionsLocked(sourceUserId);
19353        }
19354    }
19355
19356    // Enforcing that callingUid is owning pkg on userId
19357    private void enforceOwnerRights(String pkg, int callingUid) {
19358        // The system owns everything.
19359        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19360            return;
19361        }
19362        final int callingUserId = UserHandle.getUserId(callingUid);
19363        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19364        if (pi == null) {
19365            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19366                    + callingUserId);
19367        }
19368        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19369            throw new SecurityException("Calling uid " + callingUid
19370                    + " does not own package " + pkg);
19371        }
19372    }
19373
19374    @Override
19375    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19376        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19377            return null;
19378        }
19379        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19380    }
19381
19382    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
19383        UserManagerService ums = UserManagerService.getInstance();
19384        if (ums != null) {
19385            final UserInfo parent = ums.getProfileParent(userId);
19386            final int launcherUid = (parent != null) ? parent.id : userId;
19387            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
19388            if (launcherComponent != null) {
19389                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
19390                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
19391                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
19392                        .setPackage(launcherComponent.getPackageName());
19393                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
19394            }
19395        }
19396    }
19397
19398    /**
19399     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19400     * then reports the most likely home activity or null if there are more than one.
19401     */
19402    private ComponentName getDefaultHomeActivity(int userId) {
19403        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19404        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19405        if (cn != null) {
19406            return cn;
19407        }
19408
19409        // Find the launcher with the highest priority and return that component if there are no
19410        // other home activity with the same priority.
19411        int lastPriority = Integer.MIN_VALUE;
19412        ComponentName lastComponent = null;
19413        final int size = allHomeCandidates.size();
19414        for (int i = 0; i < size; i++) {
19415            final ResolveInfo ri = allHomeCandidates.get(i);
19416            if (ri.priority > lastPriority) {
19417                lastComponent = ri.activityInfo.getComponentName();
19418                lastPriority = ri.priority;
19419            } else if (ri.priority == lastPriority) {
19420                // Two components found with same priority.
19421                lastComponent = null;
19422            }
19423        }
19424        return lastComponent;
19425    }
19426
19427    private Intent getHomeIntent() {
19428        Intent intent = new Intent(Intent.ACTION_MAIN);
19429        intent.addCategory(Intent.CATEGORY_HOME);
19430        intent.addCategory(Intent.CATEGORY_DEFAULT);
19431        return intent;
19432    }
19433
19434    private IntentFilter getHomeFilter() {
19435        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19436        filter.addCategory(Intent.CATEGORY_HOME);
19437        filter.addCategory(Intent.CATEGORY_DEFAULT);
19438        return filter;
19439    }
19440
19441    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19442            int userId) {
19443        Intent intent  = getHomeIntent();
19444        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19445                PackageManager.GET_META_DATA, userId);
19446        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19447                true, false, false, userId);
19448
19449        allHomeCandidates.clear();
19450        if (list != null) {
19451            for (ResolveInfo ri : list) {
19452                allHomeCandidates.add(ri);
19453            }
19454        }
19455        return (preferred == null || preferred.activityInfo == null)
19456                ? null
19457                : new ComponentName(preferred.activityInfo.packageName,
19458                        preferred.activityInfo.name);
19459    }
19460
19461    @Override
19462    public void setHomeActivity(ComponentName comp, int userId) {
19463        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19464            return;
19465        }
19466        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19467        getHomeActivitiesAsUser(homeActivities, userId);
19468
19469        boolean found = false;
19470
19471        final int size = homeActivities.size();
19472        final ComponentName[] set = new ComponentName[size];
19473        for (int i = 0; i < size; i++) {
19474            final ResolveInfo candidate = homeActivities.get(i);
19475            final ActivityInfo info = candidate.activityInfo;
19476            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19477            set[i] = activityName;
19478            if (!found && activityName.equals(comp)) {
19479                found = true;
19480            }
19481        }
19482        if (!found) {
19483            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19484                    + userId);
19485        }
19486        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19487                set, comp, userId);
19488    }
19489
19490    private @Nullable String getSetupWizardPackageName() {
19491        final Intent intent = new Intent(Intent.ACTION_MAIN);
19492        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19493
19494        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19495                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19496                        | MATCH_DISABLED_COMPONENTS,
19497                UserHandle.myUserId());
19498        if (matches.size() == 1) {
19499            return matches.get(0).getComponentInfo().packageName;
19500        } else {
19501            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19502                    + ": matches=" + matches);
19503            return null;
19504        }
19505    }
19506
19507    private @Nullable String getStorageManagerPackageName() {
19508        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19509
19510        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19511                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19512                        | MATCH_DISABLED_COMPONENTS,
19513                UserHandle.myUserId());
19514        if (matches.size() == 1) {
19515            return matches.get(0).getComponentInfo().packageName;
19516        } else {
19517            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19518                    + matches.size() + ": matches=" + matches);
19519            return null;
19520        }
19521    }
19522
19523    @Override
19524    public void setApplicationEnabledSetting(String appPackageName,
19525            int newState, int flags, int userId, String callingPackage) {
19526        if (!sUserManager.exists(userId)) return;
19527        if (callingPackage == null) {
19528            callingPackage = Integer.toString(Binder.getCallingUid());
19529        }
19530        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19531    }
19532
19533    @Override
19534    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19535        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19536        synchronized (mPackages) {
19537            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19538            if (pkgSetting != null) {
19539                pkgSetting.setUpdateAvailable(updateAvailable);
19540            }
19541        }
19542    }
19543
19544    @Override
19545    public void setComponentEnabledSetting(ComponentName componentName,
19546            int newState, int flags, int userId) {
19547        if (!sUserManager.exists(userId)) return;
19548        setEnabledSetting(componentName.getPackageName(),
19549                componentName.getClassName(), newState, flags, userId, null);
19550    }
19551
19552    private void setEnabledSetting(final String packageName, String className, int newState,
19553            final int flags, int userId, String callingPackage) {
19554        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19555              || newState == COMPONENT_ENABLED_STATE_ENABLED
19556              || newState == COMPONENT_ENABLED_STATE_DISABLED
19557              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19558              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19559            throw new IllegalArgumentException("Invalid new component state: "
19560                    + newState);
19561        }
19562        PackageSetting pkgSetting;
19563        final int callingUid = Binder.getCallingUid();
19564        final int permission;
19565        if (callingUid == Process.SYSTEM_UID) {
19566            permission = PackageManager.PERMISSION_GRANTED;
19567        } else {
19568            permission = mContext.checkCallingOrSelfPermission(
19569                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19570        }
19571        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19572                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19573        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19574        boolean sendNow = false;
19575        boolean isApp = (className == null);
19576        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
19577        String componentName = isApp ? packageName : className;
19578        int packageUid = -1;
19579        ArrayList<String> components;
19580
19581        // reader
19582        synchronized (mPackages) {
19583            pkgSetting = mSettings.mPackages.get(packageName);
19584            if (pkgSetting == null) {
19585                if (!isCallerInstantApp) {
19586                    if (className == null) {
19587                        throw new IllegalArgumentException("Unknown package: " + packageName);
19588                    }
19589                    throw new IllegalArgumentException(
19590                            "Unknown component: " + packageName + "/" + className);
19591                } else {
19592                    // throw SecurityException to prevent leaking package information
19593                    throw new SecurityException(
19594                            "Attempt to change component state; "
19595                            + "pid=" + Binder.getCallingPid()
19596                            + ", uid=" + callingUid
19597                            + (className == null
19598                                    ? ", package=" + packageName
19599                                    : ", component=" + packageName + "/" + className));
19600                }
19601            }
19602        }
19603
19604        // Limit who can change which apps
19605        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
19606            // Don't allow apps that don't have permission to modify other apps
19607            if (!allowedByPermission
19608                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
19609                throw new SecurityException(
19610                        "Attempt to change component state; "
19611                        + "pid=" + Binder.getCallingPid()
19612                        + ", uid=" + callingUid
19613                        + (className == null
19614                                ? ", package=" + packageName
19615                                : ", component=" + packageName + "/" + className));
19616            }
19617            // Don't allow changing protected packages.
19618            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19619                throw new SecurityException("Cannot disable a protected package: " + packageName);
19620            }
19621        }
19622
19623        synchronized (mPackages) {
19624            if (callingUid == Process.SHELL_UID
19625                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19626                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19627                // unless it is a test package.
19628                int oldState = pkgSetting.getEnabled(userId);
19629                if (className == null
19630                        &&
19631                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19632                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19633                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19634                        &&
19635                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19636                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
19637                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19638                    // ok
19639                } else {
19640                    throw new SecurityException(
19641                            "Shell cannot change component state for " + packageName + "/"
19642                                    + className + " to " + newState);
19643                }
19644            }
19645        }
19646        if (className == null) {
19647            // We're dealing with an application/package level state change
19648            synchronized (mPackages) {
19649                if (pkgSetting.getEnabled(userId) == newState) {
19650                    // Nothing to do
19651                    return;
19652                }
19653            }
19654            // If we're enabling a system stub, there's a little more work to do.
19655            // Prior to enabling the package, we need to decompress the APK(s) to the
19656            // data partition and then replace the version on the system partition.
19657            final PackageParser.Package deletedPkg = pkgSetting.pkg;
19658            final boolean isSystemStub = deletedPkg.isStub
19659                    && deletedPkg.isSystem();
19660            if (isSystemStub
19661                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19662                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
19663                final File codePath = decompressPackage(deletedPkg);
19664                if (codePath == null) {
19665                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
19666                    return;
19667                }
19668                // TODO remove direct parsing of the package object during internal cleanup
19669                // of scan package
19670                // We need to call parse directly here for no other reason than we need
19671                // the new package in order to disable the old one [we use the information
19672                // for some internal optimization to optionally create a new package setting
19673                // object on replace]. However, we can't get the package from the scan
19674                // because the scan modifies live structures and we need to remove the
19675                // old [system] package from the system before a scan can be attempted.
19676                // Once scan is indempotent we can remove this parse and use the package
19677                // object we scanned, prior to adding it to package settings.
19678                final PackageParser pp = new PackageParser();
19679                pp.setSeparateProcesses(mSeparateProcesses);
19680                pp.setDisplayMetrics(mMetrics);
19681                pp.setCallback(mPackageParserCallback);
19682                final PackageParser.Package tmpPkg;
19683                try {
19684                    final @ParseFlags int parseFlags = mDefParseFlags
19685                            | PackageParser.PARSE_MUST_BE_APK
19686                            | PackageParser.PARSE_IS_SYSTEM_DIR;
19687                    tmpPkg = pp.parsePackage(codePath, parseFlags);
19688                } catch (PackageParserException e) {
19689                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
19690                    return;
19691                }
19692                synchronized (mInstallLock) {
19693                    // Disable the stub and remove any package entries
19694                    removePackageLI(deletedPkg, true);
19695                    synchronized (mPackages) {
19696                        disableSystemPackageLPw(deletedPkg, tmpPkg);
19697                    }
19698                    final PackageParser.Package pkg;
19699                    try (PackageFreezer freezer =
19700                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19701                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
19702                                | PackageParser.PARSE_ENFORCE_CODE;
19703                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
19704                                0 /*currentTime*/, null /*user*/);
19705                        prepareAppDataAfterInstallLIF(pkg);
19706                        synchronized (mPackages) {
19707                            try {
19708                                updateSharedLibrariesLPr(pkg, null);
19709                            } catch (PackageManagerException e) {
19710                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
19711                            }
19712                            mPermissionManager.updatePermissions(
19713                                    pkg.packageName, pkg, true, mPackages.values(),
19714                                    mPermissionCallback);
19715                            mSettings.writeLPr();
19716                        }
19717                    } catch (PackageManagerException e) {
19718                        // Whoops! Something went wrong; try to roll back to the stub
19719                        Slog.w(TAG, "Failed to install compressed system package:"
19720                                + pkgSetting.name, e);
19721                        // Remove the failed install
19722                        removeCodePathLI(codePath);
19723
19724                        // Install the system package
19725                        try (PackageFreezer freezer =
19726                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
19727                            synchronized (mPackages) {
19728                                // NOTE: The system package always needs to be enabled; even
19729                                // if it's for a compressed stub. If we don't, installing the
19730                                // system package fails during scan [scanning checks the disabled
19731                                // packages]. We will reverse this later, after we've "installed"
19732                                // the stub.
19733                                // This leaves us in a fragile state; the stub should never be
19734                                // enabled, so, cross your fingers and hope nothing goes wrong
19735                                // until we can disable the package later.
19736                                enableSystemPackageLPw(deletedPkg);
19737                            }
19738                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
19739                                    false /*isPrivileged*/, null /*allUserHandles*/,
19740                                    null /*origUserHandles*/, null /*origPermissionsState*/,
19741                                    true /*writeSettings*/);
19742                        } catch (PackageManagerException pme) {
19743                            Slog.w(TAG, "Failed to restore system package:"
19744                                    + deletedPkg.packageName, pme);
19745                        } finally {
19746                            synchronized (mPackages) {
19747                                mSettings.disableSystemPackageLPw(
19748                                        deletedPkg.packageName, true /*replaced*/);
19749                                mSettings.writeLPr();
19750                            }
19751                        }
19752                        return;
19753                    }
19754                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
19755                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19756                    clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19757                    mDexManager.notifyPackageUpdated(pkg.packageName,
19758                            pkg.baseCodePath, pkg.splitCodePaths);
19759                }
19760            }
19761            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19762                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19763                // Don't care about who enables an app.
19764                callingPackage = null;
19765            }
19766            synchronized (mPackages) {
19767                pkgSetting.setEnabled(newState, userId, callingPackage);
19768            }
19769        } else {
19770            synchronized (mPackages) {
19771                // We're dealing with a component level state change
19772                // First, verify that this is a valid class name.
19773                PackageParser.Package pkg = pkgSetting.pkg;
19774                if (pkg == null || !pkg.hasComponentClassName(className)) {
19775                    if (pkg != null &&
19776                            pkg.applicationInfo.targetSdkVersion >=
19777                                    Build.VERSION_CODES.JELLY_BEAN) {
19778                        throw new IllegalArgumentException("Component class " + className
19779                                + " does not exist in " + packageName);
19780                    } else {
19781                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19782                                + className + " does not exist in " + packageName);
19783                    }
19784                }
19785                switch (newState) {
19786                    case COMPONENT_ENABLED_STATE_ENABLED:
19787                        if (!pkgSetting.enableComponentLPw(className, userId)) {
19788                            return;
19789                        }
19790                        break;
19791                    case COMPONENT_ENABLED_STATE_DISABLED:
19792                        if (!pkgSetting.disableComponentLPw(className, userId)) {
19793                            return;
19794                        }
19795                        break;
19796                    case COMPONENT_ENABLED_STATE_DEFAULT:
19797                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
19798                            return;
19799                        }
19800                        break;
19801                    default:
19802                        Slog.e(TAG, "Invalid new component state: " + newState);
19803                        return;
19804                }
19805            }
19806        }
19807        synchronized (mPackages) {
19808            scheduleWritePackageRestrictionsLocked(userId);
19809            updateSequenceNumberLP(pkgSetting, new int[] { userId });
19810            final long callingId = Binder.clearCallingIdentity();
19811            try {
19812                updateInstantAppInstallerLocked(packageName);
19813            } finally {
19814                Binder.restoreCallingIdentity(callingId);
19815            }
19816            components = mPendingBroadcasts.get(userId, packageName);
19817            final boolean newPackage = components == null;
19818            if (newPackage) {
19819                components = new ArrayList<String>();
19820            }
19821            if (!components.contains(componentName)) {
19822                components.add(componentName);
19823            }
19824            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19825                sendNow = true;
19826                // Purge entry from pending broadcast list if another one exists already
19827                // since we are sending one right away.
19828                mPendingBroadcasts.remove(userId, packageName);
19829            } else {
19830                if (newPackage) {
19831                    mPendingBroadcasts.put(userId, packageName, components);
19832                }
19833                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19834                    // Schedule a message
19835                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19836                }
19837            }
19838        }
19839
19840        long callingId = Binder.clearCallingIdentity();
19841        try {
19842            if (sendNow) {
19843                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19844                sendPackageChangedBroadcast(packageName,
19845                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19846            }
19847        } finally {
19848            Binder.restoreCallingIdentity(callingId);
19849        }
19850    }
19851
19852    @Override
19853    public void flushPackageRestrictionsAsUser(int userId) {
19854        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19855            return;
19856        }
19857        if (!sUserManager.exists(userId)) {
19858            return;
19859        }
19860        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19861                false /* checkShell */, "flushPackageRestrictions");
19862        synchronized (mPackages) {
19863            mSettings.writePackageRestrictionsLPr(userId);
19864            mDirtyUsers.remove(userId);
19865            if (mDirtyUsers.isEmpty()) {
19866                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19867            }
19868        }
19869    }
19870
19871    private void sendPackageChangedBroadcast(String packageName,
19872            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19873        if (DEBUG_INSTALL)
19874            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19875                    + componentNames);
19876        Bundle extras = new Bundle(4);
19877        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19878        String nameList[] = new String[componentNames.size()];
19879        componentNames.toArray(nameList);
19880        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19881        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19882        extras.putInt(Intent.EXTRA_UID, packageUid);
19883        // If this is not reporting a change of the overall package, then only send it
19884        // to registered receivers.  We don't want to launch a swath of apps for every
19885        // little component state change.
19886        final int flags = !componentNames.contains(packageName)
19887                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19888        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19889                new int[] {UserHandle.getUserId(packageUid)});
19890    }
19891
19892    @Override
19893    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19894        if (!sUserManager.exists(userId)) return;
19895        final int callingUid = Binder.getCallingUid();
19896        if (getInstantAppPackageName(callingUid) != null) {
19897            return;
19898        }
19899        final int permission = mContext.checkCallingOrSelfPermission(
19900                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19901        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19902        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19903                true /* requireFullPermission */, true /* checkShell */, "stop package");
19904        // writer
19905        synchronized (mPackages) {
19906            final PackageSetting ps = mSettings.mPackages.get(packageName);
19907            if (!filterAppAccessLPr(ps, callingUid, userId)
19908                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19909                            allowedByPermission, callingUid, userId)) {
19910                scheduleWritePackageRestrictionsLocked(userId);
19911            }
19912        }
19913    }
19914
19915    @Override
19916    public String getInstallerPackageName(String packageName) {
19917        final int callingUid = Binder.getCallingUid();
19918        if (getInstantAppPackageName(callingUid) != null) {
19919            return null;
19920        }
19921        // reader
19922        synchronized (mPackages) {
19923            final PackageSetting ps = mSettings.mPackages.get(packageName);
19924            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19925                return null;
19926            }
19927            return mSettings.getInstallerPackageNameLPr(packageName);
19928        }
19929    }
19930
19931    public boolean isOrphaned(String packageName) {
19932        // reader
19933        synchronized (mPackages) {
19934            return mSettings.isOrphaned(packageName);
19935        }
19936    }
19937
19938    @Override
19939    public int getApplicationEnabledSetting(String packageName, int userId) {
19940        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19941        int callingUid = Binder.getCallingUid();
19942        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19943                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19944        // reader
19945        synchronized (mPackages) {
19946            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
19947                return COMPONENT_ENABLED_STATE_DISABLED;
19948            }
19949            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19950        }
19951    }
19952
19953    @Override
19954    public int getComponentEnabledSetting(ComponentName component, int userId) {
19955        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19956        int callingUid = Binder.getCallingUid();
19957        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19958                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
19959        synchronized (mPackages) {
19960            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
19961                    component, TYPE_UNKNOWN, userId)) {
19962                return COMPONENT_ENABLED_STATE_DISABLED;
19963            }
19964            return mSettings.getComponentEnabledSettingLPr(component, userId);
19965        }
19966    }
19967
19968    @Override
19969    public void enterSafeMode() {
19970        enforceSystemOrRoot("Only the system can request entering safe mode");
19971
19972        if (!mSystemReady) {
19973            mSafeMode = true;
19974        }
19975    }
19976
19977    @Override
19978    public void systemReady() {
19979        enforceSystemOrRoot("Only the system can claim the system is ready");
19980
19981        mSystemReady = true;
19982        final ContentResolver resolver = mContext.getContentResolver();
19983        ContentObserver co = new ContentObserver(mHandler) {
19984            @Override
19985            public void onChange(boolean selfChange) {
19986                mEphemeralAppsDisabled =
19987                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
19988                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
19989            }
19990        };
19991        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
19992                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
19993                false, co, UserHandle.USER_SYSTEM);
19994        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
19995                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
19996        co.onChange(true);
19997
19998        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19999        // disabled after already being started.
20000        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20001                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20002
20003        // Read the compatibilty setting when the system is ready.
20004        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20005                mContext.getContentResolver(),
20006                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20007        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20008        if (DEBUG_SETTINGS) {
20009            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20010        }
20011
20012        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20013
20014        synchronized (mPackages) {
20015            // Verify that all of the preferred activity components actually
20016            // exist.  It is possible for applications to be updated and at
20017            // that point remove a previously declared activity component that
20018            // had been set as a preferred activity.  We try to clean this up
20019            // the next time we encounter that preferred activity, but it is
20020            // possible for the user flow to never be able to return to that
20021            // situation so here we do a sanity check to make sure we haven't
20022            // left any junk around.
20023            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20024            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20025                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20026                removed.clear();
20027                for (PreferredActivity pa : pir.filterSet()) {
20028                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20029                        removed.add(pa);
20030                    }
20031                }
20032                if (removed.size() > 0) {
20033                    for (int r=0; r<removed.size(); r++) {
20034                        PreferredActivity pa = removed.get(r);
20035                        Slog.w(TAG, "Removing dangling preferred activity: "
20036                                + pa.mPref.mComponent);
20037                        pir.removeFilter(pa);
20038                    }
20039                    mSettings.writePackageRestrictionsLPr(
20040                            mSettings.mPreferredActivities.keyAt(i));
20041                }
20042            }
20043
20044            for (int userId : UserManagerService.getInstance().getUserIds()) {
20045                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20046                    grantPermissionsUserIds = ArrayUtils.appendInt(
20047                            grantPermissionsUserIds, userId);
20048                }
20049            }
20050        }
20051        sUserManager.systemReady();
20052
20053        // If we upgraded grant all default permissions before kicking off.
20054        for (int userId : grantPermissionsUserIds) {
20055            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
20056        }
20057
20058        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20059            // If we did not grant default permissions, we preload from this the
20060            // default permission exceptions lazily to ensure we don't hit the
20061            // disk on a new user creation.
20062            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20063        }
20064
20065        // Now that we've scanned all packages, and granted any default
20066        // permissions, ensure permissions are updated. Beware of dragons if you
20067        // try optimizing this.
20068        synchronized (mPackages) {
20069            mPermissionManager.updateAllPermissions(
20070                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20071                    mPermissionCallback);
20072        }
20073
20074        // Kick off any messages waiting for system ready
20075        if (mPostSystemReadyMessages != null) {
20076            for (Message msg : mPostSystemReadyMessages) {
20077                msg.sendToTarget();
20078            }
20079            mPostSystemReadyMessages = null;
20080        }
20081
20082        // Watch for external volumes that come and go over time
20083        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20084        storage.registerListener(mStorageListener);
20085
20086        mInstallerService.systemReady();
20087        mPackageDexOptimizer.systemReady();
20088
20089        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20090                StorageManagerInternal.class);
20091        StorageManagerInternal.addExternalStoragePolicy(
20092                new StorageManagerInternal.ExternalStorageMountPolicy() {
20093            @Override
20094            public int getMountMode(int uid, String packageName) {
20095                if (Process.isIsolated(uid)) {
20096                    return Zygote.MOUNT_EXTERNAL_NONE;
20097                }
20098                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20099                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20100                }
20101                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20102                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20103                }
20104                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20105                    return Zygote.MOUNT_EXTERNAL_READ;
20106                }
20107                return Zygote.MOUNT_EXTERNAL_WRITE;
20108            }
20109
20110            @Override
20111            public boolean hasExternalStorage(int uid, String packageName) {
20112                return true;
20113            }
20114        });
20115
20116        // Now that we're mostly running, clean up stale users and apps
20117        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20118        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20119
20120        mPermissionManager.systemReady();
20121    }
20122
20123    public void waitForAppDataPrepared() {
20124        if (mPrepareAppDataFuture == null) {
20125            return;
20126        }
20127        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20128        mPrepareAppDataFuture = null;
20129    }
20130
20131    @Override
20132    public boolean isSafeMode() {
20133        // allow instant applications
20134        return mSafeMode;
20135    }
20136
20137    @Override
20138    public boolean hasSystemUidErrors() {
20139        // allow instant applications
20140        return mHasSystemUidErrors;
20141    }
20142
20143    static String arrayToString(int[] array) {
20144        StringBuffer buf = new StringBuffer(128);
20145        buf.append('[');
20146        if (array != null) {
20147            for (int i=0; i<array.length; i++) {
20148                if (i > 0) buf.append(", ");
20149                buf.append(array[i]);
20150            }
20151        }
20152        buf.append(']');
20153        return buf.toString();
20154    }
20155
20156    @Override
20157    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20158            FileDescriptor err, String[] args, ShellCallback callback,
20159            ResultReceiver resultReceiver) {
20160        (new PackageManagerShellCommand(this)).exec(
20161                this, in, out, err, args, callback, resultReceiver);
20162    }
20163
20164    @Override
20165    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20166        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20167
20168        DumpState dumpState = new DumpState();
20169        boolean fullPreferred = false;
20170        boolean checkin = false;
20171
20172        String packageName = null;
20173        ArraySet<String> permissionNames = null;
20174
20175        int opti = 0;
20176        while (opti < args.length) {
20177            String opt = args[opti];
20178            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20179                break;
20180            }
20181            opti++;
20182
20183            if ("-a".equals(opt)) {
20184                // Right now we only know how to print all.
20185            } else if ("-h".equals(opt)) {
20186                pw.println("Package manager dump options:");
20187                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20188                pw.println("    --checkin: dump for a checkin");
20189                pw.println("    -f: print details of intent filters");
20190                pw.println("    -h: print this help");
20191                pw.println("  cmd may be one of:");
20192                pw.println("    l[ibraries]: list known shared libraries");
20193                pw.println("    f[eatures]: list device features");
20194                pw.println("    k[eysets]: print known keysets");
20195                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20196                pw.println("    perm[issions]: dump permissions");
20197                pw.println("    permission [name ...]: dump declaration and use of given permission");
20198                pw.println("    pref[erred]: print preferred package settings");
20199                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20200                pw.println("    prov[iders]: dump content providers");
20201                pw.println("    p[ackages]: dump installed packages");
20202                pw.println("    s[hared-users]: dump shared user IDs");
20203                pw.println("    m[essages]: print collected runtime messages");
20204                pw.println("    v[erifiers]: print package verifier info");
20205                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20206                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20207                pw.println("    version: print database version info");
20208                pw.println("    write: write current settings now");
20209                pw.println("    installs: details about install sessions");
20210                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20211                pw.println("    dexopt: dump dexopt state");
20212                pw.println("    compiler-stats: dump compiler statistics");
20213                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20214                pw.println("    <package.name>: info about given package");
20215                return;
20216            } else if ("--checkin".equals(opt)) {
20217                checkin = true;
20218            } else if ("-f".equals(opt)) {
20219                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20220            } else if ("--proto".equals(opt)) {
20221                dumpProto(fd);
20222                return;
20223            } else {
20224                pw.println("Unknown argument: " + opt + "; use -h for help");
20225            }
20226        }
20227
20228        // Is the caller requesting to dump a particular piece of data?
20229        if (opti < args.length) {
20230            String cmd = args[opti];
20231            opti++;
20232            // Is this a package name?
20233            if ("android".equals(cmd) || cmd.contains(".")) {
20234                packageName = cmd;
20235                // When dumping a single package, we always dump all of its
20236                // filter information since the amount of data will be reasonable.
20237                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20238            } else if ("check-permission".equals(cmd)) {
20239                if (opti >= args.length) {
20240                    pw.println("Error: check-permission missing permission argument");
20241                    return;
20242                }
20243                String perm = args[opti];
20244                opti++;
20245                if (opti >= args.length) {
20246                    pw.println("Error: check-permission missing package argument");
20247                    return;
20248                }
20249
20250                String pkg = args[opti];
20251                opti++;
20252                int user = UserHandle.getUserId(Binder.getCallingUid());
20253                if (opti < args.length) {
20254                    try {
20255                        user = Integer.parseInt(args[opti]);
20256                    } catch (NumberFormatException e) {
20257                        pw.println("Error: check-permission user argument is not a number: "
20258                                + args[opti]);
20259                        return;
20260                    }
20261                }
20262
20263                // Normalize package name to handle renamed packages and static libs
20264                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20265
20266                pw.println(checkPermission(perm, pkg, user));
20267                return;
20268            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20269                dumpState.setDump(DumpState.DUMP_LIBS);
20270            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20271                dumpState.setDump(DumpState.DUMP_FEATURES);
20272            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20273                if (opti >= args.length) {
20274                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20275                            | DumpState.DUMP_SERVICE_RESOLVERS
20276                            | DumpState.DUMP_RECEIVER_RESOLVERS
20277                            | DumpState.DUMP_CONTENT_RESOLVERS);
20278                } else {
20279                    while (opti < args.length) {
20280                        String name = args[opti];
20281                        if ("a".equals(name) || "activity".equals(name)) {
20282                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20283                        } else if ("s".equals(name) || "service".equals(name)) {
20284                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20285                        } else if ("r".equals(name) || "receiver".equals(name)) {
20286                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20287                        } else if ("c".equals(name) || "content".equals(name)) {
20288                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20289                        } else {
20290                            pw.println("Error: unknown resolver table type: " + name);
20291                            return;
20292                        }
20293                        opti++;
20294                    }
20295                }
20296            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20297                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20298            } else if ("permission".equals(cmd)) {
20299                if (opti >= args.length) {
20300                    pw.println("Error: permission requires permission name");
20301                    return;
20302                }
20303                permissionNames = new ArraySet<>();
20304                while (opti < args.length) {
20305                    permissionNames.add(args[opti]);
20306                    opti++;
20307                }
20308                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20309                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20310            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20311                dumpState.setDump(DumpState.DUMP_PREFERRED);
20312            } else if ("preferred-xml".equals(cmd)) {
20313                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20314                if (opti < args.length && "--full".equals(args[opti])) {
20315                    fullPreferred = true;
20316                    opti++;
20317                }
20318            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20319                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20320            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20321                dumpState.setDump(DumpState.DUMP_PACKAGES);
20322            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20323                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20324            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20325                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20326            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20327                dumpState.setDump(DumpState.DUMP_MESSAGES);
20328            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20329                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20330            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20331                    || "intent-filter-verifiers".equals(cmd)) {
20332                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20333            } else if ("version".equals(cmd)) {
20334                dumpState.setDump(DumpState.DUMP_VERSION);
20335            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20336                dumpState.setDump(DumpState.DUMP_KEYSETS);
20337            } else if ("installs".equals(cmd)) {
20338                dumpState.setDump(DumpState.DUMP_INSTALLS);
20339            } else if ("frozen".equals(cmd)) {
20340                dumpState.setDump(DumpState.DUMP_FROZEN);
20341            } else if ("volumes".equals(cmd)) {
20342                dumpState.setDump(DumpState.DUMP_VOLUMES);
20343            } else if ("dexopt".equals(cmd)) {
20344                dumpState.setDump(DumpState.DUMP_DEXOPT);
20345            } else if ("compiler-stats".equals(cmd)) {
20346                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20347            } else if ("changes".equals(cmd)) {
20348                dumpState.setDump(DumpState.DUMP_CHANGES);
20349            } else if ("write".equals(cmd)) {
20350                synchronized (mPackages) {
20351                    mSettings.writeLPr();
20352                    pw.println("Settings written.");
20353                    return;
20354                }
20355            }
20356        }
20357
20358        if (checkin) {
20359            pw.println("vers,1");
20360        }
20361
20362        // reader
20363        synchronized (mPackages) {
20364            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20365                if (!checkin) {
20366                    if (dumpState.onTitlePrinted())
20367                        pw.println();
20368                    pw.println("Database versions:");
20369                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20370                }
20371            }
20372
20373            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20374                if (!checkin) {
20375                    if (dumpState.onTitlePrinted())
20376                        pw.println();
20377                    pw.println("Verifiers:");
20378                    pw.print("  Required: ");
20379                    pw.print(mRequiredVerifierPackage);
20380                    pw.print(" (uid=");
20381                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20382                            UserHandle.USER_SYSTEM));
20383                    pw.println(")");
20384                } else if (mRequiredVerifierPackage != null) {
20385                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20386                    pw.print(",");
20387                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20388                            UserHandle.USER_SYSTEM));
20389                }
20390            }
20391
20392            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20393                    packageName == null) {
20394                if (mIntentFilterVerifierComponent != null) {
20395                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20396                    if (!checkin) {
20397                        if (dumpState.onTitlePrinted())
20398                            pw.println();
20399                        pw.println("Intent Filter Verifier:");
20400                        pw.print("  Using: ");
20401                        pw.print(verifierPackageName);
20402                        pw.print(" (uid=");
20403                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20404                                UserHandle.USER_SYSTEM));
20405                        pw.println(")");
20406                    } else if (verifierPackageName != null) {
20407                        pw.print("ifv,"); pw.print(verifierPackageName);
20408                        pw.print(",");
20409                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20410                                UserHandle.USER_SYSTEM));
20411                    }
20412                } else {
20413                    pw.println();
20414                    pw.println("No Intent Filter Verifier available!");
20415                }
20416            }
20417
20418            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20419                boolean printedHeader = false;
20420                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20421                while (it.hasNext()) {
20422                    String libName = it.next();
20423                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20424                    if (versionedLib == null) {
20425                        continue;
20426                    }
20427                    final int versionCount = versionedLib.size();
20428                    for (int i = 0; i < versionCount; i++) {
20429                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20430                        if (!checkin) {
20431                            if (!printedHeader) {
20432                                if (dumpState.onTitlePrinted())
20433                                    pw.println();
20434                                pw.println("Libraries:");
20435                                printedHeader = true;
20436                            }
20437                            pw.print("  ");
20438                        } else {
20439                            pw.print("lib,");
20440                        }
20441                        pw.print(libEntry.info.getName());
20442                        if (libEntry.info.isStatic()) {
20443                            pw.print(" version=" + libEntry.info.getVersion());
20444                        }
20445                        if (!checkin) {
20446                            pw.print(" -> ");
20447                        }
20448                        if (libEntry.path != null) {
20449                            pw.print(" (jar) ");
20450                            pw.print(libEntry.path);
20451                        } else {
20452                            pw.print(" (apk) ");
20453                            pw.print(libEntry.apk);
20454                        }
20455                        pw.println();
20456                    }
20457                }
20458            }
20459
20460            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20461                if (dumpState.onTitlePrinted())
20462                    pw.println();
20463                if (!checkin) {
20464                    pw.println("Features:");
20465                }
20466
20467                synchronized (mAvailableFeatures) {
20468                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20469                        if (checkin) {
20470                            pw.print("feat,");
20471                            pw.print(feat.name);
20472                            pw.print(",");
20473                            pw.println(feat.version);
20474                        } else {
20475                            pw.print("  ");
20476                            pw.print(feat.name);
20477                            if (feat.version > 0) {
20478                                pw.print(" version=");
20479                                pw.print(feat.version);
20480                            }
20481                            pw.println();
20482                        }
20483                    }
20484                }
20485            }
20486
20487            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20488                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20489                        : "Activity Resolver Table:", "  ", packageName,
20490                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20491                    dumpState.setTitlePrinted(true);
20492                }
20493            }
20494            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20495                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20496                        : "Receiver Resolver Table:", "  ", packageName,
20497                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20498                    dumpState.setTitlePrinted(true);
20499                }
20500            }
20501            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20502                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20503                        : "Service Resolver Table:", "  ", packageName,
20504                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20505                    dumpState.setTitlePrinted(true);
20506                }
20507            }
20508            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20509                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20510                        : "Provider Resolver Table:", "  ", packageName,
20511                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20512                    dumpState.setTitlePrinted(true);
20513                }
20514            }
20515
20516            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20517                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20518                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20519                    int user = mSettings.mPreferredActivities.keyAt(i);
20520                    if (pir.dump(pw,
20521                            dumpState.getTitlePrinted()
20522                                ? "\nPreferred Activities User " + user + ":"
20523                                : "Preferred Activities User " + user + ":", "  ",
20524                            packageName, true, false)) {
20525                        dumpState.setTitlePrinted(true);
20526                    }
20527                }
20528            }
20529
20530            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20531                pw.flush();
20532                FileOutputStream fout = new FileOutputStream(fd);
20533                BufferedOutputStream str = new BufferedOutputStream(fout);
20534                XmlSerializer serializer = new FastXmlSerializer();
20535                try {
20536                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20537                    serializer.startDocument(null, true);
20538                    serializer.setFeature(
20539                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20540                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20541                    serializer.endDocument();
20542                    serializer.flush();
20543                } catch (IllegalArgumentException e) {
20544                    pw.println("Failed writing: " + e);
20545                } catch (IllegalStateException e) {
20546                    pw.println("Failed writing: " + e);
20547                } catch (IOException e) {
20548                    pw.println("Failed writing: " + e);
20549                }
20550            }
20551
20552            if (!checkin
20553                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20554                    && packageName == null) {
20555                pw.println();
20556                int count = mSettings.mPackages.size();
20557                if (count == 0) {
20558                    pw.println("No applications!");
20559                    pw.println();
20560                } else {
20561                    final String prefix = "  ";
20562                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20563                    if (allPackageSettings.size() == 0) {
20564                        pw.println("No domain preferred apps!");
20565                        pw.println();
20566                    } else {
20567                        pw.println("App verification status:");
20568                        pw.println();
20569                        count = 0;
20570                        for (PackageSetting ps : allPackageSettings) {
20571                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20572                            if (ivi == null || ivi.getPackageName() == null) continue;
20573                            pw.println(prefix + "Package: " + ivi.getPackageName());
20574                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20575                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20576                            pw.println();
20577                            count++;
20578                        }
20579                        if (count == 0) {
20580                            pw.println(prefix + "No app verification established.");
20581                            pw.println();
20582                        }
20583                        for (int userId : sUserManager.getUserIds()) {
20584                            pw.println("App linkages for user " + userId + ":");
20585                            pw.println();
20586                            count = 0;
20587                            for (PackageSetting ps : allPackageSettings) {
20588                                final long status = ps.getDomainVerificationStatusForUser(userId);
20589                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20590                                        && !DEBUG_DOMAIN_VERIFICATION) {
20591                                    continue;
20592                                }
20593                                pw.println(prefix + "Package: " + ps.name);
20594                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20595                                String statusStr = IntentFilterVerificationInfo.
20596                                        getStatusStringFromValue(status);
20597                                pw.println(prefix + "Status:  " + statusStr);
20598                                pw.println();
20599                                count++;
20600                            }
20601                            if (count == 0) {
20602                                pw.println(prefix + "No configured app linkages.");
20603                                pw.println();
20604                            }
20605                        }
20606                    }
20607                }
20608            }
20609
20610            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20611                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20612            }
20613
20614            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20615                boolean printedSomething = false;
20616                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20617                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20618                        continue;
20619                    }
20620                    if (!printedSomething) {
20621                        if (dumpState.onTitlePrinted())
20622                            pw.println();
20623                        pw.println("Registered ContentProviders:");
20624                        printedSomething = true;
20625                    }
20626                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20627                    pw.print("    "); pw.println(p.toString());
20628                }
20629                printedSomething = false;
20630                for (Map.Entry<String, PackageParser.Provider> entry :
20631                        mProvidersByAuthority.entrySet()) {
20632                    PackageParser.Provider p = entry.getValue();
20633                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20634                        continue;
20635                    }
20636                    if (!printedSomething) {
20637                        if (dumpState.onTitlePrinted())
20638                            pw.println();
20639                        pw.println("ContentProvider Authorities:");
20640                        printedSomething = true;
20641                    }
20642                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20643                    pw.print("    "); pw.println(p.toString());
20644                    if (p.info != null && p.info.applicationInfo != null) {
20645                        final String appInfo = p.info.applicationInfo.toString();
20646                        pw.print("      applicationInfo="); pw.println(appInfo);
20647                    }
20648                }
20649            }
20650
20651            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20652                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20653            }
20654
20655            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20656                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20657            }
20658
20659            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20660                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20661            }
20662
20663            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
20664                if (dumpState.onTitlePrinted()) pw.println();
20665                pw.println("Package Changes:");
20666                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
20667                final int K = mChangedPackages.size();
20668                for (int i = 0; i < K; i++) {
20669                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
20670                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
20671                    final int N = changes.size();
20672                    if (N == 0) {
20673                        pw.print("    "); pw.println("No packages changed");
20674                    } else {
20675                        for (int j = 0; j < N; j++) {
20676                            final String pkgName = changes.valueAt(j);
20677                            final int sequenceNumber = changes.keyAt(j);
20678                            pw.print("    ");
20679                            pw.print("seq=");
20680                            pw.print(sequenceNumber);
20681                            pw.print(", package=");
20682                            pw.println(pkgName);
20683                        }
20684                    }
20685                }
20686            }
20687
20688            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20689                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20690            }
20691
20692            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20693                // XXX should handle packageName != null by dumping only install data that
20694                // the given package is involved with.
20695                if (dumpState.onTitlePrinted()) pw.println();
20696
20697                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20698                ipw.println();
20699                ipw.println("Frozen packages:");
20700                ipw.increaseIndent();
20701                if (mFrozenPackages.size() == 0) {
20702                    ipw.println("(none)");
20703                } else {
20704                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20705                        ipw.println(mFrozenPackages.valueAt(i));
20706                    }
20707                }
20708                ipw.decreaseIndent();
20709            }
20710
20711            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
20712                if (dumpState.onTitlePrinted()) pw.println();
20713
20714                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20715                ipw.println();
20716                ipw.println("Loaded volumes:");
20717                ipw.increaseIndent();
20718                if (mLoadedVolumes.size() == 0) {
20719                    ipw.println("(none)");
20720                } else {
20721                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
20722                        ipw.println(mLoadedVolumes.valueAt(i));
20723                    }
20724                }
20725                ipw.decreaseIndent();
20726            }
20727
20728            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20729                if (dumpState.onTitlePrinted()) pw.println();
20730                dumpDexoptStateLPr(pw, packageName);
20731            }
20732
20733            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20734                if (dumpState.onTitlePrinted()) pw.println();
20735                dumpCompilerStatsLPr(pw, packageName);
20736            }
20737
20738            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20739                if (dumpState.onTitlePrinted()) pw.println();
20740                mSettings.dumpReadMessagesLPr(pw, dumpState);
20741
20742                pw.println();
20743                pw.println("Package warning messages:");
20744                dumpCriticalInfo(pw, null);
20745            }
20746
20747            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20748                dumpCriticalInfo(pw, "msg,");
20749            }
20750        }
20751
20752        // PackageInstaller should be called outside of mPackages lock
20753        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20754            // XXX should handle packageName != null by dumping only install data that
20755            // the given package is involved with.
20756            if (dumpState.onTitlePrinted()) pw.println();
20757            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20758        }
20759    }
20760
20761    private void dumpProto(FileDescriptor fd) {
20762        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20763
20764        synchronized (mPackages) {
20765            final long requiredVerifierPackageToken =
20766                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20767            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20768            proto.write(
20769                    PackageServiceDumpProto.PackageShortProto.UID,
20770                    getPackageUid(
20771                            mRequiredVerifierPackage,
20772                            MATCH_DEBUG_TRIAGED_MISSING,
20773                            UserHandle.USER_SYSTEM));
20774            proto.end(requiredVerifierPackageToken);
20775
20776            if (mIntentFilterVerifierComponent != null) {
20777                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20778                final long verifierPackageToken =
20779                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20780                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20781                proto.write(
20782                        PackageServiceDumpProto.PackageShortProto.UID,
20783                        getPackageUid(
20784                                verifierPackageName,
20785                                MATCH_DEBUG_TRIAGED_MISSING,
20786                                UserHandle.USER_SYSTEM));
20787                proto.end(verifierPackageToken);
20788            }
20789
20790            dumpSharedLibrariesProto(proto);
20791            dumpFeaturesProto(proto);
20792            mSettings.dumpPackagesProto(proto);
20793            mSettings.dumpSharedUsersProto(proto);
20794            dumpCriticalInfo(proto);
20795        }
20796        proto.flush();
20797    }
20798
20799    private void dumpFeaturesProto(ProtoOutputStream proto) {
20800        synchronized (mAvailableFeatures) {
20801            final int count = mAvailableFeatures.size();
20802            for (int i = 0; i < count; i++) {
20803                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
20804            }
20805        }
20806    }
20807
20808    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20809        final int count = mSharedLibraries.size();
20810        for (int i = 0; i < count; i++) {
20811            final String libName = mSharedLibraries.keyAt(i);
20812            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20813            if (versionedLib == null) {
20814                continue;
20815            }
20816            final int versionCount = versionedLib.size();
20817            for (int j = 0; j < versionCount; j++) {
20818                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20819                final long sharedLibraryToken =
20820                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20821                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20822                final boolean isJar = (libEntry.path != null);
20823                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20824                if (isJar) {
20825                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20826                } else {
20827                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20828                }
20829                proto.end(sharedLibraryToken);
20830            }
20831        }
20832    }
20833
20834    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20835        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20836        ipw.println();
20837        ipw.println("Dexopt state:");
20838        ipw.increaseIndent();
20839        Collection<PackageParser.Package> packages = null;
20840        if (packageName != null) {
20841            PackageParser.Package targetPackage = mPackages.get(packageName);
20842            if (targetPackage != null) {
20843                packages = Collections.singletonList(targetPackage);
20844            } else {
20845                ipw.println("Unable to find package: " + packageName);
20846                return;
20847            }
20848        } else {
20849            packages = mPackages.values();
20850        }
20851
20852        for (PackageParser.Package pkg : packages) {
20853            ipw.println("[" + pkg.packageName + "]");
20854            ipw.increaseIndent();
20855            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
20856                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
20857            ipw.decreaseIndent();
20858        }
20859    }
20860
20861    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20862        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
20863        ipw.println();
20864        ipw.println("Compiler stats:");
20865        ipw.increaseIndent();
20866        Collection<PackageParser.Package> packages = null;
20867        if (packageName != null) {
20868            PackageParser.Package targetPackage = mPackages.get(packageName);
20869            if (targetPackage != null) {
20870                packages = Collections.singletonList(targetPackage);
20871            } else {
20872                ipw.println("Unable to find package: " + packageName);
20873                return;
20874            }
20875        } else {
20876            packages = mPackages.values();
20877        }
20878
20879        for (PackageParser.Package pkg : packages) {
20880            ipw.println("[" + pkg.packageName + "]");
20881            ipw.increaseIndent();
20882
20883            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20884            if (stats == null) {
20885                ipw.println("(No recorded stats)");
20886            } else {
20887                stats.dump(ipw);
20888            }
20889            ipw.decreaseIndent();
20890        }
20891    }
20892
20893    private String dumpDomainString(String packageName) {
20894        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20895                .getList();
20896        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20897
20898        ArraySet<String> result = new ArraySet<>();
20899        if (iviList.size() > 0) {
20900            for (IntentFilterVerificationInfo ivi : iviList) {
20901                for (String host : ivi.getDomains()) {
20902                    result.add(host);
20903                }
20904            }
20905        }
20906        if (filters != null && filters.size() > 0) {
20907            for (IntentFilter filter : filters) {
20908                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20909                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20910                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20911                    result.addAll(filter.getHostsList());
20912                }
20913            }
20914        }
20915
20916        StringBuilder sb = new StringBuilder(result.size() * 16);
20917        for (String domain : result) {
20918            if (sb.length() > 0) sb.append(" ");
20919            sb.append(domain);
20920        }
20921        return sb.toString();
20922    }
20923
20924    // ------- apps on sdcard specific code -------
20925    static final boolean DEBUG_SD_INSTALL = false;
20926
20927    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20928
20929    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20930
20931    private boolean mMediaMounted = false;
20932
20933    static String getEncryptKey() {
20934        try {
20935            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20936                    SD_ENCRYPTION_KEYSTORE_NAME);
20937            if (sdEncKey == null) {
20938                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20939                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20940                if (sdEncKey == null) {
20941                    Slog.e(TAG, "Failed to create encryption keys");
20942                    return null;
20943                }
20944            }
20945            return sdEncKey;
20946        } catch (NoSuchAlgorithmException nsae) {
20947            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20948            return null;
20949        } catch (IOException ioe) {
20950            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20951            return null;
20952        }
20953    }
20954
20955    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20956            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20957        final int size = infos.size();
20958        final String[] packageNames = new String[size];
20959        final int[] packageUids = new int[size];
20960        for (int i = 0; i < size; i++) {
20961            final ApplicationInfo info = infos.get(i);
20962            packageNames[i] = info.packageName;
20963            packageUids[i] = info.uid;
20964        }
20965        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20966                finishedReceiver);
20967    }
20968
20969    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20970            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20971        sendResourcesChangedBroadcast(mediaStatus, replacing,
20972                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20973    }
20974
20975    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20976            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20977        int size = pkgList.length;
20978        if (size > 0) {
20979            // Send broadcasts here
20980            Bundle extras = new Bundle();
20981            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20982            if (uidArr != null) {
20983                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20984            }
20985            if (replacing) {
20986                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20987            }
20988            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20989                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20990            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20991        }
20992    }
20993
20994    private void loadPrivatePackages(final VolumeInfo vol) {
20995        mHandler.post(new Runnable() {
20996            @Override
20997            public void run() {
20998                loadPrivatePackagesInner(vol);
20999            }
21000        });
21001    }
21002
21003    private void loadPrivatePackagesInner(VolumeInfo vol) {
21004        final String volumeUuid = vol.fsUuid;
21005        if (TextUtils.isEmpty(volumeUuid)) {
21006            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21007            return;
21008        }
21009
21010        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21011        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21012        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21013
21014        final VersionInfo ver;
21015        final List<PackageSetting> packages;
21016        synchronized (mPackages) {
21017            ver = mSettings.findOrCreateVersion(volumeUuid);
21018            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21019        }
21020
21021        for (PackageSetting ps : packages) {
21022            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21023            synchronized (mInstallLock) {
21024                final PackageParser.Package pkg;
21025                try {
21026                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21027                    loaded.add(pkg.applicationInfo);
21028
21029                } catch (PackageManagerException e) {
21030                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21031                }
21032
21033                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21034                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21035                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21036                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21037                }
21038            }
21039        }
21040
21041        // Reconcile app data for all started/unlocked users
21042        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21043        final UserManager um = mContext.getSystemService(UserManager.class);
21044        UserManagerInternal umInternal = getUserManagerInternal();
21045        for (UserInfo user : um.getUsers()) {
21046            final int flags;
21047            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21048                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21049            } else if (umInternal.isUserRunning(user.id)) {
21050                flags = StorageManager.FLAG_STORAGE_DE;
21051            } else {
21052                continue;
21053            }
21054
21055            try {
21056                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21057                synchronized (mInstallLock) {
21058                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21059                }
21060            } catch (IllegalStateException e) {
21061                // Device was probably ejected, and we'll process that event momentarily
21062                Slog.w(TAG, "Failed to prepare storage: " + e);
21063            }
21064        }
21065
21066        synchronized (mPackages) {
21067            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21068            if (sdkUpdated) {
21069                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21070                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21071            }
21072            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21073                    mPermissionCallback);
21074
21075            // Yay, everything is now upgraded
21076            ver.forceCurrent();
21077
21078            mSettings.writeLPr();
21079        }
21080
21081        for (PackageFreezer freezer : freezers) {
21082            freezer.close();
21083        }
21084
21085        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21086        sendResourcesChangedBroadcast(true, false, loaded, null);
21087        mLoadedVolumes.add(vol.getId());
21088    }
21089
21090    private void unloadPrivatePackages(final VolumeInfo vol) {
21091        mHandler.post(new Runnable() {
21092            @Override
21093            public void run() {
21094                unloadPrivatePackagesInner(vol);
21095            }
21096        });
21097    }
21098
21099    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21100        final String volumeUuid = vol.fsUuid;
21101        if (TextUtils.isEmpty(volumeUuid)) {
21102            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21103            return;
21104        }
21105
21106        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21107        synchronized (mInstallLock) {
21108        synchronized (mPackages) {
21109            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21110            for (PackageSetting ps : packages) {
21111                if (ps.pkg == null) continue;
21112
21113                final ApplicationInfo info = ps.pkg.applicationInfo;
21114                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21115                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21116
21117                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21118                        "unloadPrivatePackagesInner")) {
21119                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21120                            false, null)) {
21121                        unloaded.add(info);
21122                    } else {
21123                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21124                    }
21125                }
21126
21127                // Try very hard to release any references to this package
21128                // so we don't risk the system server being killed due to
21129                // open FDs
21130                AttributeCache.instance().removePackage(ps.name);
21131            }
21132
21133            mSettings.writeLPr();
21134        }
21135        }
21136
21137        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21138        sendResourcesChangedBroadcast(false, false, unloaded, null);
21139        mLoadedVolumes.remove(vol.getId());
21140
21141        // Try very hard to release any references to this path so we don't risk
21142        // the system server being killed due to open FDs
21143        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21144
21145        for (int i = 0; i < 3; i++) {
21146            System.gc();
21147            System.runFinalization();
21148        }
21149    }
21150
21151    private void assertPackageKnown(String volumeUuid, String packageName)
21152            throws PackageManagerException {
21153        synchronized (mPackages) {
21154            // Normalize package name to handle renamed packages
21155            packageName = normalizePackageNameLPr(packageName);
21156
21157            final PackageSetting ps = mSettings.mPackages.get(packageName);
21158            if (ps == null) {
21159                throw new PackageManagerException("Package " + packageName + " is unknown");
21160            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21161                throw new PackageManagerException(
21162                        "Package " + packageName + " found on unknown volume " + volumeUuid
21163                                + "; expected volume " + ps.volumeUuid);
21164            }
21165        }
21166    }
21167
21168    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21169            throws PackageManagerException {
21170        synchronized (mPackages) {
21171            // Normalize package name to handle renamed packages
21172            packageName = normalizePackageNameLPr(packageName);
21173
21174            final PackageSetting ps = mSettings.mPackages.get(packageName);
21175            if (ps == null) {
21176                throw new PackageManagerException("Package " + packageName + " is unknown");
21177            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21178                throw new PackageManagerException(
21179                        "Package " + packageName + " found on unknown volume " + volumeUuid
21180                                + "; expected volume " + ps.volumeUuid);
21181            } else if (!ps.getInstalled(userId)) {
21182                throw new PackageManagerException(
21183                        "Package " + packageName + " not installed for user " + userId);
21184            }
21185        }
21186    }
21187
21188    private List<String> collectAbsoluteCodePaths() {
21189        synchronized (mPackages) {
21190            List<String> codePaths = new ArrayList<>();
21191            final int packageCount = mSettings.mPackages.size();
21192            for (int i = 0; i < packageCount; i++) {
21193                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21194                codePaths.add(ps.codePath.getAbsolutePath());
21195            }
21196            return codePaths;
21197        }
21198    }
21199
21200    /**
21201     * Examine all apps present on given mounted volume, and destroy apps that
21202     * aren't expected, either due to uninstallation or reinstallation on
21203     * another volume.
21204     */
21205    private void reconcileApps(String volumeUuid) {
21206        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21207        List<File> filesToDelete = null;
21208
21209        final File[] files = FileUtils.listFilesOrEmpty(
21210                Environment.getDataAppDirectory(volumeUuid));
21211        for (File file : files) {
21212            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21213                    && !PackageInstallerService.isStageName(file.getName());
21214            if (!isPackage) {
21215                // Ignore entries which are not packages
21216                continue;
21217            }
21218
21219            String absolutePath = file.getAbsolutePath();
21220
21221            boolean pathValid = false;
21222            final int absoluteCodePathCount = absoluteCodePaths.size();
21223            for (int i = 0; i < absoluteCodePathCount; i++) {
21224                String absoluteCodePath = absoluteCodePaths.get(i);
21225                if (absolutePath.startsWith(absoluteCodePath)) {
21226                    pathValid = true;
21227                    break;
21228                }
21229            }
21230
21231            if (!pathValid) {
21232                if (filesToDelete == null) {
21233                    filesToDelete = new ArrayList<>();
21234                }
21235                filesToDelete.add(file);
21236            }
21237        }
21238
21239        if (filesToDelete != null) {
21240            final int fileToDeleteCount = filesToDelete.size();
21241            for (int i = 0; i < fileToDeleteCount; i++) {
21242                File fileToDelete = filesToDelete.get(i);
21243                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21244                synchronized (mInstallLock) {
21245                    removeCodePathLI(fileToDelete);
21246                }
21247            }
21248        }
21249    }
21250
21251    /**
21252     * Reconcile all app data for the given user.
21253     * <p>
21254     * Verifies that directories exist and that ownership and labeling is
21255     * correct for all installed apps on all mounted volumes.
21256     */
21257    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21258        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21259        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21260            final String volumeUuid = vol.getFsUuid();
21261            synchronized (mInstallLock) {
21262                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21263            }
21264        }
21265    }
21266
21267    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21268            boolean migrateAppData) {
21269        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21270    }
21271
21272    /**
21273     * Reconcile all app data on given mounted volume.
21274     * <p>
21275     * Destroys app data that isn't expected, either due to uninstallation or
21276     * reinstallation on another volume.
21277     * <p>
21278     * Verifies that directories exist and that ownership and labeling is
21279     * correct for all installed apps.
21280     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21281     */
21282    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21283            boolean migrateAppData, boolean onlyCoreApps) {
21284        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21285                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21286        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21287
21288        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21289        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21290
21291        // First look for stale data that doesn't belong, and check if things
21292        // have changed since we did our last restorecon
21293        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21294            if (StorageManager.isFileEncryptedNativeOrEmulated()
21295                    && !StorageManager.isUserKeyUnlocked(userId)) {
21296                throw new RuntimeException(
21297                        "Yikes, someone asked us to reconcile CE storage while " + userId
21298                                + " was still locked; this would have caused massive data loss!");
21299            }
21300
21301            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21302            for (File file : files) {
21303                final String packageName = file.getName();
21304                try {
21305                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21306                } catch (PackageManagerException e) {
21307                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21308                    try {
21309                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21310                                StorageManager.FLAG_STORAGE_CE, 0);
21311                    } catch (InstallerException e2) {
21312                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21313                    }
21314                }
21315            }
21316        }
21317        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21318            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21319            for (File file : files) {
21320                final String packageName = file.getName();
21321                try {
21322                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21323                } catch (PackageManagerException e) {
21324                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21325                    try {
21326                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21327                                StorageManager.FLAG_STORAGE_DE, 0);
21328                    } catch (InstallerException e2) {
21329                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21330                    }
21331                }
21332            }
21333        }
21334
21335        // Ensure that data directories are ready to roll for all packages
21336        // installed for this volume and user
21337        final List<PackageSetting> packages;
21338        synchronized (mPackages) {
21339            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21340        }
21341        int preparedCount = 0;
21342        for (PackageSetting ps : packages) {
21343            final String packageName = ps.name;
21344            if (ps.pkg == null) {
21345                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21346                // TODO: might be due to legacy ASEC apps; we should circle back
21347                // and reconcile again once they're scanned
21348                continue;
21349            }
21350            // Skip non-core apps if requested
21351            if (onlyCoreApps && !ps.pkg.coreApp) {
21352                result.add(packageName);
21353                continue;
21354            }
21355
21356            if (ps.getInstalled(userId)) {
21357                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21358                preparedCount++;
21359            }
21360        }
21361
21362        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21363        return result;
21364    }
21365
21366    /**
21367     * Prepare app data for the given app just after it was installed or
21368     * upgraded. This method carefully only touches users that it's installed
21369     * for, and it forces a restorecon to handle any seinfo changes.
21370     * <p>
21371     * Verifies that directories exist and that ownership and labeling is
21372     * correct for all installed apps. If there is an ownership mismatch, it
21373     * will try recovering system apps by wiping data; third-party app data is
21374     * left intact.
21375     * <p>
21376     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21377     */
21378    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21379        final PackageSetting ps;
21380        synchronized (mPackages) {
21381            ps = mSettings.mPackages.get(pkg.packageName);
21382            mSettings.writeKernelMappingLPr(ps);
21383        }
21384
21385        final UserManager um = mContext.getSystemService(UserManager.class);
21386        UserManagerInternal umInternal = getUserManagerInternal();
21387        for (UserInfo user : um.getUsers()) {
21388            final int flags;
21389            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21390                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21391            } else if (umInternal.isUserRunning(user.id)) {
21392                flags = StorageManager.FLAG_STORAGE_DE;
21393            } else {
21394                continue;
21395            }
21396
21397            if (ps.getInstalled(user.id)) {
21398                // TODO: when user data is locked, mark that we're still dirty
21399                prepareAppDataLIF(pkg, user.id, flags);
21400            }
21401        }
21402    }
21403
21404    /**
21405     * Prepare app data for the given app.
21406     * <p>
21407     * Verifies that directories exist and that ownership and labeling is
21408     * correct for all installed apps. If there is an ownership mismatch, this
21409     * will try recovering system apps by wiping data; third-party app data is
21410     * left intact.
21411     */
21412    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21413        if (pkg == null) {
21414            Slog.wtf(TAG, "Package was null!", new Throwable());
21415            return;
21416        }
21417        prepareAppDataLeafLIF(pkg, userId, flags);
21418        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21419        for (int i = 0; i < childCount; i++) {
21420            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21421        }
21422    }
21423
21424    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21425            boolean maybeMigrateAppData) {
21426        prepareAppDataLIF(pkg, userId, flags);
21427
21428        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21429            // We may have just shuffled around app data directories, so
21430            // prepare them one more time
21431            prepareAppDataLIF(pkg, userId, flags);
21432        }
21433    }
21434
21435    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21436        if (DEBUG_APP_DATA) {
21437            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21438                    + Integer.toHexString(flags));
21439        }
21440
21441        final String volumeUuid = pkg.volumeUuid;
21442        final String packageName = pkg.packageName;
21443        final ApplicationInfo app = pkg.applicationInfo;
21444        final int appId = UserHandle.getAppId(app.uid);
21445
21446        Preconditions.checkNotNull(app.seInfo);
21447
21448        long ceDataInode = -1;
21449        try {
21450            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21451                    appId, app.seInfo, app.targetSdkVersion);
21452        } catch (InstallerException e) {
21453            if (app.isSystemApp()) {
21454                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21455                        + ", but trying to recover: " + e);
21456                destroyAppDataLeafLIF(pkg, userId, flags);
21457                try {
21458                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21459                            appId, app.seInfo, app.targetSdkVersion);
21460                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21461                } catch (InstallerException e2) {
21462                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21463                }
21464            } else {
21465                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21466            }
21467        }
21468
21469        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21470            // TODO: mark this structure as dirty so we persist it!
21471            synchronized (mPackages) {
21472                final PackageSetting ps = mSettings.mPackages.get(packageName);
21473                if (ps != null) {
21474                    ps.setCeDataInode(ceDataInode, userId);
21475                }
21476            }
21477        }
21478
21479        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21480    }
21481
21482    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21483        if (pkg == null) {
21484            Slog.wtf(TAG, "Package was null!", new Throwable());
21485            return;
21486        }
21487        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21488        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21489        for (int i = 0; i < childCount; i++) {
21490            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21491        }
21492    }
21493
21494    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21495        final String volumeUuid = pkg.volumeUuid;
21496        final String packageName = pkg.packageName;
21497        final ApplicationInfo app = pkg.applicationInfo;
21498
21499        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21500            // Create a native library symlink only if we have native libraries
21501            // and if the native libraries are 32 bit libraries. We do not provide
21502            // this symlink for 64 bit libraries.
21503            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21504                final String nativeLibPath = app.nativeLibraryDir;
21505                try {
21506                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21507                            nativeLibPath, userId);
21508                } catch (InstallerException e) {
21509                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21510                }
21511            }
21512        }
21513    }
21514
21515    /**
21516     * For system apps on non-FBE devices, this method migrates any existing
21517     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21518     * requested by the app.
21519     */
21520    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21521        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
21522                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21523            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21524                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21525            try {
21526                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21527                        storageTarget);
21528            } catch (InstallerException e) {
21529                logCriticalInfo(Log.WARN,
21530                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21531            }
21532            return true;
21533        } else {
21534            return false;
21535        }
21536    }
21537
21538    public PackageFreezer freezePackage(String packageName, String killReason) {
21539        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21540    }
21541
21542    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21543        return new PackageFreezer(packageName, userId, killReason);
21544    }
21545
21546    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21547            String killReason) {
21548        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21549    }
21550
21551    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21552            String killReason) {
21553        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21554            return new PackageFreezer();
21555        } else {
21556            return freezePackage(packageName, userId, killReason);
21557        }
21558    }
21559
21560    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21561            String killReason) {
21562        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21563    }
21564
21565    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21566            String killReason) {
21567        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21568            return new PackageFreezer();
21569        } else {
21570            return freezePackage(packageName, userId, killReason);
21571        }
21572    }
21573
21574    /**
21575     * Class that freezes and kills the given package upon creation, and
21576     * unfreezes it upon closing. This is typically used when doing surgery on
21577     * app code/data to prevent the app from running while you're working.
21578     */
21579    private class PackageFreezer implements AutoCloseable {
21580        private final String mPackageName;
21581        private final PackageFreezer[] mChildren;
21582
21583        private final boolean mWeFroze;
21584
21585        private final AtomicBoolean mClosed = new AtomicBoolean();
21586        private final CloseGuard mCloseGuard = CloseGuard.get();
21587
21588        /**
21589         * Create and return a stub freezer that doesn't actually do anything,
21590         * typically used when someone requested
21591         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21592         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21593         */
21594        public PackageFreezer() {
21595            mPackageName = null;
21596            mChildren = null;
21597            mWeFroze = false;
21598            mCloseGuard.open("close");
21599        }
21600
21601        public PackageFreezer(String packageName, int userId, String killReason) {
21602            synchronized (mPackages) {
21603                mPackageName = packageName;
21604                mWeFroze = mFrozenPackages.add(mPackageName);
21605
21606                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21607                if (ps != null) {
21608                    killApplication(ps.name, ps.appId, userId, killReason);
21609                }
21610
21611                final PackageParser.Package p = mPackages.get(packageName);
21612                if (p != null && p.childPackages != null) {
21613                    final int N = p.childPackages.size();
21614                    mChildren = new PackageFreezer[N];
21615                    for (int i = 0; i < N; i++) {
21616                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21617                                userId, killReason);
21618                    }
21619                } else {
21620                    mChildren = null;
21621                }
21622            }
21623            mCloseGuard.open("close");
21624        }
21625
21626        @Override
21627        protected void finalize() throws Throwable {
21628            try {
21629                if (mCloseGuard != null) {
21630                    mCloseGuard.warnIfOpen();
21631                }
21632
21633                close();
21634            } finally {
21635                super.finalize();
21636            }
21637        }
21638
21639        @Override
21640        public void close() {
21641            mCloseGuard.close();
21642            if (mClosed.compareAndSet(false, true)) {
21643                synchronized (mPackages) {
21644                    if (mWeFroze) {
21645                        mFrozenPackages.remove(mPackageName);
21646                    }
21647
21648                    if (mChildren != null) {
21649                        for (PackageFreezer freezer : mChildren) {
21650                            freezer.close();
21651                        }
21652                    }
21653                }
21654            }
21655        }
21656    }
21657
21658    /**
21659     * Verify that given package is currently frozen.
21660     */
21661    private void checkPackageFrozen(String packageName) {
21662        synchronized (mPackages) {
21663            if (!mFrozenPackages.contains(packageName)) {
21664                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21665            }
21666        }
21667    }
21668
21669    @Override
21670    public int movePackage(final String packageName, final String volumeUuid) {
21671        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21672
21673        final int callingUid = Binder.getCallingUid();
21674        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
21675        final int moveId = mNextMoveId.getAndIncrement();
21676        mHandler.post(new Runnable() {
21677            @Override
21678            public void run() {
21679                try {
21680                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
21681                } catch (PackageManagerException e) {
21682                    Slog.w(TAG, "Failed to move " + packageName, e);
21683                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
21684                }
21685            }
21686        });
21687        return moveId;
21688    }
21689
21690    private void movePackageInternal(final String packageName, final String volumeUuid,
21691            final int moveId, final int callingUid, UserHandle user)
21692                    throws PackageManagerException {
21693        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21694        final PackageManager pm = mContext.getPackageManager();
21695
21696        final boolean currentAsec;
21697        final String currentVolumeUuid;
21698        final File codeFile;
21699        final String installerPackageName;
21700        final String packageAbiOverride;
21701        final int appId;
21702        final String seinfo;
21703        final String label;
21704        final int targetSdkVersion;
21705        final PackageFreezer freezer;
21706        final int[] installedUserIds;
21707
21708        // reader
21709        synchronized (mPackages) {
21710            final PackageParser.Package pkg = mPackages.get(packageName);
21711            final PackageSetting ps = mSettings.mPackages.get(packageName);
21712            if (pkg == null
21713                    || ps == null
21714                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
21715                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21716            }
21717            if (pkg.applicationInfo.isSystemApp()) {
21718                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21719                        "Cannot move system application");
21720            }
21721
21722            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21723            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21724                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21725            if (isInternalStorage && !allow3rdPartyOnInternal) {
21726                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21727                        "3rd party apps are not allowed on internal storage");
21728            }
21729
21730            if (pkg.applicationInfo.isExternalAsec()) {
21731                currentAsec = true;
21732                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21733            } else if (pkg.applicationInfo.isForwardLocked()) {
21734                currentAsec = true;
21735                currentVolumeUuid = "forward_locked";
21736            } else {
21737                currentAsec = false;
21738                currentVolumeUuid = ps.volumeUuid;
21739
21740                final File probe = new File(pkg.codePath);
21741                final File probeOat = new File(probe, "oat");
21742                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21743                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21744                            "Move only supported for modern cluster style installs");
21745                }
21746            }
21747
21748            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21749                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21750                        "Package already moved to " + volumeUuid);
21751            }
21752            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21753                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21754                        "Device admin cannot be moved");
21755            }
21756
21757            if (mFrozenPackages.contains(packageName)) {
21758                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21759                        "Failed to move already frozen package");
21760            }
21761
21762            codeFile = new File(pkg.codePath);
21763            installerPackageName = ps.installerPackageName;
21764            packageAbiOverride = ps.cpuAbiOverrideString;
21765            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21766            seinfo = pkg.applicationInfo.seInfo;
21767            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21768            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21769            freezer = freezePackage(packageName, "movePackageInternal");
21770            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21771        }
21772
21773        final Bundle extras = new Bundle();
21774        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21775        extras.putString(Intent.EXTRA_TITLE, label);
21776        mMoveCallbacks.notifyCreated(moveId, extras);
21777
21778        int installFlags;
21779        final boolean moveCompleteApp;
21780        final File measurePath;
21781
21782        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21783            installFlags = INSTALL_INTERNAL;
21784            moveCompleteApp = !currentAsec;
21785            measurePath = Environment.getDataAppDirectory(volumeUuid);
21786        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21787            installFlags = INSTALL_EXTERNAL;
21788            moveCompleteApp = false;
21789            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21790        } else {
21791            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21792            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21793                    || !volume.isMountedWritable()) {
21794                freezer.close();
21795                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21796                        "Move location not mounted private volume");
21797            }
21798
21799            Preconditions.checkState(!currentAsec);
21800
21801            installFlags = INSTALL_INTERNAL;
21802            moveCompleteApp = true;
21803            measurePath = Environment.getDataAppDirectory(volumeUuid);
21804        }
21805
21806        // If we're moving app data around, we need all the users unlocked
21807        if (moveCompleteApp) {
21808            for (int userId : installedUserIds) {
21809                if (StorageManager.isFileEncryptedNativeOrEmulated()
21810                        && !StorageManager.isUserKeyUnlocked(userId)) {
21811                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
21812                            "User " + userId + " must be unlocked");
21813                }
21814            }
21815        }
21816
21817        final PackageStats stats = new PackageStats(null, -1);
21818        synchronized (mInstaller) {
21819            for (int userId : installedUserIds) {
21820                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21821                    freezer.close();
21822                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21823                            "Failed to measure package size");
21824                }
21825            }
21826        }
21827
21828        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
21829                + stats.dataSize);
21830
21831        final long startFreeBytes = measurePath.getUsableSpace();
21832        final long sizeBytes;
21833        if (moveCompleteApp) {
21834            sizeBytes = stats.codeSize + stats.dataSize;
21835        } else {
21836            sizeBytes = stats.codeSize;
21837        }
21838
21839        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
21840            freezer.close();
21841            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21842                    "Not enough free space to move");
21843        }
21844
21845        mMoveCallbacks.notifyStatusChanged(moveId, 10);
21846
21847        final CountDownLatch installedLatch = new CountDownLatch(1);
21848        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
21849            @Override
21850            public void onUserActionRequired(Intent intent) throws RemoteException {
21851                throw new IllegalStateException();
21852            }
21853
21854            @Override
21855            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
21856                    Bundle extras) throws RemoteException {
21857                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
21858                        + PackageManager.installStatusToString(returnCode, msg));
21859
21860                installedLatch.countDown();
21861                freezer.close();
21862
21863                final int status = PackageManager.installStatusToPublicStatus(returnCode);
21864                switch (status) {
21865                    case PackageInstaller.STATUS_SUCCESS:
21866                        mMoveCallbacks.notifyStatusChanged(moveId,
21867                                PackageManager.MOVE_SUCCEEDED);
21868                        break;
21869                    case PackageInstaller.STATUS_FAILURE_STORAGE:
21870                        mMoveCallbacks.notifyStatusChanged(moveId,
21871                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
21872                        break;
21873                    default:
21874                        mMoveCallbacks.notifyStatusChanged(moveId,
21875                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21876                        break;
21877                }
21878            }
21879        };
21880
21881        final MoveInfo move;
21882        if (moveCompleteApp) {
21883            // Kick off a thread to report progress estimates
21884            new Thread() {
21885                @Override
21886                public void run() {
21887                    while (true) {
21888                        try {
21889                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
21890                                break;
21891                            }
21892                        } catch (InterruptedException ignored) {
21893                        }
21894
21895                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
21896                        final int progress = 10 + (int) MathUtils.constrain(
21897                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
21898                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
21899                    }
21900                }
21901            }.start();
21902
21903            final String dataAppName = codeFile.getName();
21904            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
21905                    dataAppName, appId, seinfo, targetSdkVersion);
21906        } else {
21907            move = null;
21908        }
21909
21910        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
21911
21912        final Message msg = mHandler.obtainMessage(INIT_COPY);
21913        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
21914        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
21915                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
21916                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
21917                PackageManager.INSTALL_REASON_UNKNOWN);
21918        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
21919        msg.obj = params;
21920
21921        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
21922                System.identityHashCode(msg.obj));
21923        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
21924                System.identityHashCode(msg.obj));
21925
21926        mHandler.sendMessage(msg);
21927    }
21928
21929    @Override
21930    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
21931        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21932
21933        final int realMoveId = mNextMoveId.getAndIncrement();
21934        final Bundle extras = new Bundle();
21935        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
21936        mMoveCallbacks.notifyCreated(realMoveId, extras);
21937
21938        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
21939            @Override
21940            public void onCreated(int moveId, Bundle extras) {
21941                // Ignored
21942            }
21943
21944            @Override
21945            public void onStatusChanged(int moveId, int status, long estMillis) {
21946                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
21947            }
21948        };
21949
21950        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21951        storage.setPrimaryStorageUuid(volumeUuid, callback);
21952        return realMoveId;
21953    }
21954
21955    @Override
21956    public int getMoveStatus(int moveId) {
21957        mContext.enforceCallingOrSelfPermission(
21958                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21959        return mMoveCallbacks.mLastStatus.get(moveId);
21960    }
21961
21962    @Override
21963    public void registerMoveCallback(IPackageMoveObserver callback) {
21964        mContext.enforceCallingOrSelfPermission(
21965                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21966        mMoveCallbacks.register(callback);
21967    }
21968
21969    @Override
21970    public void unregisterMoveCallback(IPackageMoveObserver callback) {
21971        mContext.enforceCallingOrSelfPermission(
21972                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
21973        mMoveCallbacks.unregister(callback);
21974    }
21975
21976    @Override
21977    public boolean setInstallLocation(int loc) {
21978        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
21979                null);
21980        if (getInstallLocation() == loc) {
21981            return true;
21982        }
21983        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
21984                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
21985            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
21986                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
21987            return true;
21988        }
21989        return false;
21990   }
21991
21992    @Override
21993    public int getInstallLocation() {
21994        // allow instant app access
21995        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
21996                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
21997                PackageHelper.APP_INSTALL_AUTO);
21998    }
21999
22000    /** Called by UserManagerService */
22001    void cleanUpUser(UserManagerService userManager, int userHandle) {
22002        synchronized (mPackages) {
22003            mDirtyUsers.remove(userHandle);
22004            mUserNeedsBadging.delete(userHandle);
22005            mSettings.removeUserLPw(userHandle);
22006            mPendingBroadcasts.remove(userHandle);
22007            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22008            removeUnusedPackagesLPw(userManager, userHandle);
22009        }
22010    }
22011
22012    /**
22013     * We're removing userHandle and would like to remove any downloaded packages
22014     * that are no longer in use by any other user.
22015     * @param userHandle the user being removed
22016     */
22017    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22018        final boolean DEBUG_CLEAN_APKS = false;
22019        int [] users = userManager.getUserIds();
22020        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22021        while (psit.hasNext()) {
22022            PackageSetting ps = psit.next();
22023            if (ps.pkg == null) {
22024                continue;
22025            }
22026            final String packageName = ps.pkg.packageName;
22027            // Skip over if system app
22028            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22029                continue;
22030            }
22031            if (DEBUG_CLEAN_APKS) {
22032                Slog.i(TAG, "Checking package " + packageName);
22033            }
22034            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22035            if (keep) {
22036                if (DEBUG_CLEAN_APKS) {
22037                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22038                }
22039            } else {
22040                for (int i = 0; i < users.length; i++) {
22041                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22042                        keep = true;
22043                        if (DEBUG_CLEAN_APKS) {
22044                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22045                                    + users[i]);
22046                        }
22047                        break;
22048                    }
22049                }
22050            }
22051            if (!keep) {
22052                if (DEBUG_CLEAN_APKS) {
22053                    Slog.i(TAG, "  Removing package " + packageName);
22054                }
22055                mHandler.post(new Runnable() {
22056                    public void run() {
22057                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22058                                userHandle, 0);
22059                    } //end run
22060                });
22061            }
22062        }
22063    }
22064
22065    /** Called by UserManagerService */
22066    void createNewUser(int userId, String[] disallowedPackages) {
22067        synchronized (mInstallLock) {
22068            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22069        }
22070        synchronized (mPackages) {
22071            scheduleWritePackageRestrictionsLocked(userId);
22072            scheduleWritePackageListLocked(userId);
22073            applyFactoryDefaultBrowserLPw(userId);
22074            primeDomainVerificationsLPw(userId);
22075        }
22076    }
22077
22078    void onNewUserCreated(final int userId) {
22079        synchronized(mPackages) {
22080            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
22081            // If permission review for legacy apps is required, we represent
22082            // dagerous permissions for such apps as always granted runtime
22083            // permissions to keep per user flag state whether review is needed.
22084            // Hence, if a new user is added we have to propagate dangerous
22085            // permission grants for these legacy apps.
22086            if (mSettings.mPermissions.mPermissionReviewRequired) {
22087// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
22088                mPermissionManager.updateAllPermissions(
22089                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
22090                        mPermissionCallback);
22091            }
22092        }
22093    }
22094
22095    @Override
22096    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22097        mContext.enforceCallingOrSelfPermission(
22098                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22099                "Only package verification agents can read the verifier device identity");
22100
22101        synchronized (mPackages) {
22102            return mSettings.getVerifierDeviceIdentityLPw();
22103        }
22104    }
22105
22106    @Override
22107    public void setPermissionEnforced(String permission, boolean enforced) {
22108        // TODO: Now that we no longer change GID for storage, this should to away.
22109        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22110                "setPermissionEnforced");
22111        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22112            synchronized (mPackages) {
22113                if (mSettings.mReadExternalStorageEnforced == null
22114                        || mSettings.mReadExternalStorageEnforced != enforced) {
22115                    mSettings.mReadExternalStorageEnforced =
22116                            enforced ? Boolean.TRUE : Boolean.FALSE;
22117                    mSettings.writeLPr();
22118                }
22119            }
22120            // kill any non-foreground processes so we restart them and
22121            // grant/revoke the GID.
22122            final IActivityManager am = ActivityManager.getService();
22123            if (am != null) {
22124                final long token = Binder.clearCallingIdentity();
22125                try {
22126                    am.killProcessesBelowForeground("setPermissionEnforcement");
22127                } catch (RemoteException e) {
22128                } finally {
22129                    Binder.restoreCallingIdentity(token);
22130                }
22131            }
22132        } else {
22133            throw new IllegalArgumentException("No selective enforcement for " + permission);
22134        }
22135    }
22136
22137    @Override
22138    @Deprecated
22139    public boolean isPermissionEnforced(String permission) {
22140        // allow instant applications
22141        return true;
22142    }
22143
22144    @Override
22145    public boolean isStorageLow() {
22146        // allow instant applications
22147        final long token = Binder.clearCallingIdentity();
22148        try {
22149            final DeviceStorageMonitorInternal
22150                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22151            if (dsm != null) {
22152                return dsm.isMemoryLow();
22153            } else {
22154                return false;
22155            }
22156        } finally {
22157            Binder.restoreCallingIdentity(token);
22158        }
22159    }
22160
22161    @Override
22162    public IPackageInstaller getPackageInstaller() {
22163        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22164            return null;
22165        }
22166        return mInstallerService;
22167    }
22168
22169    private boolean userNeedsBadging(int userId) {
22170        int index = mUserNeedsBadging.indexOfKey(userId);
22171        if (index < 0) {
22172            final UserInfo userInfo;
22173            final long token = Binder.clearCallingIdentity();
22174            try {
22175                userInfo = sUserManager.getUserInfo(userId);
22176            } finally {
22177                Binder.restoreCallingIdentity(token);
22178            }
22179            final boolean b;
22180            if (userInfo != null && userInfo.isManagedProfile()) {
22181                b = true;
22182            } else {
22183                b = false;
22184            }
22185            mUserNeedsBadging.put(userId, b);
22186            return b;
22187        }
22188        return mUserNeedsBadging.valueAt(index);
22189    }
22190
22191    @Override
22192    public KeySet getKeySetByAlias(String packageName, String alias) {
22193        if (packageName == null || alias == null) {
22194            return null;
22195        }
22196        synchronized(mPackages) {
22197            final PackageParser.Package pkg = mPackages.get(packageName);
22198            if (pkg == null) {
22199                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22200                throw new IllegalArgumentException("Unknown package: " + packageName);
22201            }
22202            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22203            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
22204                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
22205                throw new IllegalArgumentException("Unknown package: " + packageName);
22206            }
22207            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22208            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22209        }
22210    }
22211
22212    @Override
22213    public KeySet getSigningKeySet(String packageName) {
22214        if (packageName == null) {
22215            return null;
22216        }
22217        synchronized(mPackages) {
22218            final int callingUid = Binder.getCallingUid();
22219            final int callingUserId = UserHandle.getUserId(callingUid);
22220            final PackageParser.Package pkg = mPackages.get(packageName);
22221            if (pkg == null) {
22222                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22223                throw new IllegalArgumentException("Unknown package: " + packageName);
22224            }
22225            final PackageSetting ps = (PackageSetting) pkg.mExtras;
22226            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
22227                // filter and pretend the package doesn't exist
22228                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
22229                        + ", uid:" + callingUid);
22230                throw new IllegalArgumentException("Unknown package: " + packageName);
22231            }
22232            if (pkg.applicationInfo.uid != callingUid
22233                    && Process.SYSTEM_UID != callingUid) {
22234                throw new SecurityException("May not access signing KeySet of other apps.");
22235            }
22236            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22237            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22238        }
22239    }
22240
22241    @Override
22242    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22243        final int callingUid = Binder.getCallingUid();
22244        if (getInstantAppPackageName(callingUid) != null) {
22245            return false;
22246        }
22247        if (packageName == null || ks == null) {
22248            return false;
22249        }
22250        synchronized(mPackages) {
22251            final PackageParser.Package pkg = mPackages.get(packageName);
22252            if (pkg == null
22253                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
22254                            UserHandle.getUserId(callingUid))) {
22255                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22256                throw new IllegalArgumentException("Unknown package: " + packageName);
22257            }
22258            IBinder ksh = ks.getToken();
22259            if (ksh instanceof KeySetHandle) {
22260                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
22261                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22262            }
22263            return false;
22264        }
22265    }
22266
22267    @Override
22268    public boolean isPackageSignedByKeySetExactly(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.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22288            }
22289            return false;
22290        }
22291    }
22292
22293    private void deletePackageIfUnusedLPr(final String packageName) {
22294        PackageSetting ps = mSettings.mPackages.get(packageName);
22295        if (ps == null) {
22296            return;
22297        }
22298        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22299            // TODO Implement atomic delete if package is unused
22300            // It is currently possible that the package will be deleted even if it is installed
22301            // after this method returns.
22302            mHandler.post(new Runnable() {
22303                public void run() {
22304                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22305                            0, PackageManager.DELETE_ALL_USERS);
22306                }
22307            });
22308        }
22309    }
22310
22311    /**
22312     * Check and throw if the given before/after packages would be considered a
22313     * downgrade.
22314     */
22315    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22316            throws PackageManagerException {
22317        if (after.versionCode < before.mVersionCode) {
22318            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22319                    "Update version code " + after.versionCode + " is older than current "
22320                    + before.mVersionCode);
22321        } else if (after.versionCode == before.mVersionCode) {
22322            if (after.baseRevisionCode < before.baseRevisionCode) {
22323                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22324                        "Update base revision code " + after.baseRevisionCode
22325                        + " is older than current " + before.baseRevisionCode);
22326            }
22327
22328            if (!ArrayUtils.isEmpty(after.splitNames)) {
22329                for (int i = 0; i < after.splitNames.length; i++) {
22330                    final String splitName = after.splitNames[i];
22331                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22332                    if (j != -1) {
22333                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22334                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22335                                    "Update split " + splitName + " revision code "
22336                                    + after.splitRevisionCodes[i] + " is older than current "
22337                                    + before.splitRevisionCodes[j]);
22338                        }
22339                    }
22340                }
22341            }
22342        }
22343    }
22344
22345    private static class MoveCallbacks extends Handler {
22346        private static final int MSG_CREATED = 1;
22347        private static final int MSG_STATUS_CHANGED = 2;
22348
22349        private final RemoteCallbackList<IPackageMoveObserver>
22350                mCallbacks = new RemoteCallbackList<>();
22351
22352        private final SparseIntArray mLastStatus = new SparseIntArray();
22353
22354        public MoveCallbacks(Looper looper) {
22355            super(looper);
22356        }
22357
22358        public void register(IPackageMoveObserver callback) {
22359            mCallbacks.register(callback);
22360        }
22361
22362        public void unregister(IPackageMoveObserver callback) {
22363            mCallbacks.unregister(callback);
22364        }
22365
22366        @Override
22367        public void handleMessage(Message msg) {
22368            final SomeArgs args = (SomeArgs) msg.obj;
22369            final int n = mCallbacks.beginBroadcast();
22370            for (int i = 0; i < n; i++) {
22371                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22372                try {
22373                    invokeCallback(callback, msg.what, args);
22374                } catch (RemoteException ignored) {
22375                }
22376            }
22377            mCallbacks.finishBroadcast();
22378            args.recycle();
22379        }
22380
22381        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22382                throws RemoteException {
22383            switch (what) {
22384                case MSG_CREATED: {
22385                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22386                    break;
22387                }
22388                case MSG_STATUS_CHANGED: {
22389                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22390                    break;
22391                }
22392            }
22393        }
22394
22395        private void notifyCreated(int moveId, Bundle extras) {
22396            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22397
22398            final SomeArgs args = SomeArgs.obtain();
22399            args.argi1 = moveId;
22400            args.arg2 = extras;
22401            obtainMessage(MSG_CREATED, args).sendToTarget();
22402        }
22403
22404        private void notifyStatusChanged(int moveId, int status) {
22405            notifyStatusChanged(moveId, status, -1);
22406        }
22407
22408        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22409            Slog.v(TAG, "Move " + moveId + " status " + status);
22410
22411            final SomeArgs args = SomeArgs.obtain();
22412            args.argi1 = moveId;
22413            args.argi2 = status;
22414            args.arg3 = estMillis;
22415            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22416
22417            synchronized (mLastStatus) {
22418                mLastStatus.put(moveId, status);
22419            }
22420        }
22421    }
22422
22423    private final static class OnPermissionChangeListeners extends Handler {
22424        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22425
22426        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22427                new RemoteCallbackList<>();
22428
22429        public OnPermissionChangeListeners(Looper looper) {
22430            super(looper);
22431        }
22432
22433        @Override
22434        public void handleMessage(Message msg) {
22435            switch (msg.what) {
22436                case MSG_ON_PERMISSIONS_CHANGED: {
22437                    final int uid = msg.arg1;
22438                    handleOnPermissionsChanged(uid);
22439                } break;
22440            }
22441        }
22442
22443        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22444            mPermissionListeners.register(listener);
22445
22446        }
22447
22448        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22449            mPermissionListeners.unregister(listener);
22450        }
22451
22452        public void onPermissionsChanged(int uid) {
22453            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22454                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22455            }
22456        }
22457
22458        private void handleOnPermissionsChanged(int uid) {
22459            final int count = mPermissionListeners.beginBroadcast();
22460            try {
22461                for (int i = 0; i < count; i++) {
22462                    IOnPermissionsChangeListener callback = mPermissionListeners
22463                            .getBroadcastItem(i);
22464                    try {
22465                        callback.onPermissionsChanged(uid);
22466                    } catch (RemoteException e) {
22467                        Log.e(TAG, "Permission listener is dead", e);
22468                    }
22469                }
22470            } finally {
22471                mPermissionListeners.finishBroadcast();
22472            }
22473        }
22474    }
22475
22476    private class PackageManagerNative extends IPackageManagerNative.Stub {
22477        @Override
22478        public String[] getNamesForUids(int[] uids) throws RemoteException {
22479            final String[] results = PackageManagerService.this.getNamesForUids(uids);
22480            // massage results so they can be parsed by the native binder
22481            for (int i = results.length - 1; i >= 0; --i) {
22482                if (results[i] == null) {
22483                    results[i] = "";
22484                }
22485            }
22486            return results;
22487        }
22488
22489        // NB: this differentiates between preloads and sideloads
22490        @Override
22491        public String getInstallerForPackage(String packageName) throws RemoteException {
22492            final String installerName = getInstallerPackageName(packageName);
22493            if (!TextUtils.isEmpty(installerName)) {
22494                return installerName;
22495            }
22496            // differentiate between preload and sideload
22497            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22498            ApplicationInfo appInfo = getApplicationInfo(packageName,
22499                                    /*flags*/ 0,
22500                                    /*userId*/ callingUser);
22501            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22502                return "preload";
22503            }
22504            return "";
22505        }
22506
22507        @Override
22508        public int getVersionCodeForPackage(String packageName) throws RemoteException {
22509            try {
22510                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
22511                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
22512                if (pInfo != null) {
22513                    return pInfo.versionCode;
22514                }
22515            } catch (Exception e) {
22516            }
22517            return 0;
22518        }
22519    }
22520
22521    private class PackageManagerInternalImpl extends PackageManagerInternal {
22522        @Override
22523        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
22524                int flagValues, int userId) {
22525            PackageManagerService.this.updatePermissionFlags(
22526                    permName, packageName, flagMask, flagValues, userId);
22527        }
22528
22529        @Override
22530        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
22531            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
22532        }
22533
22534        @Override
22535        public boolean isInstantApp(String packageName, int userId) {
22536            return PackageManagerService.this.isInstantApp(packageName, userId);
22537        }
22538
22539        @Override
22540        public String getInstantAppPackageName(int uid) {
22541            return PackageManagerService.this.getInstantAppPackageName(uid);
22542        }
22543
22544        @Override
22545        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
22546            synchronized (mPackages) {
22547                return PackageManagerService.this.filterAppAccessLPr(
22548                        (PackageSetting) pkg.mExtras, callingUid, userId);
22549            }
22550        }
22551
22552        @Override
22553        public PackageParser.Package getPackage(String packageName) {
22554            synchronized (mPackages) {
22555                packageName = resolveInternalPackageNameLPr(
22556                        packageName, PackageManager.VERSION_CODE_HIGHEST);
22557                return mPackages.get(packageName);
22558            }
22559        }
22560
22561        @Override
22562        public PackageParser.Package getDisabledPackage(String packageName) {
22563            synchronized (mPackages) {
22564                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
22565                return (ps != null) ? ps.pkg : null;
22566            }
22567        }
22568
22569        @Override
22570        public String getKnownPackageName(int knownPackage, int userId) {
22571            switch(knownPackage) {
22572                case PackageManagerInternal.PACKAGE_BROWSER:
22573                    return getDefaultBrowserPackageName(userId);
22574                case PackageManagerInternal.PACKAGE_INSTALLER:
22575                    return mRequiredInstallerPackage;
22576                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
22577                    return mSetupWizardPackage;
22578                case PackageManagerInternal.PACKAGE_SYSTEM:
22579                    return "android";
22580                case PackageManagerInternal.PACKAGE_VERIFIER:
22581                    return mRequiredVerifierPackage;
22582            }
22583            return null;
22584        }
22585
22586        @Override
22587        public boolean isResolveActivityComponent(ComponentInfo component) {
22588            return mResolveActivity.packageName.equals(component.packageName)
22589                    && mResolveActivity.name.equals(component.name);
22590        }
22591
22592        @Override
22593        public void setLocationPackagesProvider(PackagesProvider provider) {
22594            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
22595        }
22596
22597        @Override
22598        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22599            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
22600        }
22601
22602        @Override
22603        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22604            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
22605        }
22606
22607        @Override
22608        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22609            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
22610        }
22611
22612        @Override
22613        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22614            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
22615        }
22616
22617        @Override
22618        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22619            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
22620        }
22621
22622        @Override
22623        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22624            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
22625        }
22626
22627        @Override
22628        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22629            synchronized (mPackages) {
22630                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22631            }
22632            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
22633        }
22634
22635        @Override
22636        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22637            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
22638                    packageName, userId);
22639        }
22640
22641        @Override
22642        public void setKeepUninstalledPackages(final List<String> packageList) {
22643            Preconditions.checkNotNull(packageList);
22644            List<String> removedFromList = null;
22645            synchronized (mPackages) {
22646                if (mKeepUninstalledPackages != null) {
22647                    final int packagesCount = mKeepUninstalledPackages.size();
22648                    for (int i = 0; i < packagesCount; i++) {
22649                        String oldPackage = mKeepUninstalledPackages.get(i);
22650                        if (packageList != null && packageList.contains(oldPackage)) {
22651                            continue;
22652                        }
22653                        if (removedFromList == null) {
22654                            removedFromList = new ArrayList<>();
22655                        }
22656                        removedFromList.add(oldPackage);
22657                    }
22658                }
22659                mKeepUninstalledPackages = new ArrayList<>(packageList);
22660                if (removedFromList != null) {
22661                    final int removedCount = removedFromList.size();
22662                    for (int i = 0; i < removedCount; i++) {
22663                        deletePackageIfUnusedLPr(removedFromList.get(i));
22664                    }
22665                }
22666            }
22667        }
22668
22669        @Override
22670        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22671            synchronized (mPackages) {
22672                return mPermissionManager.isPermissionsReviewRequired(
22673                        mPackages.get(packageName), userId);
22674            }
22675        }
22676
22677        @Override
22678        public PackageInfo getPackageInfo(
22679                String packageName, int flags, int filterCallingUid, int userId) {
22680            return PackageManagerService.this
22681                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
22682                            flags, filterCallingUid, userId);
22683        }
22684
22685        @Override
22686        public ApplicationInfo getApplicationInfo(
22687                String packageName, int flags, int filterCallingUid, int userId) {
22688            return PackageManagerService.this
22689                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
22690        }
22691
22692        @Override
22693        public ActivityInfo getActivityInfo(
22694                ComponentName component, int flags, int filterCallingUid, int userId) {
22695            return PackageManagerService.this
22696                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
22697        }
22698
22699        @Override
22700        public List<ResolveInfo> queryIntentActivities(
22701                Intent intent, int flags, int filterCallingUid, int userId) {
22702            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22703            return PackageManagerService.this
22704                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
22705                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
22706        }
22707
22708        @Override
22709        public List<ResolveInfo> queryIntentServices(
22710                Intent intent, int flags, int callingUid, int userId) {
22711            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
22712            return PackageManagerService.this
22713                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
22714                            false);
22715        }
22716
22717        @Override
22718        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22719                int userId) {
22720            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22721        }
22722
22723        @Override
22724        public void setDeviceAndProfileOwnerPackages(
22725                int deviceOwnerUserId, String deviceOwnerPackage,
22726                SparseArray<String> profileOwnerPackages) {
22727            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22728                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22729        }
22730
22731        @Override
22732        public boolean isPackageDataProtected(int userId, String packageName) {
22733            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22734        }
22735
22736        @Override
22737        public boolean isPackageEphemeral(int userId, String packageName) {
22738            synchronized (mPackages) {
22739                final PackageSetting ps = mSettings.mPackages.get(packageName);
22740                return ps != null ? ps.getInstantApp(userId) : false;
22741            }
22742        }
22743
22744        @Override
22745        public boolean wasPackageEverLaunched(String packageName, int userId) {
22746            synchronized (mPackages) {
22747                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22748            }
22749        }
22750
22751        @Override
22752        public void grantRuntimePermission(String packageName, String permName, int userId,
22753                boolean overridePolicy) {
22754            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
22755                    permName, packageName, overridePolicy, getCallingUid(), userId,
22756                    mPermissionCallback);
22757        }
22758
22759        @Override
22760        public void revokeRuntimePermission(String packageName, String permName, int userId,
22761                boolean overridePolicy) {
22762            mPermissionManager.revokeRuntimePermission(
22763                    permName, packageName, overridePolicy, getCallingUid(), userId,
22764                    mPermissionCallback);
22765        }
22766
22767        @Override
22768        public String getNameForUid(int uid) {
22769            return PackageManagerService.this.getNameForUid(uid);
22770        }
22771
22772        @Override
22773        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
22774                Intent origIntent, String resolvedType, String callingPackage,
22775                Bundle verificationBundle, int userId) {
22776            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
22777                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
22778                    userId);
22779        }
22780
22781        @Override
22782        public void grantEphemeralAccess(int userId, Intent intent,
22783                int targetAppId, int ephemeralAppId) {
22784            synchronized (mPackages) {
22785                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22786                        targetAppId, ephemeralAppId);
22787            }
22788        }
22789
22790        @Override
22791        public boolean isInstantAppInstallerComponent(ComponentName component) {
22792            synchronized (mPackages) {
22793                return mInstantAppInstallerActivity != null
22794                        && mInstantAppInstallerActivity.getComponentName().equals(component);
22795            }
22796        }
22797
22798        @Override
22799        public void pruneInstantApps() {
22800            mInstantAppRegistry.pruneInstantApps();
22801        }
22802
22803        @Override
22804        public String getSetupWizardPackageName() {
22805            return mSetupWizardPackage;
22806        }
22807
22808        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22809            if (policy != null) {
22810                mExternalSourcesPolicy = policy;
22811            }
22812        }
22813
22814        @Override
22815        public boolean isPackagePersistent(String packageName) {
22816            synchronized (mPackages) {
22817                PackageParser.Package pkg = mPackages.get(packageName);
22818                return pkg != null
22819                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
22820                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
22821                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
22822                        : false;
22823            }
22824        }
22825
22826        @Override
22827        public boolean isLegacySystemApp(Package pkg) {
22828            synchronized (mPackages) {
22829                final PackageSetting ps = (PackageSetting) pkg.mExtras;
22830                return mPromoteSystemApps
22831                        && ps.isSystem()
22832                        && mExistingSystemPackages.contains(ps.name);
22833            }
22834        }
22835
22836        @Override
22837        public List<PackageInfo> getOverlayPackages(int userId) {
22838            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22839            synchronized (mPackages) {
22840                for (PackageParser.Package p : mPackages.values()) {
22841                    if (p.mOverlayTarget != null) {
22842                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22843                        if (pkg != null) {
22844                            overlayPackages.add(pkg);
22845                        }
22846                    }
22847                }
22848            }
22849            return overlayPackages;
22850        }
22851
22852        @Override
22853        public List<String> getTargetPackageNames(int userId) {
22854            List<String> targetPackages = new ArrayList<>();
22855            synchronized (mPackages) {
22856                for (PackageParser.Package p : mPackages.values()) {
22857                    if (p.mOverlayTarget == null) {
22858                        targetPackages.add(p.packageName);
22859                    }
22860                }
22861            }
22862            return targetPackages;
22863        }
22864
22865        @Override
22866        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
22867                @Nullable List<String> overlayPackageNames) {
22868            synchronized (mPackages) {
22869                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
22870                    Slog.e(TAG, "failed to find package " + targetPackageName);
22871                    return false;
22872                }
22873                ArrayList<String> overlayPaths = null;
22874                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
22875                    final int N = overlayPackageNames.size();
22876                    overlayPaths = new ArrayList<>(N);
22877                    for (int i = 0; i < N; i++) {
22878                        final String packageName = overlayPackageNames.get(i);
22879                        final PackageParser.Package pkg = mPackages.get(packageName);
22880                        if (pkg == null) {
22881                            Slog.e(TAG, "failed to find package " + packageName);
22882                            return false;
22883                        }
22884                        overlayPaths.add(pkg.baseCodePath);
22885                    }
22886                }
22887
22888                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
22889                ps.setOverlayPaths(overlayPaths, userId);
22890                return true;
22891            }
22892        }
22893
22894        @Override
22895        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
22896                int flags, int userId, boolean resolveForStart) {
22897            return resolveIntentInternal(
22898                    intent, resolvedType, flags, userId, resolveForStart);
22899        }
22900
22901        @Override
22902        public ResolveInfo resolveService(Intent intent, String resolvedType,
22903                int flags, int userId, int callingUid) {
22904            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
22905        }
22906
22907        @Override
22908        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
22909            return PackageManagerService.this.resolveContentProviderInternal(
22910                    name, flags, userId);
22911        }
22912
22913        @Override
22914        public void addIsolatedUid(int isolatedUid, int ownerUid) {
22915            synchronized (mPackages) {
22916                mIsolatedOwners.put(isolatedUid, ownerUid);
22917            }
22918        }
22919
22920        @Override
22921        public void removeIsolatedUid(int isolatedUid) {
22922            synchronized (mPackages) {
22923                mIsolatedOwners.delete(isolatedUid);
22924            }
22925        }
22926
22927        @Override
22928        public int getUidTargetSdkVersion(int uid) {
22929            synchronized (mPackages) {
22930                return getUidTargetSdkVersionLockedLPr(uid);
22931            }
22932        }
22933
22934        @Override
22935        public boolean canAccessInstantApps(int callingUid, int userId) {
22936            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
22937        }
22938
22939        @Override
22940        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
22941            synchronized (mPackages) {
22942                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
22943            }
22944        }
22945
22946        @Override
22947        public void notifyPackageUse(String packageName, int reason) {
22948            synchronized (mPackages) {
22949                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
22950            }
22951        }
22952    }
22953
22954    @Override
22955    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22956        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22957        synchronized (mPackages) {
22958            final long identity = Binder.clearCallingIdentity();
22959            try {
22960                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
22961                        packageNames, userId);
22962            } finally {
22963                Binder.restoreCallingIdentity(identity);
22964            }
22965        }
22966    }
22967
22968    @Override
22969    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22970        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
22971        synchronized (mPackages) {
22972            final long identity = Binder.clearCallingIdentity();
22973            try {
22974                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
22975                        packageNames, userId);
22976            } finally {
22977                Binder.restoreCallingIdentity(identity);
22978            }
22979        }
22980    }
22981
22982    private static void enforceSystemOrPhoneCaller(String tag) {
22983        int callingUid = Binder.getCallingUid();
22984        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22985            throw new SecurityException(
22986                    "Cannot call " + tag + " from UID " + callingUid);
22987        }
22988    }
22989
22990    boolean isHistoricalPackageUsageAvailable() {
22991        return mPackageUsage.isHistoricalPackageUsageAvailable();
22992    }
22993
22994    /**
22995     * Return a <b>copy</b> of the collection of packages known to the package manager.
22996     * @return A copy of the values of mPackages.
22997     */
22998    Collection<PackageParser.Package> getPackages() {
22999        synchronized (mPackages) {
23000            return new ArrayList<>(mPackages.values());
23001        }
23002    }
23003
23004    /**
23005     * Logs process start information (including base APK hash) to the security log.
23006     * @hide
23007     */
23008    @Override
23009    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23010            String apkFile, int pid) {
23011        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23012            return;
23013        }
23014        if (!SecurityLog.isLoggingEnabled()) {
23015            return;
23016        }
23017        Bundle data = new Bundle();
23018        data.putLong("startTimestamp", System.currentTimeMillis());
23019        data.putString("processName", processName);
23020        data.putInt("uid", uid);
23021        data.putString("seinfo", seinfo);
23022        data.putString("apkFile", apkFile);
23023        data.putInt("pid", pid);
23024        Message msg = mProcessLoggingHandler.obtainMessage(
23025                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23026        msg.setData(data);
23027        mProcessLoggingHandler.sendMessage(msg);
23028    }
23029
23030    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23031        return mCompilerStats.getPackageStats(pkgName);
23032    }
23033
23034    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23035        return getOrCreateCompilerPackageStats(pkg.packageName);
23036    }
23037
23038    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23039        return mCompilerStats.getOrCreatePackageStats(pkgName);
23040    }
23041
23042    public void deleteCompilerPackageStats(String pkgName) {
23043        mCompilerStats.deletePackageStats(pkgName);
23044    }
23045
23046    @Override
23047    public int getInstallReason(String packageName, int userId) {
23048        final int callingUid = Binder.getCallingUid();
23049        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
23050                true /* requireFullPermission */, false /* checkShell */,
23051                "get install reason");
23052        synchronized (mPackages) {
23053            final PackageSetting ps = mSettings.mPackages.get(packageName);
23054            if (filterAppAccessLPr(ps, callingUid, userId)) {
23055                return PackageManager.INSTALL_REASON_UNKNOWN;
23056            }
23057            if (ps != null) {
23058                return ps.getInstallReason(userId);
23059            }
23060        }
23061        return PackageManager.INSTALL_REASON_UNKNOWN;
23062    }
23063
23064    @Override
23065    public boolean canRequestPackageInstalls(String packageName, int userId) {
23066        return canRequestPackageInstallsInternal(packageName, 0, userId,
23067                true /* throwIfPermNotDeclared*/);
23068    }
23069
23070    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
23071            boolean throwIfPermNotDeclared) {
23072        int callingUid = Binder.getCallingUid();
23073        int uid = getPackageUid(packageName, 0, userId);
23074        if (callingUid != uid && callingUid != Process.ROOT_UID
23075                && callingUid != Process.SYSTEM_UID) {
23076            throw new SecurityException(
23077                    "Caller uid " + callingUid + " does not own package " + packageName);
23078        }
23079        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
23080        if (info == null) {
23081            return false;
23082        }
23083        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23084            return false;
23085        }
23086        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23087        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23088        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23089            if (throwIfPermNotDeclared) {
23090                throw new SecurityException("Need to declare " + appOpPermission
23091                        + " to call this api");
23092            } else {
23093                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
23094                return false;
23095            }
23096        }
23097        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23098            return false;
23099        }
23100        if (mExternalSourcesPolicy != null) {
23101            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23102            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23103                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23104            }
23105        }
23106        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23107    }
23108
23109    @Override
23110    public ComponentName getInstantAppResolverSettingsComponent() {
23111        return mInstantAppResolverSettingsComponent;
23112    }
23113
23114    @Override
23115    public ComponentName getInstantAppInstallerComponent() {
23116        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23117            return null;
23118        }
23119        return mInstantAppInstallerActivity == null
23120                ? null : mInstantAppInstallerActivity.getComponentName();
23121    }
23122
23123    @Override
23124    public String getInstantAppAndroidId(String packageName, int userId) {
23125        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23126                "getInstantAppAndroidId");
23127        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
23128                true /* requireFullPermission */, false /* checkShell */,
23129                "getInstantAppAndroidId");
23130        // Make sure the target is an Instant App.
23131        if (!isInstantApp(packageName, userId)) {
23132            return null;
23133        }
23134        synchronized (mPackages) {
23135            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23136        }
23137    }
23138
23139    boolean canHaveOatDir(String packageName) {
23140        synchronized (mPackages) {
23141            PackageParser.Package p = mPackages.get(packageName);
23142            if (p == null) {
23143                return false;
23144            }
23145            return p.canHaveOatDir();
23146        }
23147    }
23148
23149    private String getOatDir(PackageParser.Package pkg) {
23150        if (!pkg.canHaveOatDir()) {
23151            return null;
23152        }
23153        File codePath = new File(pkg.codePath);
23154        if (codePath.isDirectory()) {
23155            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
23156        }
23157        return null;
23158    }
23159
23160    void deleteOatArtifactsOfPackage(String packageName) {
23161        final String[] instructionSets;
23162        final List<String> codePaths;
23163        final String oatDir;
23164        final PackageParser.Package pkg;
23165        synchronized (mPackages) {
23166            pkg = mPackages.get(packageName);
23167        }
23168        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
23169        codePaths = pkg.getAllCodePaths();
23170        oatDir = getOatDir(pkg);
23171
23172        for (String codePath : codePaths) {
23173            for (String isa : instructionSets) {
23174                try {
23175                    mInstaller.deleteOdex(codePath, isa, oatDir);
23176                } catch (InstallerException e) {
23177                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
23178                }
23179            }
23180        }
23181    }
23182
23183    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
23184        Set<String> unusedPackages = new HashSet<>();
23185        long currentTimeInMillis = System.currentTimeMillis();
23186        synchronized (mPackages) {
23187            for (PackageParser.Package pkg : mPackages.values()) {
23188                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
23189                if (ps == null) {
23190                    continue;
23191                }
23192                PackageDexUsage.PackageUseInfo packageUseInfo =
23193                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
23194                if (PackageManagerServiceUtils
23195                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
23196                                downgradeTimeThresholdMillis, packageUseInfo,
23197                                pkg.getLatestPackageUseTimeInMills(),
23198                                pkg.getLatestForegroundPackageUseTimeInMills())) {
23199                    unusedPackages.add(pkg.packageName);
23200                }
23201            }
23202        }
23203        return unusedPackages;
23204    }
23205}
23206
23207interface PackageSender {
23208    void sendPackageBroadcast(final String action, final String pkg,
23209        final Bundle extras, final int flags, final String targetPkg,
23210        final IIntentReceiver finishedReceiver, final int[] userIds);
23211    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
23212        boolean includeStopped, int appId, int... userIds);
23213}
23214