PackageManagerService.java revision 7098c1cbec6801f4301bd00d4acd4788e99e602d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108
109import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageManagerInternal;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.BootTimingsTraceLog;
233import android.util.DisplayMetrics;
234import android.util.EventLog;
235import android.util.ExceptionUtils;
236import android.util.Log;
237import android.util.LogPrinter;
238import android.util.MathUtils;
239import android.util.PackageUtils;
240import android.util.Pair;
241import android.util.PrintStreamPrinter;
242import android.util.Slog;
243import android.util.SparseArray;
244import android.util.SparseBooleanArray;
245import android.util.SparseIntArray;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.PermissionsState.PermissionState;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexManager;
289import com.android.server.pm.dex.DexoptOptions;
290import com.android.server.pm.dex.PackageDexUsage;
291import com.android.server.storage.DeviceStorageMonitorInternal;
292
293import dalvik.system.CloseGuard;
294import dalvik.system.DexFile;
295import dalvik.system.VMRuntime;
296
297import libcore.io.IoUtils;
298import libcore.io.Streams;
299import libcore.util.EmptyArray;
300
301import org.xmlpull.v1.XmlPullParser;
302import org.xmlpull.v1.XmlPullParserException;
303import org.xmlpull.v1.XmlSerializer;
304
305import java.io.BufferedOutputStream;
306import java.io.BufferedReader;
307import java.io.ByteArrayInputStream;
308import java.io.ByteArrayOutputStream;
309import java.io.File;
310import java.io.FileDescriptor;
311import java.io.FileInputStream;
312import java.io.FileOutputStream;
313import java.io.FileReader;
314import java.io.FilenameFilter;
315import java.io.IOException;
316import java.io.InputStream;
317import java.io.OutputStream;
318import java.io.PrintWriter;
319import java.lang.annotation.Retention;
320import java.lang.annotation.RetentionPolicy;
321import java.nio.charset.StandardCharsets;
322import java.security.DigestInputStream;
323import java.security.MessageDigest;
324import java.security.NoSuchAlgorithmException;
325import java.security.PublicKey;
326import java.security.SecureRandom;
327import java.security.cert.Certificate;
328import java.security.cert.CertificateEncodingException;
329import java.security.cert.CertificateException;
330import java.text.SimpleDateFormat;
331import java.util.ArrayList;
332import java.util.Arrays;
333import java.util.Collection;
334import java.util.Collections;
335import java.util.Comparator;
336import java.util.Date;
337import java.util.HashMap;
338import java.util.HashSet;
339import java.util.Iterator;
340import java.util.List;
341import java.util.Map;
342import java.util.Objects;
343import java.util.Set;
344import java.util.concurrent.CountDownLatch;
345import java.util.concurrent.Future;
346import java.util.concurrent.TimeUnit;
347import java.util.concurrent.atomic.AtomicBoolean;
348import java.util.concurrent.atomic.AtomicInteger;
349import java.util.zip.GZIPInputStream;
350
351/**
352 * Keep track of all those APKs everywhere.
353 * <p>
354 * Internally there are two important locks:
355 * <ul>
356 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
357 * and other related state. It is a fine-grained lock that should only be held
358 * momentarily, as it's one of the most contended locks in the system.
359 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
360 * operations typically involve heavy lifting of application data on disk. Since
361 * {@code installd} is single-threaded, and it's operations can often be slow,
362 * this lock should never be acquired while already holding {@link #mPackages}.
363 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
364 * holding {@link #mInstallLock}.
365 * </ul>
366 * Many internal methods rely on the caller to hold the appropriate locks, and
367 * this contract is expressed through method name suffixes:
368 * <ul>
369 * <li>fooLI(): the caller must hold {@link #mInstallLock}
370 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
371 * being modified must be frozen
372 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
373 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
374 * </ul>
375 * <p>
376 * Because this class is very central to the platform's security; please run all
377 * CTS and unit tests whenever making modifications:
378 *
379 * <pre>
380 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
381 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
382 * </pre>
383 */
384public class PackageManagerService extends IPackageManager.Stub
385        implements PackageSender {
386    static final String TAG = "PackageManager";
387    static final boolean DEBUG_SETTINGS = false;
388    static final boolean DEBUG_PREFERRED = false;
389    static final boolean DEBUG_UPGRADE = false;
390    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
391    private static final boolean DEBUG_BACKUP = false;
392    private static final boolean DEBUG_INSTALL = false;
393    private static final boolean DEBUG_REMOVE = false;
394    private static final boolean DEBUG_BROADCASTS = false;
395    private static final boolean DEBUG_SHOW_INFO = false;
396    private static final boolean DEBUG_PACKAGE_INFO = false;
397    private static final boolean DEBUG_INTENT_MATCHING = false;
398    private static final boolean DEBUG_PACKAGE_SCANNING = false;
399    private static final boolean DEBUG_VERIFY = false;
400    private static final boolean DEBUG_FILTERS = false;
401    private static final boolean DEBUG_PERMISSIONS = false;
402    private static final boolean DEBUG_SHARED_LIBRARIES = false;
403    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
404
405    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
406    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
407    // user, but by default initialize to this.
408    public static final boolean DEBUG_DEXOPT = false;
409
410    private static final boolean DEBUG_ABI_SELECTION = false;
411    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
412    private static final boolean DEBUG_TRIAGED_MISSING = false;
413    private static final boolean DEBUG_APP_DATA = false;
414
415    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
416    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
417
418    private static final boolean HIDE_EPHEMERAL_APIS = false;
419
420    private static final boolean ENABLE_FREE_CACHE_V2 =
421            SystemProperties.getBoolean("fw.free_cache_v2", true);
422
423    private static final int RADIO_UID = Process.PHONE_UID;
424    private static final int LOG_UID = Process.LOG_UID;
425    private static final int NFC_UID = Process.NFC_UID;
426    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
427    private static final int SHELL_UID = Process.SHELL_UID;
428
429    // Cap the size of permission trees that 3rd party apps can define
430    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
431
432    // Suffix used during package installation when copying/moving
433    // package apks to install directory.
434    private static final String INSTALL_PACKAGE_SUFFIX = "-";
435
436    static final int SCAN_NO_DEX = 1<<1;
437    static final int SCAN_FORCE_DEX = 1<<2;
438    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
439    static final int SCAN_NEW_INSTALL = 1<<4;
440    static final int SCAN_UPDATE_TIME = 1<<5;
441    static final int SCAN_BOOTING = 1<<6;
442    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
443    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
444    static final int SCAN_REPLACING = 1<<9;
445    static final int SCAN_REQUIRE_KNOWN = 1<<10;
446    static final int SCAN_MOVE = 1<<11;
447    static final int SCAN_INITIAL = 1<<12;
448    static final int SCAN_CHECK_ONLY = 1<<13;
449    static final int SCAN_DONT_KILL_APP = 1<<14;
450    static final int SCAN_IGNORE_FROZEN = 1<<15;
451    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
452    static final int SCAN_AS_INSTANT_APP = 1<<17;
453    static final int SCAN_AS_FULL_APP = 1<<18;
454    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
455    /** Should not be with the scan flags */
456    static final int FLAGS_REMOVE_CHATTY = 1<<31;
457
458    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
459    /** Extension of the compressed packages */
460    private final static String COMPRESSED_EXTENSION = ".gz";
461
462    private static final int[] EMPTY_INT_ARRAY = new int[0];
463
464    private static final int TYPE_UNKNOWN = 0;
465    private static final int TYPE_ACTIVITY = 1;
466    private static final int TYPE_RECEIVER = 2;
467    private static final int TYPE_SERVICE = 3;
468    private static final int TYPE_PROVIDER = 4;
469    @IntDef(prefix = { "TYPE_" }, value = {
470            TYPE_UNKNOWN,
471            TYPE_ACTIVITY,
472            TYPE_RECEIVER,
473            TYPE_SERVICE,
474            TYPE_PROVIDER,
475    })
476    @Retention(RetentionPolicy.SOURCE)
477    public @interface ComponentType {}
478
479    /**
480     * Timeout (in milliseconds) after which the watchdog should declare that
481     * our handler thread is wedged.  The usual default for such things is one
482     * minute but we sometimes do very lengthy I/O operations on this thread,
483     * such as installing multi-gigabyte applications, so ours needs to be longer.
484     */
485    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
486
487    /**
488     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
489     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
490     * settings entry if available, otherwise we use the hardcoded default.  If it's been
491     * more than this long since the last fstrim, we force one during the boot sequence.
492     *
493     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
494     * one gets run at the next available charging+idle time.  This final mandatory
495     * no-fstrim check kicks in only of the other scheduling criteria is never met.
496     */
497    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
498
499    /**
500     * Whether verification is enabled by default.
501     */
502    private static final boolean DEFAULT_VERIFY_ENABLE = true;
503
504    /**
505     * The default maximum time to wait for the verification agent to return in
506     * milliseconds.
507     */
508    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
509
510    /**
511     * The default response for package verification timeout.
512     *
513     * This can be either PackageManager.VERIFICATION_ALLOW or
514     * PackageManager.VERIFICATION_REJECT.
515     */
516    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
517
518    static final String PLATFORM_PACKAGE_NAME = "android";
519
520    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
521
522    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
523            DEFAULT_CONTAINER_PACKAGE,
524            "com.android.defcontainer.DefaultContainerService");
525
526    private static final String KILL_APP_REASON_GIDS_CHANGED =
527            "permission grant or revoke changed gids";
528
529    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
530            "permissions revoked";
531
532    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
533
534    private static final String PACKAGE_SCHEME = "package";
535
536    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
537
538    /** Permission grant: not grant the permission. */
539    private static final int GRANT_DENIED = 1;
540
541    /** Permission grant: grant the permission as an install permission. */
542    private static final int GRANT_INSTALL = 2;
543
544    /** Permission grant: grant the permission as a runtime one. */
545    private static final int GRANT_RUNTIME = 3;
546
547    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
548    private static final int GRANT_UPGRADE = 4;
549
550    /** Canonical intent used to identify what counts as a "web browser" app */
551    private static final Intent sBrowserIntent;
552    static {
553        sBrowserIntent = new Intent();
554        sBrowserIntent.setAction(Intent.ACTION_VIEW);
555        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
556        sBrowserIntent.setData(Uri.parse("http:"));
557    }
558
559    /**
560     * The set of all protected actions [i.e. those actions for which a high priority
561     * intent filter is disallowed].
562     */
563    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
564    static {
565        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
566        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
567        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
568        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
569    }
570
571    // Compilation reasons.
572    public static final int REASON_FIRST_BOOT = 0;
573    public static final int REASON_BOOT = 1;
574    public static final int REASON_INSTALL = 2;
575    public static final int REASON_BACKGROUND_DEXOPT = 3;
576    public static final int REASON_AB_OTA = 4;
577    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
578
579    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
580
581    /** All dangerous permission names in the same order as the events in MetricsEvent */
582    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
583            Manifest.permission.READ_CALENDAR,
584            Manifest.permission.WRITE_CALENDAR,
585            Manifest.permission.CAMERA,
586            Manifest.permission.READ_CONTACTS,
587            Manifest.permission.WRITE_CONTACTS,
588            Manifest.permission.GET_ACCOUNTS,
589            Manifest.permission.ACCESS_FINE_LOCATION,
590            Manifest.permission.ACCESS_COARSE_LOCATION,
591            Manifest.permission.RECORD_AUDIO,
592            Manifest.permission.READ_PHONE_STATE,
593            Manifest.permission.CALL_PHONE,
594            Manifest.permission.READ_CALL_LOG,
595            Manifest.permission.WRITE_CALL_LOG,
596            Manifest.permission.ADD_VOICEMAIL,
597            Manifest.permission.USE_SIP,
598            Manifest.permission.PROCESS_OUTGOING_CALLS,
599            Manifest.permission.READ_CELL_BROADCASTS,
600            Manifest.permission.BODY_SENSORS,
601            Manifest.permission.SEND_SMS,
602            Manifest.permission.RECEIVE_SMS,
603            Manifest.permission.READ_SMS,
604            Manifest.permission.RECEIVE_WAP_PUSH,
605            Manifest.permission.RECEIVE_MMS,
606            Manifest.permission.READ_EXTERNAL_STORAGE,
607            Manifest.permission.WRITE_EXTERNAL_STORAGE,
608            Manifest.permission.READ_PHONE_NUMBERS,
609            Manifest.permission.ANSWER_PHONE_CALLS);
610
611
612    /**
613     * Version number for the package parser cache. Increment this whenever the format or
614     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
615     */
616    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
617
618    /**
619     * Whether the package parser cache is enabled.
620     */
621    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
622
623    final ServiceThread mHandlerThread;
624
625    final PackageHandler mHandler;
626
627    private final ProcessLoggingHandler mProcessLoggingHandler;
628
629    /**
630     * Messages for {@link #mHandler} that need to wait for system ready before
631     * being dispatched.
632     */
633    private ArrayList<Message> mPostSystemReadyMessages;
634
635    final int mSdkVersion = Build.VERSION.SDK_INT;
636
637    final Context mContext;
638    final boolean mFactoryTest;
639    final boolean mOnlyCore;
640    final DisplayMetrics mMetrics;
641    final int mDefParseFlags;
642    final String[] mSeparateProcesses;
643    final boolean mIsUpgrade;
644    final boolean mIsPreNUpgrade;
645    final boolean mIsPreNMR1Upgrade;
646
647    // Have we told the Activity Manager to whitelist the default container service by uid yet?
648    @GuardedBy("mPackages")
649    boolean mDefaultContainerWhitelisted = false;
650
651    @GuardedBy("mPackages")
652    private boolean mDexOptDialogShown;
653
654    /** The location for ASEC container files on internal storage. */
655    final String mAsecInternalPath;
656
657    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
658    // LOCK HELD.  Can be called with mInstallLock held.
659    @GuardedBy("mInstallLock")
660    final Installer mInstaller;
661
662    /** Directory where installed third-party apps stored */
663    final File mAppInstallDir;
664
665    /**
666     * Directory to which applications installed internally have their
667     * 32 bit native libraries copied.
668     */
669    private File mAppLib32InstallDir;
670
671    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
672    // apps.
673    final File mDrmAppPrivateInstallDir;
674
675    // ----------------------------------------------------------------
676
677    // Lock for state used when installing and doing other long running
678    // operations.  Methods that must be called with this lock held have
679    // the suffix "LI".
680    final Object mInstallLock = new Object();
681
682    // ----------------------------------------------------------------
683
684    // Keys are String (package name), values are Package.  This also serves
685    // as the lock for the global state.  Methods that must be called with
686    // this lock held have the prefix "LP".
687    @GuardedBy("mPackages")
688    final ArrayMap<String, PackageParser.Package> mPackages =
689            new ArrayMap<String, PackageParser.Package>();
690
691    final ArrayMap<String, Set<String>> mKnownCodebase =
692            new ArrayMap<String, Set<String>>();
693
694    // Keys are isolated uids and values are the uid of the application
695    // that created the isolated proccess.
696    @GuardedBy("mPackages")
697    final SparseIntArray mIsolatedOwners = new SparseIntArray();
698
699    /**
700     * Tracks new system packages [received in an OTA] that we expect to
701     * find updated user-installed versions. Keys are package name, values
702     * are package location.
703     */
704    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
705    /**
706     * Tracks high priority intent filters for protected actions. During boot, certain
707     * filter actions are protected and should never be allowed to have a high priority
708     * intent filter for them. However, there is one, and only one exception -- the
709     * setup wizard. It must be able to define a high priority intent filter for these
710     * actions to ensure there are no escapes from the wizard. We need to delay processing
711     * of these during boot as we need to look at all of the system packages in order
712     * to know which component is the setup wizard.
713     */
714    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
715    /**
716     * Whether or not processing protected filters should be deferred.
717     */
718    private boolean mDeferProtectedFilters = true;
719
720    /**
721     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
722     */
723    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
724    /**
725     * Whether or not system app permissions should be promoted from install to runtime.
726     */
727    boolean mPromoteSystemApps;
728
729    @GuardedBy("mPackages")
730    final Settings mSettings;
731
732    /**
733     * Set of package names that are currently "frozen", which means active
734     * surgery is being done on the code/data for that package. The platform
735     * will refuse to launch frozen packages to avoid race conditions.
736     *
737     * @see PackageFreezer
738     */
739    @GuardedBy("mPackages")
740    final ArraySet<String> mFrozenPackages = new ArraySet<>();
741
742    final ProtectedPackages mProtectedPackages;
743
744    @GuardedBy("mLoadedVolumes")
745    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
746
747    boolean mFirstBoot;
748
749    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
750
751    // System configuration read by SystemConfig.
752    final int[] mGlobalGids;
753    final SparseArray<ArraySet<String>> mSystemPermissions;
754    @GuardedBy("mAvailableFeatures")
755    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
756
757    // If mac_permissions.xml was found for seinfo labeling.
758    boolean mFoundPolicyFile;
759
760    private final InstantAppRegistry mInstantAppRegistry;
761
762    @GuardedBy("mPackages")
763    int mChangedPackagesSequenceNumber;
764    /**
765     * List of changed [installed, removed or updated] packages.
766     * mapping from user id -> sequence number -> package name
767     */
768    @GuardedBy("mPackages")
769    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
770    /**
771     * The sequence number of the last change to a package.
772     * mapping from user id -> package name -> sequence number
773     */
774    @GuardedBy("mPackages")
775    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
776
777    class PackageParserCallback implements PackageParser.Callback {
778        @Override public final boolean hasFeature(String feature) {
779            return PackageManagerService.this.hasSystemFeature(feature, 0);
780        }
781
782        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
783                Collection<PackageParser.Package> allPackages, String targetPackageName) {
784            List<PackageParser.Package> overlayPackages = null;
785            for (PackageParser.Package p : allPackages) {
786                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
787                    if (overlayPackages == null) {
788                        overlayPackages = new ArrayList<PackageParser.Package>();
789                    }
790                    overlayPackages.add(p);
791                }
792            }
793            if (overlayPackages != null) {
794                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
795                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
796                        return p1.mOverlayPriority - p2.mOverlayPriority;
797                    }
798                };
799                Collections.sort(overlayPackages, cmp);
800            }
801            return overlayPackages;
802        }
803
804        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
805                String targetPackageName, String targetPath) {
806            if ("android".equals(targetPackageName)) {
807                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
808                // native AssetManager.
809                return null;
810            }
811            List<PackageParser.Package> overlayPackages =
812                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
813            if (overlayPackages == null || overlayPackages.isEmpty()) {
814                return null;
815            }
816            List<String> overlayPathList = null;
817            for (PackageParser.Package overlayPackage : overlayPackages) {
818                if (targetPath == null) {
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                    continue;
824                }
825
826                try {
827                    // Creates idmaps for system to parse correctly the Android manifest of the
828                    // target package.
829                    //
830                    // OverlayManagerService will update each of them with a correct gid from its
831                    // target package app id.
832                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
833                            UserHandle.getSharedAppGid(
834                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
835                    if (overlayPathList == null) {
836                        overlayPathList = new ArrayList<String>();
837                    }
838                    overlayPathList.add(overlayPackage.baseCodePath);
839                } catch (InstallerException e) {
840                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
841                            overlayPackage.baseCodePath);
842                }
843            }
844            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
845        }
846
847        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
848            synchronized (mPackages) {
849                return getStaticOverlayPathsLocked(
850                        mPackages.values(), targetPackageName, targetPath);
851            }
852        }
853
854        @Override public final String[] getOverlayApks(String targetPackageName) {
855            return getStaticOverlayPaths(targetPackageName, null);
856        }
857
858        @Override public final String[] getOverlayPaths(String targetPackageName,
859                String targetPath) {
860            return getStaticOverlayPaths(targetPackageName, targetPath);
861        }
862    };
863
864    class ParallelPackageParserCallback extends PackageParserCallback {
865        List<PackageParser.Package> mOverlayPackages = null;
866
867        void findStaticOverlayPackages() {
868            synchronized (mPackages) {
869                for (PackageParser.Package p : mPackages.values()) {
870                    if (p.mIsStaticOverlay) {
871                        if (mOverlayPackages == null) {
872                            mOverlayPackages = new ArrayList<PackageParser.Package>();
873                        }
874                        mOverlayPackages.add(p);
875                    }
876                }
877            }
878        }
879
880        @Override
881        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
882            // We can trust mOverlayPackages without holding mPackages because package uninstall
883            // can't happen while running parallel parsing.
884            // Moreover holding mPackages on each parsing thread causes dead-lock.
885            return mOverlayPackages == null ? null :
886                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
887        }
888    }
889
890    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
891    final ParallelPackageParserCallback mParallelPackageParserCallback =
892            new ParallelPackageParserCallback();
893
894    public static final class SharedLibraryEntry {
895        public final @Nullable String path;
896        public final @Nullable String apk;
897        public final @NonNull SharedLibraryInfo info;
898
899        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
900                String declaringPackageName, int declaringPackageVersionCode) {
901            path = _path;
902            apk = _apk;
903            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
904                    declaringPackageName, declaringPackageVersionCode), null);
905        }
906    }
907
908    // Currently known shared libraries.
909    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
910    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
911            new ArrayMap<>();
912
913    // All available activities, for your resolving pleasure.
914    final ActivityIntentResolver mActivities =
915            new ActivityIntentResolver();
916
917    // All available receivers, for your resolving pleasure.
918    final ActivityIntentResolver mReceivers =
919            new ActivityIntentResolver();
920
921    // All available services, for your resolving pleasure.
922    final ServiceIntentResolver mServices = new ServiceIntentResolver();
923
924    // All available providers, for your resolving pleasure.
925    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
926
927    // Mapping from provider base names (first directory in content URI codePath)
928    // to the provider information.
929    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
930            new ArrayMap<String, PackageParser.Provider>();
931
932    // Mapping from instrumentation class names to info about them.
933    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
934            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
935
936    // Mapping from permission names to info about them.
937    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
938            new ArrayMap<String, PackageParser.PermissionGroup>();
939
940    // Packages whose data we have transfered into another package, thus
941    // should no longer exist.
942    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
943
944    // Broadcast actions that are only available to the system.
945    @GuardedBy("mProtectedBroadcasts")
946    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
947
948    /** List of packages waiting for verification. */
949    final SparseArray<PackageVerificationState> mPendingVerification
950            = new SparseArray<PackageVerificationState>();
951
952    /** Set of packages associated with each app op permission. */
953    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
954
955    final PackageInstallerService mInstallerService;
956
957    private final PackageDexOptimizer mPackageDexOptimizer;
958    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
959    // is used by other apps).
960    private final DexManager mDexManager;
961
962    private AtomicInteger mNextMoveId = new AtomicInteger();
963    private final MoveCallbacks mMoveCallbacks;
964
965    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
966
967    // Cache of users who need badging.
968    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
969
970    /** Token for keys in mPendingVerification. */
971    private int mPendingVerificationToken = 0;
972
973    volatile boolean mSystemReady;
974    volatile boolean mSafeMode;
975    volatile boolean mHasSystemUidErrors;
976    private volatile boolean mEphemeralAppsDisabled;
977
978    ApplicationInfo mAndroidApplication;
979    final ActivityInfo mResolveActivity = new ActivityInfo();
980    final ResolveInfo mResolveInfo = new ResolveInfo();
981    ComponentName mResolveComponentName;
982    PackageParser.Package mPlatformPackage;
983    ComponentName mCustomResolverComponentName;
984
985    boolean mResolverReplaced = false;
986
987    private final @Nullable ComponentName mIntentFilterVerifierComponent;
988    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
989
990    private int mIntentFilterVerificationToken = 0;
991
992    /** The service connection to the ephemeral resolver */
993    final EphemeralResolverConnection mInstantAppResolverConnection;
994    /** Component used to show resolver settings for Instant Apps */
995    final ComponentName mInstantAppResolverSettingsComponent;
996
997    /** Activity used to install instant applications */
998    ActivityInfo mInstantAppInstallerActivity;
999    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1000
1001    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1002            = new SparseArray<IntentFilterVerificationState>();
1003
1004    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1005
1006    // List of packages names to keep cached, even if they are uninstalled for all users
1007    private List<String> mKeepUninstalledPackages;
1008
1009    private UserManagerInternal mUserManagerInternal;
1010
1011    private DeviceIdleController.LocalService mDeviceIdleController;
1012
1013    private File mCacheDir;
1014
1015    private ArraySet<String> mPrivappPermissionsViolations;
1016
1017    private Future<?> mPrepareAppDataFuture;
1018
1019    private static class IFVerificationParams {
1020        PackageParser.Package pkg;
1021        boolean replacing;
1022        int userId;
1023        int verifierUid;
1024
1025        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1026                int _userId, int _verifierUid) {
1027            pkg = _pkg;
1028            replacing = _replacing;
1029            userId = _userId;
1030            replacing = _replacing;
1031            verifierUid = _verifierUid;
1032        }
1033    }
1034
1035    private interface IntentFilterVerifier<T extends IntentFilter> {
1036        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1037                                               T filter, String packageName);
1038        void startVerifications(int userId);
1039        void receiveVerificationResponse(int verificationId);
1040    }
1041
1042    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1043        private Context mContext;
1044        private ComponentName mIntentFilterVerifierComponent;
1045        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1046
1047        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1048            mContext = context;
1049            mIntentFilterVerifierComponent = verifierComponent;
1050        }
1051
1052        private String getDefaultScheme() {
1053            return IntentFilter.SCHEME_HTTPS;
1054        }
1055
1056        @Override
1057        public void startVerifications(int userId) {
1058            // Launch verifications requests
1059            int count = mCurrentIntentFilterVerifications.size();
1060            for (int n=0; n<count; n++) {
1061                int verificationId = mCurrentIntentFilterVerifications.get(n);
1062                final IntentFilterVerificationState ivs =
1063                        mIntentFilterVerificationStates.get(verificationId);
1064
1065                String packageName = ivs.getPackageName();
1066
1067                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1068                final int filterCount = filters.size();
1069                ArraySet<String> domainsSet = new ArraySet<>();
1070                for (int m=0; m<filterCount; m++) {
1071                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1072                    domainsSet.addAll(filter.getHostsList());
1073                }
1074                synchronized (mPackages) {
1075                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1076                            packageName, domainsSet) != null) {
1077                        scheduleWriteSettingsLocked();
1078                    }
1079                }
1080                sendVerificationRequest(verificationId, ivs);
1081            }
1082            mCurrentIntentFilterVerifications.clear();
1083        }
1084
1085        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1086            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1089                    verificationId);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1092                    getDefaultScheme());
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1095                    ivs.getHostsString());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1098                    ivs.getPackageName());
1099            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1100            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1101
1102            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1103            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1104                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1105                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1106
1107            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1108            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1109                    "Sending IntentFilter verification broadcast");
1110        }
1111
1112        public void receiveVerificationResponse(int verificationId) {
1113            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1114
1115            final boolean verified = ivs.isVerified();
1116
1117            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1118            final int count = filters.size();
1119            if (DEBUG_DOMAIN_VERIFICATION) {
1120                Slog.i(TAG, "Received verification response " + verificationId
1121                        + " for " + count + " filters, verified=" + verified);
1122            }
1123            for (int n=0; n<count; n++) {
1124                PackageParser.ActivityIntentInfo filter = filters.get(n);
1125                filter.setVerified(verified);
1126
1127                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1128                        + " verified with result:" + verified + " and hosts:"
1129                        + ivs.getHostsString());
1130            }
1131
1132            mIntentFilterVerificationStates.remove(verificationId);
1133
1134            final String packageName = ivs.getPackageName();
1135            IntentFilterVerificationInfo ivi = null;
1136
1137            synchronized (mPackages) {
1138                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1139            }
1140            if (ivi == null) {
1141                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1142                        + verificationId + " packageName:" + packageName);
1143                return;
1144            }
1145            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1146                    "Updating IntentFilterVerificationInfo for package " + packageName
1147                            +" verificationId:" + verificationId);
1148
1149            synchronized (mPackages) {
1150                if (verified) {
1151                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1152                } else {
1153                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1154                }
1155                scheduleWriteSettingsLocked();
1156
1157                final int userId = ivs.getUserId();
1158                if (userId != UserHandle.USER_ALL) {
1159                    final int userStatus =
1160                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1161
1162                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1163                    boolean needUpdate = false;
1164
1165                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1166                    // already been set by the User thru the Disambiguation dialog
1167                    switch (userStatus) {
1168                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1169                            if (verified) {
1170                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1171                            } else {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1173                            }
1174                            needUpdate = true;
1175                            break;
1176
1177                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1178                            if (verified) {
1179                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1180                                needUpdate = true;
1181                            }
1182                            break;
1183
1184                        default:
1185                            // Nothing to do
1186                    }
1187
1188                    if (needUpdate) {
1189                        mSettings.updateIntentFilterVerificationStatusLPw(
1190                                packageName, updatedStatus, userId);
1191                        scheduleWritePackageRestrictionsLocked(userId);
1192                    }
1193                }
1194            }
1195        }
1196
1197        @Override
1198        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1199                    ActivityIntentInfo filter, String packageName) {
1200            if (!hasValidDomains(filter)) {
1201                return false;
1202            }
1203            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1204            if (ivs == null) {
1205                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1206                        packageName);
1207            }
1208            if (DEBUG_DOMAIN_VERIFICATION) {
1209                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1210            }
1211            ivs.addFilter(filter);
1212            return true;
1213        }
1214
1215        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1216                int userId, int verificationId, String packageName) {
1217            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1218                    verifierUid, userId, packageName);
1219            ivs.setPendingState();
1220            synchronized (mPackages) {
1221                mIntentFilterVerificationStates.append(verificationId, ivs);
1222                mCurrentIntentFilterVerifications.add(verificationId);
1223            }
1224            return ivs;
1225        }
1226    }
1227
1228    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1229        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1230                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1231                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1232    }
1233
1234    // Set of pending broadcasts for aggregating enable/disable of components.
1235    static class PendingPackageBroadcasts {
1236        // for each user id, a map of <package name -> components within that package>
1237        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1238
1239        public PendingPackageBroadcasts() {
1240            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1241        }
1242
1243        public ArrayList<String> get(int userId, String packageName) {
1244            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1245            return packages.get(packageName);
1246        }
1247
1248        public void put(int userId, String packageName, ArrayList<String> components) {
1249            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1250            packages.put(packageName, components);
1251        }
1252
1253        public void remove(int userId, String packageName) {
1254            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1255            if (packages != null) {
1256                packages.remove(packageName);
1257            }
1258        }
1259
1260        public void remove(int userId) {
1261            mUidMap.remove(userId);
1262        }
1263
1264        public int userIdCount() {
1265            return mUidMap.size();
1266        }
1267
1268        public int userIdAt(int n) {
1269            return mUidMap.keyAt(n);
1270        }
1271
1272        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1273            return mUidMap.get(userId);
1274        }
1275
1276        public int size() {
1277            // total number of pending broadcast entries across all userIds
1278            int num = 0;
1279            for (int i = 0; i< mUidMap.size(); i++) {
1280                num += mUidMap.valueAt(i).size();
1281            }
1282            return num;
1283        }
1284
1285        public void clear() {
1286            mUidMap.clear();
1287        }
1288
1289        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1290            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1291            if (map == null) {
1292                map = new ArrayMap<String, ArrayList<String>>();
1293                mUidMap.put(userId, map);
1294            }
1295            return map;
1296        }
1297    }
1298    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1299
1300    // Service Connection to remote media container service to copy
1301    // package uri's from external media onto secure containers
1302    // or internal storage.
1303    private IMediaContainerService mContainerService = null;
1304
1305    static final int SEND_PENDING_BROADCAST = 1;
1306    static final int MCS_BOUND = 3;
1307    static final int END_COPY = 4;
1308    static final int INIT_COPY = 5;
1309    static final int MCS_UNBIND = 6;
1310    static final int START_CLEANING_PACKAGE = 7;
1311    static final int FIND_INSTALL_LOC = 8;
1312    static final int POST_INSTALL = 9;
1313    static final int MCS_RECONNECT = 10;
1314    static final int MCS_GIVE_UP = 11;
1315    static final int UPDATED_MEDIA_STATUS = 12;
1316    static final int WRITE_SETTINGS = 13;
1317    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1318    static final int PACKAGE_VERIFIED = 15;
1319    static final int CHECK_PENDING_VERIFICATION = 16;
1320    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1321    static final int INTENT_FILTER_VERIFIED = 18;
1322    static final int WRITE_PACKAGE_LIST = 19;
1323    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1324
1325    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1326
1327    // Delay time in millisecs
1328    static final int BROADCAST_DELAY = 10 * 1000;
1329
1330    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1331            2 * 60 * 60 * 1000L; /* two hours */
1332
1333    static UserManagerService sUserManager;
1334
1335    // Stores a list of users whose package restrictions file needs to be updated
1336    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1337
1338    final private DefaultContainerConnection mDefContainerConn =
1339            new DefaultContainerConnection();
1340    class DefaultContainerConnection implements ServiceConnection {
1341        public void onServiceConnected(ComponentName name, IBinder service) {
1342            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1343            final IMediaContainerService imcs = IMediaContainerService.Stub
1344                    .asInterface(Binder.allowBlocking(service));
1345            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1346        }
1347
1348        public void onServiceDisconnected(ComponentName name) {
1349            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1350        }
1351    }
1352
1353    // Recordkeeping of restore-after-install operations that are currently in flight
1354    // between the Package Manager and the Backup Manager
1355    static class PostInstallData {
1356        public InstallArgs args;
1357        public PackageInstalledInfo res;
1358
1359        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1360            args = _a;
1361            res = _r;
1362        }
1363    }
1364
1365    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1366    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1367
1368    // XML tags for backup/restore of various bits of state
1369    private static final String TAG_PREFERRED_BACKUP = "pa";
1370    private static final String TAG_DEFAULT_APPS = "da";
1371    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1372
1373    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1374    private static final String TAG_ALL_GRANTS = "rt-grants";
1375    private static final String TAG_GRANT = "grant";
1376    private static final String ATTR_PACKAGE_NAME = "pkg";
1377
1378    private static final String TAG_PERMISSION = "perm";
1379    private static final String ATTR_PERMISSION_NAME = "name";
1380    private static final String ATTR_IS_GRANTED = "g";
1381    private static final String ATTR_USER_SET = "set";
1382    private static final String ATTR_USER_FIXED = "fixed";
1383    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1384
1385    // System/policy permission grants are not backed up
1386    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1387            FLAG_PERMISSION_POLICY_FIXED
1388            | FLAG_PERMISSION_SYSTEM_FIXED
1389            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1390
1391    // And we back up these user-adjusted states
1392    private static final int USER_RUNTIME_GRANT_MASK =
1393            FLAG_PERMISSION_USER_SET
1394            | FLAG_PERMISSION_USER_FIXED
1395            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1396
1397    final @Nullable String mRequiredVerifierPackage;
1398    final @NonNull String mRequiredInstallerPackage;
1399    final @NonNull String mRequiredUninstallerPackage;
1400    final @Nullable String mSetupWizardPackage;
1401    final @Nullable String mStorageManagerPackage;
1402    final @NonNull String mServicesSystemSharedLibraryPackageName;
1403    final @NonNull String mSharedSystemSharedLibraryPackageName;
1404
1405    final boolean mPermissionReviewRequired;
1406
1407    private final PackageUsage mPackageUsage = new PackageUsage();
1408    private final CompilerStats mCompilerStats = new CompilerStats();
1409
1410    class PackageHandler extends Handler {
1411        private boolean mBound = false;
1412        final ArrayList<HandlerParams> mPendingInstalls =
1413            new ArrayList<HandlerParams>();
1414
1415        private boolean connectToService() {
1416            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1417                    " DefaultContainerService");
1418            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1421                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1422                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423                mBound = true;
1424                return true;
1425            }
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427            return false;
1428        }
1429
1430        private void disconnectService() {
1431            mContainerService = null;
1432            mBound = false;
1433            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1434            mContext.unbindService(mDefContainerConn);
1435            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436        }
1437
1438        PackageHandler(Looper looper) {
1439            super(looper);
1440        }
1441
1442        public void handleMessage(Message msg) {
1443            try {
1444                doHandleMessage(msg);
1445            } finally {
1446                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1447            }
1448        }
1449
1450        void doHandleMessage(Message msg) {
1451            switch (msg.what) {
1452                case INIT_COPY: {
1453                    HandlerParams params = (HandlerParams) msg.obj;
1454                    int idx = mPendingInstalls.size();
1455                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1456                    // If a bind was already initiated we dont really
1457                    // need to do anything. The pending install
1458                    // will be processed later on.
1459                    if (!mBound) {
1460                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1461                                System.identityHashCode(mHandler));
1462                        // If this is the only one pending we might
1463                        // have to bind to the service again.
1464                        if (!connectToService()) {
1465                            Slog.e(TAG, "Failed to bind to media container service");
1466                            params.serviceError();
1467                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1468                                    System.identityHashCode(mHandler));
1469                            if (params.traceMethod != null) {
1470                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1471                                        params.traceCookie);
1472                            }
1473                            return;
1474                        } else {
1475                            // Once we bind to the service, the first
1476                            // pending request will be processed.
1477                            mPendingInstalls.add(idx, params);
1478                        }
1479                    } else {
1480                        mPendingInstalls.add(idx, params);
1481                        // Already bound to the service. Just make
1482                        // sure we trigger off processing the first request.
1483                        if (idx == 0) {
1484                            mHandler.sendEmptyMessage(MCS_BOUND);
1485                        }
1486                    }
1487                    break;
1488                }
1489                case MCS_BOUND: {
1490                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1491                    if (msg.obj != null) {
1492                        mContainerService = (IMediaContainerService) msg.obj;
1493                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1494                                System.identityHashCode(mHandler));
1495                    }
1496                    if (mContainerService == null) {
1497                        if (!mBound) {
1498                            // Something seriously wrong since we are not bound and we are not
1499                            // waiting for connection. Bail out.
1500                            Slog.e(TAG, "Cannot bind to media container service");
1501                            for (HandlerParams params : mPendingInstalls) {
1502                                // Indicate service bind error
1503                                params.serviceError();
1504                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1505                                        System.identityHashCode(params));
1506                                if (params.traceMethod != null) {
1507                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1508                                            params.traceMethod, params.traceCookie);
1509                                }
1510                                return;
1511                            }
1512                            mPendingInstalls.clear();
1513                        } else {
1514                            Slog.w(TAG, "Waiting to connect to media container service");
1515                        }
1516                    } else if (mPendingInstalls.size() > 0) {
1517                        HandlerParams params = mPendingInstalls.get(0);
1518                        if (params != null) {
1519                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1520                                    System.identityHashCode(params));
1521                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1522                            if (params.startCopy()) {
1523                                // We are done...  look for more work or to
1524                                // go idle.
1525                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1526                                        "Checking for more work or unbind...");
1527                                // Delete pending install
1528                                if (mPendingInstalls.size() > 0) {
1529                                    mPendingInstalls.remove(0);
1530                                }
1531                                if (mPendingInstalls.size() == 0) {
1532                                    if (mBound) {
1533                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1534                                                "Posting delayed MCS_UNBIND");
1535                                        removeMessages(MCS_UNBIND);
1536                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1537                                        // Unbind after a little delay, to avoid
1538                                        // continual thrashing.
1539                                        sendMessageDelayed(ubmsg, 10000);
1540                                    }
1541                                } else {
1542                                    // There are more pending requests in queue.
1543                                    // Just post MCS_BOUND message to trigger processing
1544                                    // of next pending install.
1545                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1546                                            "Posting MCS_BOUND for next work");
1547                                    mHandler.sendEmptyMessage(MCS_BOUND);
1548                                }
1549                            }
1550                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1551                        }
1552                    } else {
1553                        // Should never happen ideally.
1554                        Slog.w(TAG, "Empty queue");
1555                    }
1556                    break;
1557                }
1558                case MCS_RECONNECT: {
1559                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1560                    if (mPendingInstalls.size() > 0) {
1561                        if (mBound) {
1562                            disconnectService();
1563                        }
1564                        if (!connectToService()) {
1565                            Slog.e(TAG, "Failed to bind to media container service");
1566                            for (HandlerParams params : mPendingInstalls) {
1567                                // Indicate service bind error
1568                                params.serviceError();
1569                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1570                                        System.identityHashCode(params));
1571                            }
1572                            mPendingInstalls.clear();
1573                        }
1574                    }
1575                    break;
1576                }
1577                case MCS_UNBIND: {
1578                    // If there is no actual work left, then time to unbind.
1579                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1580
1581                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1582                        if (mBound) {
1583                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1584
1585                            disconnectService();
1586                        }
1587                    } else if (mPendingInstalls.size() > 0) {
1588                        // There are more pending requests in queue.
1589                        // Just post MCS_BOUND message to trigger processing
1590                        // of next pending install.
1591                        mHandler.sendEmptyMessage(MCS_BOUND);
1592                    }
1593
1594                    break;
1595                }
1596                case MCS_GIVE_UP: {
1597                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1598                    HandlerParams params = mPendingInstalls.remove(0);
1599                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1600                            System.identityHashCode(params));
1601                    break;
1602                }
1603                case SEND_PENDING_BROADCAST: {
1604                    String packages[];
1605                    ArrayList<String> components[];
1606                    int size = 0;
1607                    int uids[];
1608                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1609                    synchronized (mPackages) {
1610                        if (mPendingBroadcasts == null) {
1611                            return;
1612                        }
1613                        size = mPendingBroadcasts.size();
1614                        if (size <= 0) {
1615                            // Nothing to be done. Just return
1616                            return;
1617                        }
1618                        packages = new String[size];
1619                        components = new ArrayList[size];
1620                        uids = new int[size];
1621                        int i = 0;  // filling out the above arrays
1622
1623                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1624                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1625                            Iterator<Map.Entry<String, ArrayList<String>>> it
1626                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1627                                            .entrySet().iterator();
1628                            while (it.hasNext() && i < size) {
1629                                Map.Entry<String, ArrayList<String>> ent = it.next();
1630                                packages[i] = ent.getKey();
1631                                components[i] = ent.getValue();
1632                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1633                                uids[i] = (ps != null)
1634                                        ? UserHandle.getUid(packageUserId, ps.appId)
1635                                        : -1;
1636                                i++;
1637                            }
1638                        }
1639                        size = i;
1640                        mPendingBroadcasts.clear();
1641                    }
1642                    // Send broadcasts
1643                    for (int i = 0; i < size; i++) {
1644                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1645                    }
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1647                    break;
1648                }
1649                case START_CLEANING_PACKAGE: {
1650                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1651                    final String packageName = (String)msg.obj;
1652                    final int userId = msg.arg1;
1653                    final boolean andCode = msg.arg2 != 0;
1654                    synchronized (mPackages) {
1655                        if (userId == UserHandle.USER_ALL) {
1656                            int[] users = sUserManager.getUserIds();
1657                            for (int user : users) {
1658                                mSettings.addPackageToCleanLPw(
1659                                        new PackageCleanItem(user, packageName, andCode));
1660                            }
1661                        } else {
1662                            mSettings.addPackageToCleanLPw(
1663                                    new PackageCleanItem(userId, packageName, andCode));
1664                        }
1665                    }
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1667                    startCleaningPackages();
1668                } break;
1669                case POST_INSTALL: {
1670                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1671
1672                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1673                    final boolean didRestore = (msg.arg2 != 0);
1674                    mRunningInstalls.delete(msg.arg1);
1675
1676                    if (data != null) {
1677                        InstallArgs args = data.args;
1678                        PackageInstalledInfo parentRes = data.res;
1679
1680                        final boolean grantPermissions = (args.installFlags
1681                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1682                        final boolean killApp = (args.installFlags
1683                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1684                        final boolean virtualPreload = ((args.installFlags
1685                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1686                        final String[] grantedPermissions = args.installGrantPermissions;
1687
1688                        // Handle the parent package
1689                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1690                                virtualPreload, grantedPermissions, didRestore,
1691                                args.installerPackageName, args.observer);
1692
1693                        // Handle the child packages
1694                        final int childCount = (parentRes.addedChildPackages != null)
1695                                ? parentRes.addedChildPackages.size() : 0;
1696                        for (int i = 0; i < childCount; i++) {
1697                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1698                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1699                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1700                                    args.installerPackageName, args.observer);
1701                        }
1702
1703                        // Log tracing if needed
1704                        if (args.traceMethod != null) {
1705                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1706                                    args.traceCookie);
1707                        }
1708                    } else {
1709                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1710                    }
1711
1712                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1713                } break;
1714                case UPDATED_MEDIA_STATUS: {
1715                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1716                    boolean reportStatus = msg.arg1 == 1;
1717                    boolean doGc = msg.arg2 == 1;
1718                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1719                    if (doGc) {
1720                        // Force a gc to clear up stale containers.
1721                        Runtime.getRuntime().gc();
1722                    }
1723                    if (msg.obj != null) {
1724                        @SuppressWarnings("unchecked")
1725                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1726                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1727                        // Unload containers
1728                        unloadAllContainers(args);
1729                    }
1730                    if (reportStatus) {
1731                        try {
1732                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1733                                    "Invoking StorageManagerService call back");
1734                            PackageHelper.getStorageManager().finishMediaUpdate();
1735                        } catch (RemoteException e) {
1736                            Log.e(TAG, "StorageManagerService not running?");
1737                        }
1738                    }
1739                } break;
1740                case WRITE_SETTINGS: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_SETTINGS);
1744                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1745                        mSettings.writeLPr();
1746                        mDirtyUsers.clear();
1747                    }
1748                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1749                } break;
1750                case WRITE_PACKAGE_RESTRICTIONS: {
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1752                    synchronized (mPackages) {
1753                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1754                        for (int userId : mDirtyUsers) {
1755                            mSettings.writePackageRestrictionsLPr(userId);
1756                        }
1757                        mDirtyUsers.clear();
1758                    }
1759                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1760                } break;
1761                case WRITE_PACKAGE_LIST: {
1762                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1763                    synchronized (mPackages) {
1764                        removeMessages(WRITE_PACKAGE_LIST);
1765                        mSettings.writePackageListLPr(msg.arg1);
1766                    }
1767                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1768                } break;
1769                case CHECK_PENDING_VERIFICATION: {
1770                    final int verificationId = msg.arg1;
1771                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1772
1773                    if ((state != null) && !state.timeoutExtended()) {
1774                        final InstallArgs args = state.getInstallArgs();
1775                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1776
1777                        Slog.i(TAG, "Verification timed out for " + originUri);
1778                        mPendingVerification.remove(verificationId);
1779
1780                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1781
1782                        final UserHandle user = args.getUser();
1783                        if (getDefaultVerificationResponse(user)
1784                                == PackageManager.VERIFICATION_ALLOW) {
1785                            Slog.i(TAG, "Continuing with installation of " + originUri);
1786                            state.setVerifierResponse(Binder.getCallingUid(),
1787                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1788                            broadcastPackageVerified(verificationId, originUri,
1789                                    PackageManager.VERIFICATION_ALLOW, user);
1790                            try {
1791                                ret = args.copyApk(mContainerService, true);
1792                            } catch (RemoteException e) {
1793                                Slog.e(TAG, "Could not contact the ContainerService");
1794                            }
1795                        } else {
1796                            broadcastPackageVerified(verificationId, originUri,
1797                                    PackageManager.VERIFICATION_REJECT, user);
1798                        }
1799
1800                        Trace.asyncTraceEnd(
1801                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1802
1803                        processPendingInstall(args, ret);
1804                        mHandler.sendEmptyMessage(MCS_UNBIND);
1805                    }
1806                    break;
1807                }
1808                case PACKAGE_VERIFIED: {
1809                    final int verificationId = msg.arg1;
1810
1811                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1812                    if (state == null) {
1813                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1814                        break;
1815                    }
1816
1817                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1818
1819                    state.setVerifierResponse(response.callerUid, response.code);
1820
1821                    if (state.isVerificationComplete()) {
1822                        mPendingVerification.remove(verificationId);
1823
1824                        final InstallArgs args = state.getInstallArgs();
1825                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1826
1827                        int ret;
1828                        if (state.isInstallAllowed()) {
1829                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1830                            broadcastPackageVerified(verificationId, originUri,
1831                                    response.code, state.getInstallArgs().getUser());
1832                            try {
1833                                ret = args.copyApk(mContainerService, true);
1834                            } catch (RemoteException e) {
1835                                Slog.e(TAG, "Could not contact the ContainerService");
1836                            }
1837                        } else {
1838                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1839                        }
1840
1841                        Trace.asyncTraceEnd(
1842                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1843
1844                        processPendingInstall(args, ret);
1845                        mHandler.sendEmptyMessage(MCS_UNBIND);
1846                    }
1847
1848                    break;
1849                }
1850                case START_INTENT_FILTER_VERIFICATIONS: {
1851                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1852                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1853                            params.replacing, params.pkg);
1854                    break;
1855                }
1856                case INTENT_FILTER_VERIFIED: {
1857                    final int verificationId = msg.arg1;
1858
1859                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1860                            verificationId);
1861                    if (state == null) {
1862                        Slog.w(TAG, "Invalid IntentFilter verification token "
1863                                + verificationId + " received");
1864                        break;
1865                    }
1866
1867                    final int userId = state.getUserId();
1868
1869                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1870                            "Processing IntentFilter verification with token:"
1871                            + verificationId + " and userId:" + userId);
1872
1873                    final IntentFilterVerificationResponse response =
1874                            (IntentFilterVerificationResponse) msg.obj;
1875
1876                    state.setVerifierResponse(response.callerUid, response.code);
1877
1878                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1879                            "IntentFilter verification with token:" + verificationId
1880                            + " and userId:" + userId
1881                            + " is settings verifier response with response code:"
1882                            + response.code);
1883
1884                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1885                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1886                                + response.getFailedDomainsString());
1887                    }
1888
1889                    if (state.isVerificationComplete()) {
1890                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1891                    } else {
1892                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1893                                "IntentFilter verification with token:" + verificationId
1894                                + " was not said to be complete");
1895                    }
1896
1897                    break;
1898                }
1899                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1900                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1901                            mInstantAppResolverConnection,
1902                            (InstantAppRequest) msg.obj,
1903                            mInstantAppInstallerActivity,
1904                            mHandler);
1905                }
1906            }
1907        }
1908    }
1909
1910    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1911            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1912            boolean launchedForRestore, String installerPackage,
1913            IPackageInstallObserver2 installObserver) {
1914        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1915            // Send the removed broadcasts
1916            if (res.removedInfo != null) {
1917                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1918            }
1919
1920            // Now that we successfully installed the package, grant runtime
1921            // permissions if requested before broadcasting the install. Also
1922            // for legacy apps in permission review mode we clear the permission
1923            // review flag which is used to emulate runtime permissions for
1924            // legacy apps.
1925            if (grantPermissions) {
1926                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1927            }
1928
1929            final boolean update = res.removedInfo != null
1930                    && res.removedInfo.removedPackage != null;
1931            final String origInstallerPackageName = res.removedInfo != null
1932                    ? res.removedInfo.installerPackageName : null;
1933
1934            // If this is the first time we have child packages for a disabled privileged
1935            // app that had no children, we grant requested runtime permissions to the new
1936            // children if the parent on the system image had them already granted.
1937            if (res.pkg.parentPackage != null) {
1938                synchronized (mPackages) {
1939                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1940                }
1941            }
1942
1943            synchronized (mPackages) {
1944                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1945            }
1946
1947            final String packageName = res.pkg.applicationInfo.packageName;
1948
1949            // Determine the set of users who are adding this package for
1950            // the first time vs. those who are seeing an update.
1951            int[] firstUsers = EMPTY_INT_ARRAY;
1952            int[] updateUsers = EMPTY_INT_ARRAY;
1953            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1954            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1955            for (int newUser : res.newUsers) {
1956                if (ps.getInstantApp(newUser)) {
1957                    continue;
1958                }
1959                if (allNewUsers) {
1960                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1961                    continue;
1962                }
1963                boolean isNew = true;
1964                for (int origUser : res.origUsers) {
1965                    if (origUser == newUser) {
1966                        isNew = false;
1967                        break;
1968                    }
1969                }
1970                if (isNew) {
1971                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1972                } else {
1973                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1974                }
1975            }
1976
1977            // Send installed broadcasts if the package is not a static shared lib.
1978            if (res.pkg.staticSharedLibName == null) {
1979                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1980
1981                // Send added for users that see the package for the first time
1982                // sendPackageAddedForNewUsers also deals with system apps
1983                int appId = UserHandle.getAppId(res.uid);
1984                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1985                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1986                        virtualPreload /*startReceiver*/, appId, firstUsers);
1987
1988                // Send added for users that don't see the package for the first time
1989                Bundle extras = new Bundle(1);
1990                extras.putInt(Intent.EXTRA_UID, res.uid);
1991                if (update) {
1992                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1993                }
1994                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1995                        extras, 0 /*flags*/,
1996                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1997                if (origInstallerPackageName != null) {
1998                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1999                            extras, 0 /*flags*/,
2000                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2001                }
2002
2003                // Send replaced for users that don't see the package for the first time
2004                if (update) {
2005                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2006                            packageName, extras, 0 /*flags*/,
2007                            null /*targetPackage*/, null /*finishedReceiver*/,
2008                            updateUsers);
2009                    if (origInstallerPackageName != null) {
2010                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2011                                extras, 0 /*flags*/,
2012                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2013                    }
2014                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2015                            null /*package*/, null /*extras*/, 0 /*flags*/,
2016                            packageName /*targetPackage*/,
2017                            null /*finishedReceiver*/, updateUsers);
2018                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2019                    // First-install and we did a restore, so we're responsible for the
2020                    // first-launch broadcast.
2021                    if (DEBUG_BACKUP) {
2022                        Slog.i(TAG, "Post-restore of " + packageName
2023                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2024                    }
2025                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2026                }
2027
2028                // Send broadcast package appeared if forward locked/external for all users
2029                // treat asec-hosted packages like removable media on upgrade
2030                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2031                    if (DEBUG_INSTALL) {
2032                        Slog.i(TAG, "upgrading pkg " + res.pkg
2033                                + " is ASEC-hosted -> AVAILABLE");
2034                    }
2035                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2036                    ArrayList<String> pkgList = new ArrayList<>(1);
2037                    pkgList.add(packageName);
2038                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2039                }
2040            }
2041
2042            // Work that needs to happen on first install within each user
2043            if (firstUsers != null && firstUsers.length > 0) {
2044                synchronized (mPackages) {
2045                    for (int userId : firstUsers) {
2046                        // If this app is a browser and it's newly-installed for some
2047                        // users, clear any default-browser state in those users. The
2048                        // app's nature doesn't depend on the user, so we can just check
2049                        // its browser nature in any user and generalize.
2050                        if (packageIsBrowser(packageName, userId)) {
2051                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2052                        }
2053
2054                        // We may also need to apply pending (restored) runtime
2055                        // permission grants within these users.
2056                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2057                    }
2058                }
2059            }
2060
2061            // Log current value of "unknown sources" setting
2062            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2063                    getUnknownSourcesSettings());
2064
2065            // Remove the replaced package's older resources safely now
2066            // We delete after a gc for applications  on sdcard.
2067            if (res.removedInfo != null && res.removedInfo.args != null) {
2068                Runtime.getRuntime().gc();
2069                synchronized (mInstallLock) {
2070                    res.removedInfo.args.doPostDeleteLI(true);
2071                }
2072            } else {
2073                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2074                // and not block here.
2075                VMRuntime.getRuntime().requestConcurrentGC();
2076            }
2077
2078            // Notify DexManager that the package was installed for new users.
2079            // The updated users should already be indexed and the package code paths
2080            // should not change.
2081            // Don't notify the manager for ephemeral apps as they are not expected to
2082            // survive long enough to benefit of background optimizations.
2083            for (int userId : firstUsers) {
2084                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2085                // There's a race currently where some install events may interleave with an uninstall.
2086                // This can lead to package info being null (b/36642664).
2087                if (info != null) {
2088                    mDexManager.notifyPackageInstalled(info, userId);
2089                }
2090            }
2091        }
2092
2093        // If someone is watching installs - notify them
2094        if (installObserver != null) {
2095            try {
2096                Bundle extras = extrasForInstallResult(res);
2097                installObserver.onPackageInstalled(res.name, res.returnCode,
2098                        res.returnMsg, extras);
2099            } catch (RemoteException e) {
2100                Slog.i(TAG, "Observer no longer exists.");
2101            }
2102        }
2103    }
2104
2105    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2106            PackageParser.Package pkg) {
2107        if (pkg.parentPackage == null) {
2108            return;
2109        }
2110        if (pkg.requestedPermissions == null) {
2111            return;
2112        }
2113        final PackageSetting disabledSysParentPs = mSettings
2114                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2115        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2116                || !disabledSysParentPs.isPrivileged()
2117                || (disabledSysParentPs.childPackageNames != null
2118                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2119            return;
2120        }
2121        final int[] allUserIds = sUserManager.getUserIds();
2122        final int permCount = pkg.requestedPermissions.size();
2123        for (int i = 0; i < permCount; i++) {
2124            String permission = pkg.requestedPermissions.get(i);
2125            BasePermission bp = mSettings.mPermissions.get(permission);
2126            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2127                continue;
2128            }
2129            for (int userId : allUserIds) {
2130                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2131                        permission, userId)) {
2132                    grantRuntimePermission(pkg.packageName, permission, userId);
2133                }
2134            }
2135        }
2136    }
2137
2138    private StorageEventListener mStorageListener = new StorageEventListener() {
2139        @Override
2140        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2141            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2142                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2143                    final String volumeUuid = vol.getFsUuid();
2144
2145                    // Clean up any users or apps that were removed or recreated
2146                    // while this volume was missing
2147                    sUserManager.reconcileUsers(volumeUuid);
2148                    reconcileApps(volumeUuid);
2149
2150                    // Clean up any install sessions that expired or were
2151                    // cancelled while this volume was missing
2152                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2153
2154                    loadPrivatePackages(vol);
2155
2156                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2157                    unloadPrivatePackages(vol);
2158                }
2159            }
2160
2161            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2162                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2163                    updateExternalMediaStatus(true, false);
2164                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2165                    updateExternalMediaStatus(false, false);
2166                }
2167            }
2168        }
2169
2170        @Override
2171        public void onVolumeForgotten(String fsUuid) {
2172            if (TextUtils.isEmpty(fsUuid)) {
2173                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2174                return;
2175            }
2176
2177            // Remove any apps installed on the forgotten volume
2178            synchronized (mPackages) {
2179                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2180                for (PackageSetting ps : packages) {
2181                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2182                    deletePackageVersioned(new VersionedPackage(ps.name,
2183                            PackageManager.VERSION_CODE_HIGHEST),
2184                            new LegacyPackageDeleteObserver(null).getBinder(),
2185                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2186                    // Try very hard to release any references to this package
2187                    // so we don't risk the system server being killed due to
2188                    // open FDs
2189                    AttributeCache.instance().removePackage(ps.name);
2190                }
2191
2192                mSettings.onVolumeForgotten(fsUuid);
2193                mSettings.writeLPr();
2194            }
2195        }
2196    };
2197
2198    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2199            String[] grantedPermissions) {
2200        for (int userId : userIds) {
2201            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2202        }
2203    }
2204
2205    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2206            String[] grantedPermissions) {
2207        PackageSetting ps = (PackageSetting) pkg.mExtras;
2208        if (ps == null) {
2209            return;
2210        }
2211
2212        PermissionsState permissionsState = ps.getPermissionsState();
2213
2214        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2215                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2216
2217        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2218                >= Build.VERSION_CODES.M;
2219
2220        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2221
2222        for (String permission : pkg.requestedPermissions) {
2223            final BasePermission bp;
2224            synchronized (mPackages) {
2225                bp = mSettings.mPermissions.get(permission);
2226            }
2227            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2228                    && (!instantApp || bp.isInstant())
2229                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2230                    && (grantedPermissions == null
2231                           || ArrayUtils.contains(grantedPermissions, permission))) {
2232                final int flags = permissionsState.getPermissionFlags(permission, userId);
2233                if (supportsRuntimePermissions) {
2234                    // Installer cannot change immutable permissions.
2235                    if ((flags & immutableFlags) == 0) {
2236                        grantRuntimePermission(pkg.packageName, permission, userId);
2237                    }
2238                } else if (mPermissionReviewRequired) {
2239                    // In permission review mode we clear the review flag when we
2240                    // are asked to install the app with all permissions granted.
2241                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2242                        updatePermissionFlags(permission, pkg.packageName,
2243                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2244                    }
2245                }
2246            }
2247        }
2248    }
2249
2250    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2251        Bundle extras = null;
2252        switch (res.returnCode) {
2253            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2254                extras = new Bundle();
2255                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2256                        res.origPermission);
2257                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2258                        res.origPackage);
2259                break;
2260            }
2261            case PackageManager.INSTALL_SUCCEEDED: {
2262                extras = new Bundle();
2263                extras.putBoolean(Intent.EXTRA_REPLACING,
2264                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2265                break;
2266            }
2267        }
2268        return extras;
2269    }
2270
2271    void scheduleWriteSettingsLocked() {
2272        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2273            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2274        }
2275    }
2276
2277    void scheduleWritePackageListLocked(int userId) {
2278        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2279            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2280            msg.arg1 = userId;
2281            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2282        }
2283    }
2284
2285    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2286        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2287        scheduleWritePackageRestrictionsLocked(userId);
2288    }
2289
2290    void scheduleWritePackageRestrictionsLocked(int userId) {
2291        final int[] userIds = (userId == UserHandle.USER_ALL)
2292                ? sUserManager.getUserIds() : new int[]{userId};
2293        for (int nextUserId : userIds) {
2294            if (!sUserManager.exists(nextUserId)) return;
2295            mDirtyUsers.add(nextUserId);
2296            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2297                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2298            }
2299        }
2300    }
2301
2302    public static PackageManagerService main(Context context, Installer installer,
2303            boolean factoryTest, boolean onlyCore) {
2304        // Self-check for initial settings.
2305        PackageManagerServiceCompilerMapping.checkProperties();
2306
2307        PackageManagerService m = new PackageManagerService(context, installer,
2308                factoryTest, onlyCore);
2309        m.enableSystemUserPackages();
2310        ServiceManager.addService("package", m);
2311        final PackageManagerNative pmn = m.new PackageManagerNative();
2312        ServiceManager.addService("package_native", pmn);
2313        return m;
2314    }
2315
2316    private void enableSystemUserPackages() {
2317        if (!UserManager.isSplitSystemUser()) {
2318            return;
2319        }
2320        // For system user, enable apps based on the following conditions:
2321        // - app is whitelisted or belong to one of these groups:
2322        //   -- system app which has no launcher icons
2323        //   -- system app which has INTERACT_ACROSS_USERS permission
2324        //   -- system IME app
2325        // - app is not in the blacklist
2326        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2327        Set<String> enableApps = new ArraySet<>();
2328        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2329                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2330                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2331        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2332        enableApps.addAll(wlApps);
2333        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2334                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2335        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2336        enableApps.removeAll(blApps);
2337        Log.i(TAG, "Applications installed for system user: " + enableApps);
2338        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2339                UserHandle.SYSTEM);
2340        final int allAppsSize = allAps.size();
2341        synchronized (mPackages) {
2342            for (int i = 0; i < allAppsSize; i++) {
2343                String pName = allAps.get(i);
2344                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2345                // Should not happen, but we shouldn't be failing if it does
2346                if (pkgSetting == null) {
2347                    continue;
2348                }
2349                boolean install = enableApps.contains(pName);
2350                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2351                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2352                            + " for system user");
2353                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2354                }
2355            }
2356            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2357        }
2358    }
2359
2360    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2361        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2362                Context.DISPLAY_SERVICE);
2363        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2364    }
2365
2366    /**
2367     * Requests that files preopted on a secondary system partition be copied to the data partition
2368     * if possible.  Note that the actual copying of the files is accomplished by init for security
2369     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2370     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2371     */
2372    private static void requestCopyPreoptedFiles() {
2373        final int WAIT_TIME_MS = 100;
2374        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2375        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2376            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2377            // We will wait for up to 100 seconds.
2378            final long timeStart = SystemClock.uptimeMillis();
2379            final long timeEnd = timeStart + 100 * 1000;
2380            long timeNow = timeStart;
2381            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2382                try {
2383                    Thread.sleep(WAIT_TIME_MS);
2384                } catch (InterruptedException e) {
2385                    // Do nothing
2386                }
2387                timeNow = SystemClock.uptimeMillis();
2388                if (timeNow > timeEnd) {
2389                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2390                    Slog.wtf(TAG, "cppreopt did not finish!");
2391                    break;
2392                }
2393            }
2394
2395            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2396        }
2397    }
2398
2399    public PackageManagerService(Context context, Installer installer,
2400            boolean factoryTest, boolean onlyCore) {
2401        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2402        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2403        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2404                SystemClock.uptimeMillis());
2405
2406        if (mSdkVersion <= 0) {
2407            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2408        }
2409
2410        mContext = context;
2411
2412        mPermissionReviewRequired = context.getResources().getBoolean(
2413                R.bool.config_permissionReviewRequired);
2414
2415        mFactoryTest = factoryTest;
2416        mOnlyCore = onlyCore;
2417        mMetrics = new DisplayMetrics();
2418        mSettings = new Settings(mPackages);
2419        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2420                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2421        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431
2432        String separateProcesses = SystemProperties.get("debug.separate_processes");
2433        if (separateProcesses != null && separateProcesses.length() > 0) {
2434            if ("*".equals(separateProcesses)) {
2435                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2436                mSeparateProcesses = null;
2437                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2438            } else {
2439                mDefParseFlags = 0;
2440                mSeparateProcesses = separateProcesses.split(",");
2441                Slog.w(TAG, "Running with debug.separate_processes: "
2442                        + separateProcesses);
2443            }
2444        } else {
2445            mDefParseFlags = 0;
2446            mSeparateProcesses = null;
2447        }
2448
2449        mInstaller = installer;
2450        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2451                "*dexopt*");
2452        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2453        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2454
2455        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2456                FgThread.get().getLooper());
2457
2458        getDefaultDisplayMetrics(context, mMetrics);
2459
2460        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2461        SystemConfig systemConfig = SystemConfig.getInstance();
2462        mGlobalGids = systemConfig.getGlobalGids();
2463        mSystemPermissions = systemConfig.getSystemPermissions();
2464        mAvailableFeatures = systemConfig.getAvailableFeatures();
2465        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2466
2467        mProtectedPackages = new ProtectedPackages(mContext);
2468
2469        synchronized (mInstallLock) {
2470        // writer
2471        synchronized (mPackages) {
2472            mHandlerThread = new ServiceThread(TAG,
2473                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2474            mHandlerThread.start();
2475            mHandler = new PackageHandler(mHandlerThread.getLooper());
2476            mProcessLoggingHandler = new ProcessLoggingHandler();
2477            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2478
2479            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2480            mInstantAppRegistry = new InstantAppRegistry(this);
2481
2482            File dataDir = Environment.getDataDirectory();
2483            mAppInstallDir = new File(dataDir, "app");
2484            mAppLib32InstallDir = new File(dataDir, "app-lib");
2485            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2486            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2487            sUserManager = new UserManagerService(context, this,
2488                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2489
2490            // Propagate permission configuration in to package manager.
2491            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2492                    = systemConfig.getPermissions();
2493            for (int i=0; i<permConfig.size(); i++) {
2494                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2495                BasePermission bp = mSettings.mPermissions.get(perm.name);
2496                if (bp == null) {
2497                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2498                    mSettings.mPermissions.put(perm.name, bp);
2499                }
2500                if (perm.gids != null) {
2501                    bp.setGids(perm.gids, perm.perUser);
2502                }
2503            }
2504
2505            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2506            final int builtInLibCount = libConfig.size();
2507            for (int i = 0; i < builtInLibCount; i++) {
2508                String name = libConfig.keyAt(i);
2509                String path = libConfig.valueAt(i);
2510                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2511                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2512            }
2513
2514            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2515
2516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2517            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2519
2520            // Clean up orphaned packages for which the code path doesn't exist
2521            // and they are an update to a system app - caused by bug/32321269
2522            final int packageSettingCount = mSettings.mPackages.size();
2523            for (int i = packageSettingCount - 1; i >= 0; i--) {
2524                PackageSetting ps = mSettings.mPackages.valueAt(i);
2525                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2526                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2527                    mSettings.mPackages.removeAt(i);
2528                    mSettings.enableSystemPackageLPw(ps.name);
2529                }
2530            }
2531
2532            if (mFirstBoot) {
2533                requestCopyPreoptedFiles();
2534            }
2535
2536            String customResolverActivity = Resources.getSystem().getString(
2537                    R.string.config_customResolverActivity);
2538            if (TextUtils.isEmpty(customResolverActivity)) {
2539                customResolverActivity = null;
2540            } else {
2541                mCustomResolverComponentName = ComponentName.unflattenFromString(
2542                        customResolverActivity);
2543            }
2544
2545            long startTime = SystemClock.uptimeMillis();
2546
2547            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2548                    startTime);
2549
2550            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2551            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2552
2553            if (bootClassPath == null) {
2554                Slog.w(TAG, "No BOOTCLASSPATH found!");
2555            }
2556
2557            if (systemServerClassPath == null) {
2558                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2559            }
2560
2561            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2562
2563            final VersionInfo ver = mSettings.getInternalVersion();
2564            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2565            if (mIsUpgrade) {
2566                logCriticalInfo(Log.INFO,
2567                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2568            }
2569
2570            // when upgrading from pre-M, promote system app permissions from install to runtime
2571            mPromoteSystemApps =
2572                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2573
2574            // When upgrading from pre-N, we need to handle package extraction like first boot,
2575            // as there is no profiling data available.
2576            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2577
2578            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2579
2580            // save off the names of pre-existing system packages prior to scanning; we don't
2581            // want to automatically grant runtime permissions for new system apps
2582            if (mPromoteSystemApps) {
2583                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2584                while (pkgSettingIter.hasNext()) {
2585                    PackageSetting ps = pkgSettingIter.next();
2586                    if (isSystemApp(ps)) {
2587                        mExistingSystemPackages.add(ps.name);
2588                    }
2589                }
2590            }
2591
2592            mCacheDir = preparePackageParserCache(mIsUpgrade);
2593
2594            // Set flag to monitor and not change apk file paths when
2595            // scanning install directories.
2596            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2597
2598            if (mIsUpgrade || mFirstBoot) {
2599                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2600            }
2601
2602            // Collect vendor overlay packages. (Do this before scanning any apps.)
2603            // For security and version matching reason, only consider
2604            // overlay packages if they reside in the right directory.
2605            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR
2608                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2609
2610            mParallelPackageParserCallback.findStaticOverlayPackages();
2611
2612            // Find base frameworks (resource packages without code).
2613            scanDirTracedLI(frameworkDir, mDefParseFlags
2614                    | PackageParser.PARSE_IS_SYSTEM
2615                    | PackageParser.PARSE_IS_SYSTEM_DIR
2616                    | PackageParser.PARSE_IS_PRIVILEGED,
2617                    scanFlags | SCAN_NO_DEX, 0);
2618
2619            // Collected privileged system packages.
2620            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2621            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR
2624                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2625
2626            // Collect ordinary system packages.
2627            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2628            scanDirTracedLI(systemAppDir, mDefParseFlags
2629                    | PackageParser.PARSE_IS_SYSTEM
2630                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2631
2632            // Collect all vendor packages.
2633            File vendorAppDir = new File("/vendor/app");
2634            try {
2635                vendorAppDir = vendorAppDir.getCanonicalFile();
2636            } catch (IOException e) {
2637                // failed to look up canonical path, continue with original one
2638            }
2639            scanDirTracedLI(vendorAppDir, mDefParseFlags
2640                    | PackageParser.PARSE_IS_SYSTEM
2641                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2642
2643            // Collect all OEM packages.
2644            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2645            scanDirTracedLI(oemAppDir, mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2648
2649            // Prune any system packages that no longer exist.
2650            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2651            // Stub packages must either be replaced with full versions in the /data
2652            // partition or be disabled.
2653            final List<String> stubSystemApps = new ArrayList<>();
2654            if (!mOnlyCore) {
2655                // do this first before mucking with mPackages for the "expecting better" case
2656                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2657                while (pkgIterator.hasNext()) {
2658                    final PackageParser.Package pkg = pkgIterator.next();
2659                    if (pkg.isStub) {
2660                        stubSystemApps.add(pkg.packageName);
2661                    }
2662                }
2663
2664                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2665                while (psit.hasNext()) {
2666                    PackageSetting ps = psit.next();
2667
2668                    /*
2669                     * If this is not a system app, it can't be a
2670                     * disable system app.
2671                     */
2672                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2673                        continue;
2674                    }
2675
2676                    /*
2677                     * If the package is scanned, it's not erased.
2678                     */
2679                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2680                    if (scannedPkg != null) {
2681                        /*
2682                         * If the system app is both scanned and in the
2683                         * disabled packages list, then it must have been
2684                         * added via OTA. Remove it from the currently
2685                         * scanned package so the previously user-installed
2686                         * application can be scanned.
2687                         */
2688                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2689                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2690                                    + ps.name + "; removing system app.  Last known codePath="
2691                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2692                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2693                                    + scannedPkg.mVersionCode);
2694                            removePackageLI(scannedPkg, true);
2695                            mExpectingBetter.put(ps.name, ps.codePath);
2696                        }
2697
2698                        continue;
2699                    }
2700
2701                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2702                        psit.remove();
2703                        logCriticalInfo(Log.WARN, "System package " + ps.name
2704                                + " no longer exists; it's data will be wiped");
2705                        // Actual deletion of code and data will be handled by later
2706                        // reconciliation step
2707                    } else {
2708                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2709                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2710                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2711                        }
2712                    }
2713                }
2714            }
2715
2716            //look for any incomplete package installations
2717            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2718            for (int i = 0; i < deletePkgsList.size(); i++) {
2719                // Actual deletion of code and data will be handled by later
2720                // reconciliation step
2721                final String packageName = deletePkgsList.get(i).name;
2722                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2723                synchronized (mPackages) {
2724                    mSettings.removePackageLPw(packageName);
2725                }
2726            }
2727
2728            //delete tmp files
2729            deleteTempPackageFiles();
2730
2731            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2732
2733            // Remove any shared userIDs that have no associated packages
2734            mSettings.pruneSharedUsersLPw();
2735            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2736            final int systemPackagesCount = mPackages.size();
2737            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2738                    + " ms, packageCount: " + systemPackagesCount
2739                    + " , timePerPackage: "
2740                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2741                    + " , cached: " + cachedSystemApps);
2742            if (mIsUpgrade && systemPackagesCount > 0) {
2743                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2744                        ((int) systemScanTime) / systemPackagesCount);
2745            }
2746            if (!mOnlyCore) {
2747                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2748                        SystemClock.uptimeMillis());
2749                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2750
2751                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2752                        | PackageParser.PARSE_FORWARD_LOCK,
2753                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2754
2755                // Remove disable package settings for updated system apps that were
2756                // removed via an OTA. If the update is no longer present, remove the
2757                // app completely. Otherwise, revoke their system privileges.
2758                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2759                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2760                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2761
2762                    final String msg;
2763                    if (deletedPkg == null) {
2764                        // should have found an update, but, we didn't; remove everything
2765                        msg = "Updated system package " + deletedAppName
2766                                + " no longer exists; removing its data";
2767                        // Actual deletion of code and data will be handled by later
2768                        // reconciliation step
2769                    } else {
2770                        // found an update; revoke system privileges
2771                        msg = "Updated system package + " + deletedAppName
2772                                + " no longer exists; revoking system privileges";
2773
2774                        // Don't do anything if a stub is removed from the system image. If
2775                        // we were to remove the uncompressed version from the /data partition,
2776                        // this is where it'd be done.
2777
2778                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2779                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2780                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2781                    }
2782                    logCriticalInfo(Log.WARN, msg);
2783                }
2784
2785                /*
2786                 * Make sure all system apps that we expected to appear on
2787                 * the userdata partition actually showed up. If they never
2788                 * appeared, crawl back and revive the system version.
2789                 */
2790                for (int i = 0; i < mExpectingBetter.size(); i++) {
2791                    final String packageName = mExpectingBetter.keyAt(i);
2792                    if (!mPackages.containsKey(packageName)) {
2793                        final File scanFile = mExpectingBetter.valueAt(i);
2794
2795                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2796                                + " but never showed up; reverting to system");
2797
2798                        int reparseFlags = mDefParseFlags;
2799                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2800                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2801                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2802                                    | PackageParser.PARSE_IS_PRIVILEGED;
2803                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2804                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2805                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2806                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2807                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2808                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2809                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2810                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2811                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2812                        } else {
2813                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2814                            continue;
2815                        }
2816
2817                        mSettings.enableSystemPackageLPw(packageName);
2818
2819                        try {
2820                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2821                        } catch (PackageManagerException e) {
2822                            Slog.e(TAG, "Failed to parse original system package: "
2823                                    + e.getMessage());
2824                        }
2825                    }
2826                }
2827
2828                // Uncompress and install any stubbed system applications.
2829                // This must be done last to ensure all stubs are replaced or disabled.
2830                decompressSystemApplications(stubSystemApps, scanFlags);
2831
2832                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2833                                - cachedSystemApps;
2834
2835                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2836                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2837                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2838                        + " ms, packageCount: " + dataPackagesCount
2839                        + " , timePerPackage: "
2840                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2841                        + " , cached: " + cachedNonSystemApps);
2842                if (mIsUpgrade && dataPackagesCount > 0) {
2843                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2844                            ((int) dataScanTime) / dataPackagesCount);
2845                }
2846            }
2847            mExpectingBetter.clear();
2848
2849            // Resolve the storage manager.
2850            mStorageManagerPackage = getStorageManagerPackageName();
2851
2852            // Resolve protected action filters. Only the setup wizard is allowed to
2853            // have a high priority filter for these actions.
2854            mSetupWizardPackage = getSetupWizardPackageName();
2855            if (mProtectedFilters.size() > 0) {
2856                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2857                    Slog.i(TAG, "No setup wizard;"
2858                        + " All protected intents capped to priority 0");
2859                }
2860                for (ActivityIntentInfo filter : mProtectedFilters) {
2861                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2862                        if (DEBUG_FILTERS) {
2863                            Slog.i(TAG, "Found setup wizard;"
2864                                + " allow priority " + filter.getPriority() + ";"
2865                                + " package: " + filter.activity.info.packageName
2866                                + " activity: " + filter.activity.className
2867                                + " priority: " + filter.getPriority());
2868                        }
2869                        // skip setup wizard; allow it to keep the high priority filter
2870                        continue;
2871                    }
2872                    if (DEBUG_FILTERS) {
2873                        Slog.i(TAG, "Protected action; cap priority to 0;"
2874                                + " package: " + filter.activity.info.packageName
2875                                + " activity: " + filter.activity.className
2876                                + " origPrio: " + filter.getPriority());
2877                    }
2878                    filter.setPriority(0);
2879                }
2880            }
2881            mDeferProtectedFilters = false;
2882            mProtectedFilters.clear();
2883
2884            // Now that we know all of the shared libraries, update all clients to have
2885            // the correct library paths.
2886            updateAllSharedLibrariesLPw(null);
2887
2888            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2889                // NOTE: We ignore potential failures here during a system scan (like
2890                // the rest of the commands above) because there's precious little we
2891                // can do about it. A settings error is reported, though.
2892                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2893            }
2894
2895            // Now that we know all the packages we are keeping,
2896            // read and update their last usage times.
2897            mPackageUsage.read(mPackages);
2898            mCompilerStats.read();
2899
2900            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2901                    SystemClock.uptimeMillis());
2902            Slog.i(TAG, "Time to scan packages: "
2903                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2904                    + " seconds");
2905
2906            // If the platform SDK has changed since the last time we booted,
2907            // we need to re-grant app permission to catch any new ones that
2908            // appear.  This is really a hack, and means that apps can in some
2909            // cases get permissions that the user didn't initially explicitly
2910            // allow...  it would be nice to have some better way to handle
2911            // this situation.
2912            int updateFlags = UPDATE_PERMISSIONS_ALL;
2913            if (ver.sdkVersion != mSdkVersion) {
2914                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2915                        + mSdkVersion + "; regranting permissions for internal storage");
2916                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2917            }
2918            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2919            ver.sdkVersion = mSdkVersion;
2920
2921            // If this is the first boot or an update from pre-M, and it is a normal
2922            // boot, then we need to initialize the default preferred apps across
2923            // all defined users.
2924            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2925                for (UserInfo user : sUserManager.getUsers(true)) {
2926                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2927                    applyFactoryDefaultBrowserLPw(user.id);
2928                    primeDomainVerificationsLPw(user.id);
2929                }
2930            }
2931
2932            // Prepare storage for system user really early during boot,
2933            // since core system apps like SettingsProvider and SystemUI
2934            // can't wait for user to start
2935            final int storageFlags;
2936            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2937                storageFlags = StorageManager.FLAG_STORAGE_DE;
2938            } else {
2939                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2940            }
2941            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2942                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2943                    true /* onlyCoreApps */);
2944            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2945                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2946                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2947                traceLog.traceBegin("AppDataFixup");
2948                try {
2949                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2950                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2951                } catch (InstallerException e) {
2952                    Slog.w(TAG, "Trouble fixing GIDs", e);
2953                }
2954                traceLog.traceEnd();
2955
2956                traceLog.traceBegin("AppDataPrepare");
2957                if (deferPackages == null || deferPackages.isEmpty()) {
2958                    return;
2959                }
2960                int count = 0;
2961                for (String pkgName : deferPackages) {
2962                    PackageParser.Package pkg = null;
2963                    synchronized (mPackages) {
2964                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2965                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2966                            pkg = ps.pkg;
2967                        }
2968                    }
2969                    if (pkg != null) {
2970                        synchronized (mInstallLock) {
2971                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2972                                    true /* maybeMigrateAppData */);
2973                        }
2974                        count++;
2975                    }
2976                }
2977                traceLog.traceEnd();
2978                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2979            }, "prepareAppData");
2980
2981            // If this is first boot after an OTA, and a normal boot, then
2982            // we need to clear code cache directories.
2983            // Note that we do *not* clear the application profiles. These remain valid
2984            // across OTAs and are used to drive profile verification (post OTA) and
2985            // profile compilation (without waiting to collect a fresh set of profiles).
2986            if (mIsUpgrade && !onlyCore) {
2987                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2988                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2989                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2990                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2991                        // No apps are running this early, so no need to freeze
2992                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2993                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2994                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2995                    }
2996                }
2997                ver.fingerprint = Build.FINGERPRINT;
2998            }
2999
3000            checkDefaultBrowser();
3001
3002            // clear only after permissions and other defaults have been updated
3003            mExistingSystemPackages.clear();
3004            mPromoteSystemApps = false;
3005
3006            // All the changes are done during package scanning.
3007            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3008
3009            // can downgrade to reader
3010            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3011            mSettings.writeLPr();
3012            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3013            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3014                    SystemClock.uptimeMillis());
3015
3016            if (!mOnlyCore) {
3017                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3018                mRequiredInstallerPackage = getRequiredInstallerLPr();
3019                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3020                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3021                if (mIntentFilterVerifierComponent != null) {
3022                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3023                            mIntentFilterVerifierComponent);
3024                } else {
3025                    mIntentFilterVerifier = null;
3026                }
3027                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3028                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3029                        SharedLibraryInfo.VERSION_UNDEFINED);
3030                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3031                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3032                        SharedLibraryInfo.VERSION_UNDEFINED);
3033            } else {
3034                mRequiredVerifierPackage = null;
3035                mRequiredInstallerPackage = null;
3036                mRequiredUninstallerPackage = null;
3037                mIntentFilterVerifierComponent = null;
3038                mIntentFilterVerifier = null;
3039                mServicesSystemSharedLibraryPackageName = null;
3040                mSharedSystemSharedLibraryPackageName = null;
3041            }
3042
3043            mInstallerService = new PackageInstallerService(context, this);
3044            final Pair<ComponentName, String> instantAppResolverComponent =
3045                    getInstantAppResolverLPr();
3046            if (instantAppResolverComponent != null) {
3047                if (DEBUG_EPHEMERAL) {
3048                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3049                }
3050                mInstantAppResolverConnection = new EphemeralResolverConnection(
3051                        mContext, instantAppResolverComponent.first,
3052                        instantAppResolverComponent.second);
3053                mInstantAppResolverSettingsComponent =
3054                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3055            } else {
3056                mInstantAppResolverConnection = null;
3057                mInstantAppResolverSettingsComponent = null;
3058            }
3059            updateInstantAppInstallerLocked(null);
3060
3061            // Read and update the usage of dex files.
3062            // Do this at the end of PM init so that all the packages have their
3063            // data directory reconciled.
3064            // At this point we know the code paths of the packages, so we can validate
3065            // the disk file and build the internal cache.
3066            // The usage file is expected to be small so loading and verifying it
3067            // should take a fairly small time compare to the other activities (e.g. package
3068            // scanning).
3069            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3070            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3071            for (int userId : currentUserIds) {
3072                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3073            }
3074            mDexManager.load(userPackages);
3075            if (mIsUpgrade) {
3076                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3077                        (int) (SystemClock.uptimeMillis() - startTime));
3078            }
3079        } // synchronized (mPackages)
3080        } // synchronized (mInstallLock)
3081
3082        // Now after opening every single application zip, make sure they
3083        // are all flushed.  Not really needed, but keeps things nice and
3084        // tidy.
3085        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3086        Runtime.getRuntime().gc();
3087        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3088
3089        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3090        FallbackCategoryProvider.loadFallbacks();
3091        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3092
3093        // The initial scanning above does many calls into installd while
3094        // holding the mPackages lock, but we're mostly interested in yelling
3095        // once we have a booted system.
3096        mInstaller.setWarnIfHeld(mPackages);
3097
3098        // Expose private service for system components to use.
3099        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3100        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3101    }
3102
3103    /**
3104     * Uncompress and install stub applications.
3105     * <p>In order to save space on the system partition, some applications are shipped in a
3106     * compressed form. In addition the compressed bits for the full application, the
3107     * system image contains a tiny stub comprised of only the Android manifest.
3108     * <p>During the first boot, attempt to uncompress and install the full application. If
3109     * the application can't be installed for any reason, disable the stub and prevent
3110     * uncompressing the full application during future boots.
3111     * <p>In order to forcefully attempt an installation of a full application, go to app
3112     * settings and enable the application.
3113     */
3114    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3115        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3116            final String pkgName = stubSystemApps.get(i);
3117            // skip if the system package is already disabled
3118            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3119                stubSystemApps.remove(i);
3120                continue;
3121            }
3122            // skip if the package isn't installed (?!); this should never happen
3123            final PackageParser.Package pkg = mPackages.get(pkgName);
3124            if (pkg == null) {
3125                stubSystemApps.remove(i);
3126                continue;
3127            }
3128            // skip if the package has been disabled by the user
3129            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3130            if (ps != null) {
3131                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3132                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3133                    stubSystemApps.remove(i);
3134                    continue;
3135                }
3136            }
3137
3138            if (DEBUG_COMPRESSION) {
3139                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3140            }
3141
3142            // uncompress the binary to its eventual destination on /data
3143            final File scanFile = decompressPackage(pkg);
3144            if (scanFile == null) {
3145                continue;
3146            }
3147
3148            // install the package to replace the stub on /system
3149            try {
3150                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3151                removePackageLI(pkg, true /*chatty*/);
3152                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3153                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3154                        UserHandle.USER_SYSTEM, "android");
3155                stubSystemApps.remove(i);
3156                continue;
3157            } catch (PackageManagerException e) {
3158                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3159            }
3160
3161            // any failed attempt to install the package will be cleaned up later
3162        }
3163
3164        // disable any stub still left; these failed to install the full application
3165        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3166            final String pkgName = stubSystemApps.get(i);
3167            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3168            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3169                    UserHandle.USER_SYSTEM, "android");
3170            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3171        }
3172    }
3173
3174    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3175        if (DEBUG_COMPRESSION) {
3176            Slog.i(TAG, "Decompress file"
3177                    + "; src: " + srcFile.getAbsolutePath()
3178                    + ", dst: " + dstFile.getAbsolutePath());
3179        }
3180        try (
3181                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3182                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3183        ) {
3184            Streams.copy(fileIn, fileOut);
3185            Os.chmod(dstFile.getAbsolutePath(), 0644);
3186            return PackageManager.INSTALL_SUCCEEDED;
3187        } catch (IOException e) {
3188            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3189                    + "; src: " + srcFile.getAbsolutePath()
3190                    + ", dst: " + dstFile.getAbsolutePath());
3191        }
3192        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3193    }
3194
3195    private File[] getCompressedFiles(String codePath) {
3196        return new File(codePath).listFiles(new FilenameFilter() {
3197            @Override
3198            public boolean accept(File dir, String name) {
3199                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3200            }
3201        });
3202    }
3203
3204    private boolean compressedFileExists(String codePath) {
3205        final File[] compressedFiles = getCompressedFiles(codePath);
3206        return compressedFiles != null && compressedFiles.length > 0;
3207    }
3208
3209    /**
3210     * Decompresses the given package on the system image onto
3211     * the /data partition.
3212     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3213     */
3214    private File decompressPackage(PackageParser.Package pkg) {
3215        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3216        if (compressedFiles == null || compressedFiles.length == 0) {
3217            if (DEBUG_COMPRESSION) {
3218                Slog.i(TAG, "No files to decompress");
3219            }
3220            return null;
3221        }
3222        final File dstCodePath =
3223                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3224        int ret = PackageManager.INSTALL_SUCCEEDED;
3225        try {
3226            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3227            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3228            for (File srcFile : compressedFiles) {
3229                final String srcFileName = srcFile.getName();
3230                final String dstFileName = srcFileName.substring(
3231                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3232                final File dstFile = new File(dstCodePath, dstFileName);
3233                ret = decompressFile(srcFile, dstFile);
3234                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3235                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3236                            + "; pkg: " + pkg.packageName
3237                            + ", file: " + dstFileName);
3238                    break;
3239                }
3240            }
3241        } catch (ErrnoException e) {
3242            logCriticalInfo(Log.ERROR, "Failed to decompress"
3243                    + "; pkg: " + pkg.packageName
3244                    + ", err: " + e.errno);
3245        }
3246        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3247            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3248            NativeLibraryHelper.Handle handle = null;
3249            try {
3250                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3251                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3252                        null /*abiOverride*/);
3253            } catch (IOException e) {
3254                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3255                        + "; pkg: " + pkg.packageName);
3256                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3257            } finally {
3258                IoUtils.closeQuietly(handle);
3259            }
3260        }
3261        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3262            if (dstCodePath == null || !dstCodePath.exists()) {
3263                return null;
3264            }
3265            removeCodePathLI(dstCodePath);
3266            return null;
3267        }
3268        return dstCodePath;
3269    }
3270
3271    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3272        // we're only interested in updating the installer appliction when 1) it's not
3273        // already set or 2) the modified package is the installer
3274        if (mInstantAppInstallerActivity != null
3275                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3276                        .equals(modifiedPackage)) {
3277            return;
3278        }
3279        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3280    }
3281
3282    private static File preparePackageParserCache(boolean isUpgrade) {
3283        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3284            return null;
3285        }
3286
3287        // Disable package parsing on eng builds to allow for faster incremental development.
3288        if (Build.IS_ENG) {
3289            return null;
3290        }
3291
3292        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3293            Slog.i(TAG, "Disabling package parser cache due to system property.");
3294            return null;
3295        }
3296
3297        // The base directory for the package parser cache lives under /data/system/.
3298        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3299                "package_cache");
3300        if (cacheBaseDir == null) {
3301            return null;
3302        }
3303
3304        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3305        // This also serves to "GC" unused entries when the package cache version changes (which
3306        // can only happen during upgrades).
3307        if (isUpgrade) {
3308            FileUtils.deleteContents(cacheBaseDir);
3309        }
3310
3311
3312        // Return the versioned package cache directory. This is something like
3313        // "/data/system/package_cache/1"
3314        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3315
3316        // The following is a workaround to aid development on non-numbered userdebug
3317        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3318        // the system partition is newer.
3319        //
3320        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3321        // that starts with "eng." to signify that this is an engineering build and not
3322        // destined for release.
3323        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3324            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3325
3326            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3327            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3328            // in general and should not be used for production changes. In this specific case,
3329            // we know that they will work.
3330            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3331            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3332                FileUtils.deleteContents(cacheBaseDir);
3333                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3334            }
3335        }
3336
3337        return cacheDir;
3338    }
3339
3340    @Override
3341    public boolean isFirstBoot() {
3342        // allow instant applications
3343        return mFirstBoot;
3344    }
3345
3346    @Override
3347    public boolean isOnlyCoreApps() {
3348        // allow instant applications
3349        return mOnlyCore;
3350    }
3351
3352    @Override
3353    public boolean isUpgrade() {
3354        // allow instant applications
3355        return mIsUpgrade;
3356    }
3357
3358    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3359        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3360
3361        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3362                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3363                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3364        if (matches.size() == 1) {
3365            return matches.get(0).getComponentInfo().packageName;
3366        } else if (matches.size() == 0) {
3367            Log.e(TAG, "There should probably be a verifier, but, none were found");
3368            return null;
3369        }
3370        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3371    }
3372
3373    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3374        synchronized (mPackages) {
3375            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3376            if (libraryEntry == null) {
3377                throw new IllegalStateException("Missing required shared library:" + name);
3378            }
3379            return libraryEntry.apk;
3380        }
3381    }
3382
3383    private @NonNull String getRequiredInstallerLPr() {
3384        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3385        intent.addCategory(Intent.CATEGORY_DEFAULT);
3386        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3387
3388        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3389                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3390                UserHandle.USER_SYSTEM);
3391        if (matches.size() == 1) {
3392            ResolveInfo resolveInfo = matches.get(0);
3393            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3394                throw new RuntimeException("The installer must be a privileged app");
3395            }
3396            return matches.get(0).getComponentInfo().packageName;
3397        } else {
3398            throw new RuntimeException("There must be exactly one installer; found " + matches);
3399        }
3400    }
3401
3402    private @NonNull String getRequiredUninstallerLPr() {
3403        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3404        intent.addCategory(Intent.CATEGORY_DEFAULT);
3405        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3406
3407        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3408                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3409                UserHandle.USER_SYSTEM);
3410        if (resolveInfo == null ||
3411                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3412            throw new RuntimeException("There must be exactly one uninstaller; found "
3413                    + resolveInfo);
3414        }
3415        return resolveInfo.getComponentInfo().packageName;
3416    }
3417
3418    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3419        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3420
3421        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3422                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3423                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3424        ResolveInfo best = null;
3425        final int N = matches.size();
3426        for (int i = 0; i < N; i++) {
3427            final ResolveInfo cur = matches.get(i);
3428            final String packageName = cur.getComponentInfo().packageName;
3429            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3430                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3431                continue;
3432            }
3433
3434            if (best == null || cur.priority > best.priority) {
3435                best = cur;
3436            }
3437        }
3438
3439        if (best != null) {
3440            return best.getComponentInfo().getComponentName();
3441        }
3442        Slog.w(TAG, "Intent filter verifier not found");
3443        return null;
3444    }
3445
3446    @Override
3447    public @Nullable ComponentName getInstantAppResolverComponent() {
3448        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3449            return null;
3450        }
3451        synchronized (mPackages) {
3452            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3453            if (instantAppResolver == null) {
3454                return null;
3455            }
3456            return instantAppResolver.first;
3457        }
3458    }
3459
3460    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3461        final String[] packageArray =
3462                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3463        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3464            if (DEBUG_EPHEMERAL) {
3465                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3466            }
3467            return null;
3468        }
3469
3470        final int callingUid = Binder.getCallingUid();
3471        final int resolveFlags =
3472                MATCH_DIRECT_BOOT_AWARE
3473                | MATCH_DIRECT_BOOT_UNAWARE
3474                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3475        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3476        final Intent resolverIntent = new Intent(actionName);
3477        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3478                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3479        // temporarily look for the old action
3480        if (resolvers.size() == 0) {
3481            if (DEBUG_EPHEMERAL) {
3482                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3483            }
3484            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3485            resolverIntent.setAction(actionName);
3486            resolvers = queryIntentServicesInternal(resolverIntent, null,
3487                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3488        }
3489        final int N = resolvers.size();
3490        if (N == 0) {
3491            if (DEBUG_EPHEMERAL) {
3492                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3493            }
3494            return null;
3495        }
3496
3497        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3498        for (int i = 0; i < N; i++) {
3499            final ResolveInfo info = resolvers.get(i);
3500
3501            if (info.serviceInfo == null) {
3502                continue;
3503            }
3504
3505            final String packageName = info.serviceInfo.packageName;
3506            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3507                if (DEBUG_EPHEMERAL) {
3508                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3509                            + " pkg: " + packageName + ", info:" + info);
3510                }
3511                continue;
3512            }
3513
3514            if (DEBUG_EPHEMERAL) {
3515                Slog.v(TAG, "Ephemeral resolver found;"
3516                        + " pkg: " + packageName + ", info:" + info);
3517            }
3518            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3519        }
3520        if (DEBUG_EPHEMERAL) {
3521            Slog.v(TAG, "Ephemeral resolver NOT found");
3522        }
3523        return null;
3524    }
3525
3526    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3527        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3528        intent.addCategory(Intent.CATEGORY_DEFAULT);
3529        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3530
3531        final int resolveFlags =
3532                MATCH_DIRECT_BOOT_AWARE
3533                | MATCH_DIRECT_BOOT_UNAWARE
3534                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3535        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3536                resolveFlags, UserHandle.USER_SYSTEM);
3537        // temporarily look for the old action
3538        if (matches.isEmpty()) {
3539            if (DEBUG_EPHEMERAL) {
3540                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3541            }
3542            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3543            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3544                    resolveFlags, UserHandle.USER_SYSTEM);
3545        }
3546        Iterator<ResolveInfo> iter = matches.iterator();
3547        while (iter.hasNext()) {
3548            final ResolveInfo rInfo = iter.next();
3549            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3550            if (ps != null) {
3551                final PermissionsState permissionsState = ps.getPermissionsState();
3552                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3553                    continue;
3554                }
3555            }
3556            iter.remove();
3557        }
3558        if (matches.size() == 0) {
3559            return null;
3560        } else if (matches.size() == 1) {
3561            return (ActivityInfo) matches.get(0).getComponentInfo();
3562        } else {
3563            throw new RuntimeException(
3564                    "There must be at most one ephemeral installer; found " + matches);
3565        }
3566    }
3567
3568    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3569            @NonNull ComponentName resolver) {
3570        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3571                .addCategory(Intent.CATEGORY_DEFAULT)
3572                .setPackage(resolver.getPackageName());
3573        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3574        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3575                UserHandle.USER_SYSTEM);
3576        // temporarily look for the old action
3577        if (matches.isEmpty()) {
3578            if (DEBUG_EPHEMERAL) {
3579                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3580            }
3581            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3582            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3583                    UserHandle.USER_SYSTEM);
3584        }
3585        if (matches.isEmpty()) {
3586            return null;
3587        }
3588        return matches.get(0).getComponentInfo().getComponentName();
3589    }
3590
3591    private void primeDomainVerificationsLPw(int userId) {
3592        if (DEBUG_DOMAIN_VERIFICATION) {
3593            Slog.d(TAG, "Priming domain verifications in user " + userId);
3594        }
3595
3596        SystemConfig systemConfig = SystemConfig.getInstance();
3597        ArraySet<String> packages = systemConfig.getLinkedApps();
3598
3599        for (String packageName : packages) {
3600            PackageParser.Package pkg = mPackages.get(packageName);
3601            if (pkg != null) {
3602                if (!pkg.isSystemApp()) {
3603                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3604                    continue;
3605                }
3606
3607                ArraySet<String> domains = null;
3608                for (PackageParser.Activity a : pkg.activities) {
3609                    for (ActivityIntentInfo filter : a.intents) {
3610                        if (hasValidDomains(filter)) {
3611                            if (domains == null) {
3612                                domains = new ArraySet<String>();
3613                            }
3614                            domains.addAll(filter.getHostsList());
3615                        }
3616                    }
3617                }
3618
3619                if (domains != null && domains.size() > 0) {
3620                    if (DEBUG_DOMAIN_VERIFICATION) {
3621                        Slog.v(TAG, "      + " + packageName);
3622                    }
3623                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3624                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3625                    // and then 'always' in the per-user state actually used for intent resolution.
3626                    final IntentFilterVerificationInfo ivi;
3627                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3628                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3629                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3630                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3631                } else {
3632                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3633                            + "' does not handle web links");
3634                }
3635            } else {
3636                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3637            }
3638        }
3639
3640        scheduleWritePackageRestrictionsLocked(userId);
3641        scheduleWriteSettingsLocked();
3642    }
3643
3644    private void applyFactoryDefaultBrowserLPw(int userId) {
3645        // The default browser app's package name is stored in a string resource,
3646        // with a product-specific overlay used for vendor customization.
3647        String browserPkg = mContext.getResources().getString(
3648                com.android.internal.R.string.default_browser);
3649        if (!TextUtils.isEmpty(browserPkg)) {
3650            // non-empty string => required to be a known package
3651            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3652            if (ps == null) {
3653                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3654                browserPkg = null;
3655            } else {
3656                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3657            }
3658        }
3659
3660        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3661        // default.  If there's more than one, just leave everything alone.
3662        if (browserPkg == null) {
3663            calculateDefaultBrowserLPw(userId);
3664        }
3665    }
3666
3667    private void calculateDefaultBrowserLPw(int userId) {
3668        List<String> allBrowsers = resolveAllBrowserApps(userId);
3669        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3670        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3671    }
3672
3673    private List<String> resolveAllBrowserApps(int userId) {
3674        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3675        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3676                PackageManager.MATCH_ALL, userId);
3677
3678        final int count = list.size();
3679        List<String> result = new ArrayList<String>(count);
3680        for (int i=0; i<count; i++) {
3681            ResolveInfo info = list.get(i);
3682            if (info.activityInfo == null
3683                    || !info.handleAllWebDataURI
3684                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3685                    || result.contains(info.activityInfo.packageName)) {
3686                continue;
3687            }
3688            result.add(info.activityInfo.packageName);
3689        }
3690
3691        return result;
3692    }
3693
3694    private boolean packageIsBrowser(String packageName, int userId) {
3695        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3696                PackageManager.MATCH_ALL, userId);
3697        final int N = list.size();
3698        for (int i = 0; i < N; i++) {
3699            ResolveInfo info = list.get(i);
3700            if (packageName.equals(info.activityInfo.packageName)) {
3701                return true;
3702            }
3703        }
3704        return false;
3705    }
3706
3707    private void checkDefaultBrowser() {
3708        final int myUserId = UserHandle.myUserId();
3709        final String packageName = getDefaultBrowserPackageName(myUserId);
3710        if (packageName != null) {
3711            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3712            if (info == null) {
3713                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3714                synchronized (mPackages) {
3715                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3716                }
3717            }
3718        }
3719    }
3720
3721    @Override
3722    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3723            throws RemoteException {
3724        try {
3725            return super.onTransact(code, data, reply, flags);
3726        } catch (RuntimeException e) {
3727            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3728                Slog.wtf(TAG, "Package Manager Crash", e);
3729            }
3730            throw e;
3731        }
3732    }
3733
3734    static int[] appendInts(int[] cur, int[] add) {
3735        if (add == null) return cur;
3736        if (cur == null) return add;
3737        final int N = add.length;
3738        for (int i=0; i<N; i++) {
3739            cur = appendInt(cur, add[i]);
3740        }
3741        return cur;
3742    }
3743
3744    /**
3745     * Returns whether or not a full application can see an instant application.
3746     * <p>
3747     * Currently, there are three cases in which this can occur:
3748     * <ol>
3749     * <li>The calling application is a "special" process. The special
3750     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3751     *     and {@code 0}</li>
3752     * <li>The calling application has the permission
3753     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3754     * <li>The calling application is the default launcher on the
3755     *     system partition.</li>
3756     * </ol>
3757     */
3758    private boolean canViewInstantApps(int callingUid, int userId) {
3759        if (callingUid == Process.SYSTEM_UID
3760                || callingUid == Process.SHELL_UID
3761                || callingUid == Process.ROOT_UID) {
3762            return true;
3763        }
3764        if (mContext.checkCallingOrSelfPermission(
3765                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3766            return true;
3767        }
3768        if (mContext.checkCallingOrSelfPermission(
3769                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3770            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3771            if (homeComponent != null
3772                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3773                return true;
3774            }
3775        }
3776        return false;
3777    }
3778
3779    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3780        if (!sUserManager.exists(userId)) return null;
3781        if (ps == null) {
3782            return null;
3783        }
3784        PackageParser.Package p = ps.pkg;
3785        if (p == null) {
3786            return null;
3787        }
3788        final int callingUid = Binder.getCallingUid();
3789        // Filter out ephemeral app metadata:
3790        //   * The system/shell/root can see metadata for any app
3791        //   * An installed app can see metadata for 1) other installed apps
3792        //     and 2) ephemeral apps that have explicitly interacted with it
3793        //   * Ephemeral apps can only see their own data and exposed installed apps
3794        //   * Holding a signature permission allows seeing instant apps
3795        if (filterAppAccessLPr(ps, callingUid, userId)) {
3796            return null;
3797        }
3798
3799        final PermissionsState permissionsState = ps.getPermissionsState();
3800
3801        // Compute GIDs only if requested
3802        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3803                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3804        // Compute granted permissions only if package has requested permissions
3805        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3806                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3807        final PackageUserState state = ps.readUserState(userId);
3808
3809        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3810                && ps.isSystem()) {
3811            flags |= MATCH_ANY_USER;
3812        }
3813
3814        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3815                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3816
3817        if (packageInfo == null) {
3818            return null;
3819        }
3820
3821        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3822                resolveExternalPackageNameLPr(p);
3823
3824        return packageInfo;
3825    }
3826
3827    @Override
3828    public void checkPackageStartable(String packageName, int userId) {
3829        final int callingUid = Binder.getCallingUid();
3830        if (getInstantAppPackageName(callingUid) != null) {
3831            throw new SecurityException("Instant applications don't have access to this method");
3832        }
3833        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3834        synchronized (mPackages) {
3835            final PackageSetting ps = mSettings.mPackages.get(packageName);
3836            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3837                throw new SecurityException("Package " + packageName + " was not found!");
3838            }
3839
3840            if (!ps.getInstalled(userId)) {
3841                throw new SecurityException(
3842                        "Package " + packageName + " was not installed for user " + userId + "!");
3843            }
3844
3845            if (mSafeMode && !ps.isSystem()) {
3846                throw new SecurityException("Package " + packageName + " not a system app!");
3847            }
3848
3849            if (mFrozenPackages.contains(packageName)) {
3850                throw new SecurityException("Package " + packageName + " is currently frozen!");
3851            }
3852
3853            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3854                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3855                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3856            }
3857        }
3858    }
3859
3860    @Override
3861    public boolean isPackageAvailable(String packageName, int userId) {
3862        if (!sUserManager.exists(userId)) return false;
3863        final int callingUid = Binder.getCallingUid();
3864        enforceCrossUserPermission(callingUid, userId,
3865                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3866        synchronized (mPackages) {
3867            PackageParser.Package p = mPackages.get(packageName);
3868            if (p != null) {
3869                final PackageSetting ps = (PackageSetting) p.mExtras;
3870                if (filterAppAccessLPr(ps, callingUid, userId)) {
3871                    return false;
3872                }
3873                if (ps != null) {
3874                    final PackageUserState state = ps.readUserState(userId);
3875                    if (state != null) {
3876                        return PackageParser.isAvailable(state);
3877                    }
3878                }
3879            }
3880        }
3881        return false;
3882    }
3883
3884    @Override
3885    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3886        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3887                flags, Binder.getCallingUid(), userId);
3888    }
3889
3890    @Override
3891    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3892            int flags, int userId) {
3893        return getPackageInfoInternal(versionedPackage.getPackageName(),
3894                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3895    }
3896
3897    /**
3898     * Important: The provided filterCallingUid is used exclusively to filter out packages
3899     * that can be seen based on user state. It's typically the original caller uid prior
3900     * to clearing. Because it can only be provided by trusted code, it's value can be
3901     * trusted and will be used as-is; unlike userId which will be validated by this method.
3902     */
3903    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3904            int flags, int filterCallingUid, int userId) {
3905        if (!sUserManager.exists(userId)) return null;
3906        flags = updateFlagsForPackage(flags, userId, packageName);
3907        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3908                false /* requireFullPermission */, false /* checkShell */, "get package info");
3909
3910        // reader
3911        synchronized (mPackages) {
3912            // Normalize package name to handle renamed packages and static libs
3913            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3914
3915            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3916            if (matchFactoryOnly) {
3917                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3918                if (ps != null) {
3919                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3920                        return null;
3921                    }
3922                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3923                        return null;
3924                    }
3925                    return generatePackageInfo(ps, flags, userId);
3926                }
3927            }
3928
3929            PackageParser.Package p = mPackages.get(packageName);
3930            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3931                return null;
3932            }
3933            if (DEBUG_PACKAGE_INFO)
3934                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3935            if (p != null) {
3936                final PackageSetting ps = (PackageSetting) p.mExtras;
3937                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3938                    return null;
3939                }
3940                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3941                    return null;
3942                }
3943                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3944            }
3945            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3946                final PackageSetting ps = mSettings.mPackages.get(packageName);
3947                if (ps == null) return null;
3948                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3949                    return null;
3950                }
3951                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3952                    return null;
3953                }
3954                return generatePackageInfo(ps, flags, userId);
3955            }
3956        }
3957        return null;
3958    }
3959
3960    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3961        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3962            return true;
3963        }
3964        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3965            return true;
3966        }
3967        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3968            return true;
3969        }
3970        return false;
3971    }
3972
3973    private boolean isComponentVisibleToInstantApp(
3974            @Nullable ComponentName component, @ComponentType int type) {
3975        if (type == TYPE_ACTIVITY) {
3976            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3977            return activity != null
3978                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3979                    : false;
3980        } else if (type == TYPE_RECEIVER) {
3981            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3982            return activity != null
3983                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3984                    : false;
3985        } else if (type == TYPE_SERVICE) {
3986            final PackageParser.Service service = mServices.mServices.get(component);
3987            return service != null
3988                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3989                    : false;
3990        } else if (type == TYPE_PROVIDER) {
3991            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3992            return provider != null
3993                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3994                    : false;
3995        } else if (type == TYPE_UNKNOWN) {
3996            return isComponentVisibleToInstantApp(component);
3997        }
3998        return false;
3999    }
4000
4001    /**
4002     * Returns whether or not access to the application should be filtered.
4003     * <p>
4004     * Access may be limited based upon whether the calling or target applications
4005     * are instant applications.
4006     *
4007     * @see #canAccessInstantApps(int)
4008     */
4009    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4010            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4011        // if we're in an isolated process, get the real calling UID
4012        if (Process.isIsolated(callingUid)) {
4013            callingUid = mIsolatedOwners.get(callingUid);
4014        }
4015        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4016        final boolean callerIsInstantApp = instantAppPkgName != null;
4017        if (ps == null) {
4018            if (callerIsInstantApp) {
4019                // pretend the application exists, but, needs to be filtered
4020                return true;
4021            }
4022            return false;
4023        }
4024        // if the target and caller are the same application, don't filter
4025        if (isCallerSameApp(ps.name, callingUid)) {
4026            return false;
4027        }
4028        if (callerIsInstantApp) {
4029            // request for a specific component; if it hasn't been explicitly exposed, filter
4030            if (component != null) {
4031                return !isComponentVisibleToInstantApp(component, componentType);
4032            }
4033            // request for application; if no components have been explicitly exposed, filter
4034            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4035        }
4036        if (ps.getInstantApp(userId)) {
4037            // caller can see all components of all instant applications, don't filter
4038            if (canViewInstantApps(callingUid, userId)) {
4039                return false;
4040            }
4041            // request for a specific instant application component, filter
4042            if (component != null) {
4043                return true;
4044            }
4045            // request for an instant application; if the caller hasn't been granted access, filter
4046            return !mInstantAppRegistry.isInstantAccessGranted(
4047                    userId, UserHandle.getAppId(callingUid), ps.appId);
4048        }
4049        return false;
4050    }
4051
4052    /**
4053     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4054     */
4055    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4056        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4057    }
4058
4059    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4060            int flags) {
4061        // Callers can access only the libs they depend on, otherwise they need to explicitly
4062        // ask for the shared libraries given the caller is allowed to access all static libs.
4063        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4064            // System/shell/root get to see all static libs
4065            final int appId = UserHandle.getAppId(uid);
4066            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4067                    || appId == Process.ROOT_UID) {
4068                return false;
4069            }
4070        }
4071
4072        // No package means no static lib as it is always on internal storage
4073        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4074            return false;
4075        }
4076
4077        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4078                ps.pkg.staticSharedLibVersion);
4079        if (libEntry == null) {
4080            return false;
4081        }
4082
4083        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4084        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4085        if (uidPackageNames == null) {
4086            return true;
4087        }
4088
4089        for (String uidPackageName : uidPackageNames) {
4090            if (ps.name.equals(uidPackageName)) {
4091                return false;
4092            }
4093            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4094            if (uidPs != null) {
4095                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4096                        libEntry.info.getName());
4097                if (index < 0) {
4098                    continue;
4099                }
4100                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4101                    return false;
4102                }
4103            }
4104        }
4105        return true;
4106    }
4107
4108    @Override
4109    public String[] currentToCanonicalPackageNames(String[] names) {
4110        final int callingUid = Binder.getCallingUid();
4111        if (getInstantAppPackageName(callingUid) != null) {
4112            return names;
4113        }
4114        final String[] out = new String[names.length];
4115        // reader
4116        synchronized (mPackages) {
4117            final int callingUserId = UserHandle.getUserId(callingUid);
4118            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4119            for (int i=names.length-1; i>=0; i--) {
4120                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4121                boolean translateName = false;
4122                if (ps != null && ps.realName != null) {
4123                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4124                    translateName = !targetIsInstantApp
4125                            || canViewInstantApps
4126                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4127                                    UserHandle.getAppId(callingUid), ps.appId);
4128                }
4129                out[i] = translateName ? ps.realName : names[i];
4130            }
4131        }
4132        return out;
4133    }
4134
4135    @Override
4136    public String[] canonicalToCurrentPackageNames(String[] names) {
4137        final int callingUid = Binder.getCallingUid();
4138        if (getInstantAppPackageName(callingUid) != null) {
4139            return names;
4140        }
4141        final String[] out = new String[names.length];
4142        // reader
4143        synchronized (mPackages) {
4144            final int callingUserId = UserHandle.getUserId(callingUid);
4145            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4146            for (int i=names.length-1; i>=0; i--) {
4147                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4148                boolean translateName = false;
4149                if (cur != null) {
4150                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4151                    final boolean targetIsInstantApp =
4152                            ps != null && ps.getInstantApp(callingUserId);
4153                    translateName = !targetIsInstantApp
4154                            || canViewInstantApps
4155                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4156                                    UserHandle.getAppId(callingUid), ps.appId);
4157                }
4158                out[i] = translateName ? cur : names[i];
4159            }
4160        }
4161        return out;
4162    }
4163
4164    @Override
4165    public int getPackageUid(String packageName, int flags, int userId) {
4166        if (!sUserManager.exists(userId)) return -1;
4167        final int callingUid = Binder.getCallingUid();
4168        flags = updateFlagsForPackage(flags, userId, packageName);
4169        enforceCrossUserPermission(callingUid, userId,
4170                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4171
4172        // reader
4173        synchronized (mPackages) {
4174            final PackageParser.Package p = mPackages.get(packageName);
4175            if (p != null && p.isMatch(flags)) {
4176                PackageSetting ps = (PackageSetting) p.mExtras;
4177                if (filterAppAccessLPr(ps, callingUid, userId)) {
4178                    return -1;
4179                }
4180                return UserHandle.getUid(userId, p.applicationInfo.uid);
4181            }
4182            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4183                final PackageSetting ps = mSettings.mPackages.get(packageName);
4184                if (ps != null && ps.isMatch(flags)
4185                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4186                    return UserHandle.getUid(userId, ps.appId);
4187                }
4188            }
4189        }
4190
4191        return -1;
4192    }
4193
4194    @Override
4195    public int[] getPackageGids(String packageName, int flags, int userId) {
4196        if (!sUserManager.exists(userId)) return null;
4197        final int callingUid = Binder.getCallingUid();
4198        flags = updateFlagsForPackage(flags, userId, packageName);
4199        enforceCrossUserPermission(callingUid, userId,
4200                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4201
4202        // reader
4203        synchronized (mPackages) {
4204            final PackageParser.Package p = mPackages.get(packageName);
4205            if (p != null && p.isMatch(flags)) {
4206                PackageSetting ps = (PackageSetting) p.mExtras;
4207                if (filterAppAccessLPr(ps, callingUid, userId)) {
4208                    return null;
4209                }
4210                // TODO: Shouldn't this be checking for package installed state for userId and
4211                // return null?
4212                return ps.getPermissionsState().computeGids(userId);
4213            }
4214            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4215                final PackageSetting ps = mSettings.mPackages.get(packageName);
4216                if (ps != null && ps.isMatch(flags)
4217                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4218                    return ps.getPermissionsState().computeGids(userId);
4219                }
4220            }
4221        }
4222
4223        return null;
4224    }
4225
4226    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4227        if (bp.perm != null) {
4228            return PackageParser.generatePermissionInfo(bp.perm, flags);
4229        }
4230        PermissionInfo pi = new PermissionInfo();
4231        pi.name = bp.name;
4232        pi.packageName = bp.sourcePackage;
4233        pi.nonLocalizedLabel = bp.name;
4234        pi.protectionLevel = bp.protectionLevel;
4235        return pi;
4236    }
4237
4238    @Override
4239    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4240        final int callingUid = Binder.getCallingUid();
4241        if (getInstantAppPackageName(callingUid) != null) {
4242            return null;
4243        }
4244        // reader
4245        synchronized (mPackages) {
4246            final BasePermission p = mSettings.mPermissions.get(name);
4247            if (p == null) {
4248                return null;
4249            }
4250            // If the caller is an app that targets pre 26 SDK drop protection flags.
4251            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4252            if (permissionInfo != null) {
4253                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4254                        permissionInfo.protectionLevel, packageName, callingUid);
4255            }
4256            return permissionInfo;
4257        }
4258    }
4259
4260    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4261            String packageName, int uid) {
4262        // Signature permission flags area always reported
4263        final int protectionLevelMasked = protectionLevel
4264                & (PermissionInfo.PROTECTION_NORMAL
4265                | PermissionInfo.PROTECTION_DANGEROUS
4266                | PermissionInfo.PROTECTION_SIGNATURE);
4267        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4268            return protectionLevel;
4269        }
4270
4271        // System sees all flags.
4272        final int appId = UserHandle.getAppId(uid);
4273        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4274                || appId == Process.SHELL_UID) {
4275            return protectionLevel;
4276        }
4277
4278        // Normalize package name to handle renamed packages and static libs
4279        packageName = resolveInternalPackageNameLPr(packageName,
4280                PackageManager.VERSION_CODE_HIGHEST);
4281
4282        // Apps that target O see flags for all protection levels.
4283        final PackageSetting ps = mSettings.mPackages.get(packageName);
4284        if (ps == null) {
4285            return protectionLevel;
4286        }
4287        if (ps.appId != appId) {
4288            return protectionLevel;
4289        }
4290
4291        final PackageParser.Package pkg = mPackages.get(packageName);
4292        if (pkg == null) {
4293            return protectionLevel;
4294        }
4295        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4296            return protectionLevelMasked;
4297        }
4298
4299        return protectionLevel;
4300    }
4301
4302    @Override
4303    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4304            int flags) {
4305        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4306            return null;
4307        }
4308        // reader
4309        synchronized (mPackages) {
4310            if (group != null && !mPermissionGroups.containsKey(group)) {
4311                // This is thrown as NameNotFoundException
4312                return null;
4313            }
4314
4315            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4316            for (BasePermission p : mSettings.mPermissions.values()) {
4317                if (group == null) {
4318                    if (p.perm == null || p.perm.info.group == null) {
4319                        out.add(generatePermissionInfo(p, flags));
4320                    }
4321                } else {
4322                    if (p.perm != null && group.equals(p.perm.info.group)) {
4323                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4324                    }
4325                }
4326            }
4327            return new ParceledListSlice<>(out);
4328        }
4329    }
4330
4331    @Override
4332    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4333        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4334            return null;
4335        }
4336        // reader
4337        synchronized (mPackages) {
4338            return PackageParser.generatePermissionGroupInfo(
4339                    mPermissionGroups.get(name), flags);
4340        }
4341    }
4342
4343    @Override
4344    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4345        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4346            return ParceledListSlice.emptyList();
4347        }
4348        // reader
4349        synchronized (mPackages) {
4350            final int N = mPermissionGroups.size();
4351            ArrayList<PermissionGroupInfo> out
4352                    = new ArrayList<PermissionGroupInfo>(N);
4353            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4354                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4355            }
4356            return new ParceledListSlice<>(out);
4357        }
4358    }
4359
4360    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4361            int filterCallingUid, int userId) {
4362        if (!sUserManager.exists(userId)) return null;
4363        PackageSetting ps = mSettings.mPackages.get(packageName);
4364        if (ps != null) {
4365            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4366                return null;
4367            }
4368            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4369                return null;
4370            }
4371            if (ps.pkg == null) {
4372                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4373                if (pInfo != null) {
4374                    return pInfo.applicationInfo;
4375                }
4376                return null;
4377            }
4378            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4379                    ps.readUserState(userId), userId);
4380            if (ai != null) {
4381                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4382            }
4383            return ai;
4384        }
4385        return null;
4386    }
4387
4388    @Override
4389    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4390        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4391    }
4392
4393    /**
4394     * Important: The provided filterCallingUid is used exclusively to filter out applications
4395     * that can be seen based on user state. It's typically the original caller uid prior
4396     * to clearing. Because it can only be provided by trusted code, it's value can be
4397     * trusted and will be used as-is; unlike userId which will be validated by this method.
4398     */
4399    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4400            int filterCallingUid, int userId) {
4401        if (!sUserManager.exists(userId)) return null;
4402        flags = updateFlagsForApplication(flags, userId, packageName);
4403        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4404                false /* requireFullPermission */, false /* checkShell */, "get application info");
4405
4406        // writer
4407        synchronized (mPackages) {
4408            // Normalize package name to handle renamed packages and static libs
4409            packageName = resolveInternalPackageNameLPr(packageName,
4410                    PackageManager.VERSION_CODE_HIGHEST);
4411
4412            PackageParser.Package p = mPackages.get(packageName);
4413            if (DEBUG_PACKAGE_INFO) Log.v(
4414                    TAG, "getApplicationInfo " + packageName
4415                    + ": " + p);
4416            if (p != null) {
4417                PackageSetting ps = mSettings.mPackages.get(packageName);
4418                if (ps == null) return null;
4419                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4420                    return null;
4421                }
4422                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4423                    return null;
4424                }
4425                // Note: isEnabledLP() does not apply here - always return info
4426                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4427                        p, flags, ps.readUserState(userId), userId);
4428                if (ai != null) {
4429                    ai.packageName = resolveExternalPackageNameLPr(p);
4430                }
4431                return ai;
4432            }
4433            if ("android".equals(packageName)||"system".equals(packageName)) {
4434                return mAndroidApplication;
4435            }
4436            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4437                // Already generates the external package name
4438                return generateApplicationInfoFromSettingsLPw(packageName,
4439                        flags, filterCallingUid, userId);
4440            }
4441        }
4442        return null;
4443    }
4444
4445    private String normalizePackageNameLPr(String packageName) {
4446        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4447        return normalizedPackageName != null ? normalizedPackageName : packageName;
4448    }
4449
4450    @Override
4451    public void deletePreloadsFileCache() {
4452        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4453            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4454        }
4455        File dir = Environment.getDataPreloadsFileCacheDirectory();
4456        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4457        FileUtils.deleteContents(dir);
4458    }
4459
4460    @Override
4461    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4462            final int storageFlags, final IPackageDataObserver observer) {
4463        mContext.enforceCallingOrSelfPermission(
4464                android.Manifest.permission.CLEAR_APP_CACHE, null);
4465        mHandler.post(() -> {
4466            boolean success = false;
4467            try {
4468                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4469                success = true;
4470            } catch (IOException e) {
4471                Slog.w(TAG, e);
4472            }
4473            if (observer != null) {
4474                try {
4475                    observer.onRemoveCompleted(null, success);
4476                } catch (RemoteException e) {
4477                    Slog.w(TAG, e);
4478                }
4479            }
4480        });
4481    }
4482
4483    @Override
4484    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4485            final int storageFlags, final IntentSender pi) {
4486        mContext.enforceCallingOrSelfPermission(
4487                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4488        mHandler.post(() -> {
4489            boolean success = false;
4490            try {
4491                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4492                success = true;
4493            } catch (IOException e) {
4494                Slog.w(TAG, e);
4495            }
4496            if (pi != null) {
4497                try {
4498                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4499                } catch (SendIntentException e) {
4500                    Slog.w(TAG, e);
4501                }
4502            }
4503        });
4504    }
4505
4506    /**
4507     * Blocking call to clear various types of cached data across the system
4508     * until the requested bytes are available.
4509     */
4510    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4511        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4512        final File file = storage.findPathForUuid(volumeUuid);
4513        if (file.getUsableSpace() >= bytes) return;
4514
4515        if (ENABLE_FREE_CACHE_V2) {
4516            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4517                    volumeUuid);
4518            final boolean aggressive = (storageFlags
4519                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4520            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4521
4522            // 1. Pre-flight to determine if we have any chance to succeed
4523            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4524            if (internalVolume && (aggressive || SystemProperties
4525                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4526                deletePreloadsFileCache();
4527                if (file.getUsableSpace() >= bytes) return;
4528            }
4529
4530            // 3. Consider parsed APK data (aggressive only)
4531            if (internalVolume && aggressive) {
4532                FileUtils.deleteContents(mCacheDir);
4533                if (file.getUsableSpace() >= bytes) return;
4534            }
4535
4536            // 4. Consider cached app data (above quotas)
4537            try {
4538                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4539                        Installer.FLAG_FREE_CACHE_V2);
4540            } catch (InstallerException ignored) {
4541            }
4542            if (file.getUsableSpace() >= bytes) return;
4543
4544            // 5. Consider shared libraries with refcount=0 and age>min cache period
4545            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4546                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4547                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4548                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4549                return;
4550            }
4551
4552            // 6. Consider dexopt output (aggressive only)
4553            // TODO: Implement
4554
4555            // 7. Consider installed instant apps unused longer than min cache period
4556            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4557                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4558                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4559                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4560                return;
4561            }
4562
4563            // 8. Consider cached app data (below quotas)
4564            try {
4565                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4566                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4567            } catch (InstallerException ignored) {
4568            }
4569            if (file.getUsableSpace() >= bytes) return;
4570
4571            // 9. Consider DropBox entries
4572            // TODO: Implement
4573
4574            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4575            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4576                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4577                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4578                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4579                return;
4580            }
4581        } else {
4582            try {
4583                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4584            } catch (InstallerException ignored) {
4585            }
4586            if (file.getUsableSpace() >= bytes) return;
4587        }
4588
4589        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4590    }
4591
4592    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4593            throws IOException {
4594        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4595        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4596
4597        List<VersionedPackage> packagesToDelete = null;
4598        final long now = System.currentTimeMillis();
4599
4600        synchronized (mPackages) {
4601            final int[] allUsers = sUserManager.getUserIds();
4602            final int libCount = mSharedLibraries.size();
4603            for (int i = 0; i < libCount; i++) {
4604                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4605                if (versionedLib == null) {
4606                    continue;
4607                }
4608                final int versionCount = versionedLib.size();
4609                for (int j = 0; j < versionCount; j++) {
4610                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4611                    // Skip packages that are not static shared libs.
4612                    if (!libInfo.isStatic()) {
4613                        break;
4614                    }
4615                    // Important: We skip static shared libs used for some user since
4616                    // in such a case we need to keep the APK on the device. The check for
4617                    // a lib being used for any user is performed by the uninstall call.
4618                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4619                    // Resolve the package name - we use synthetic package names internally
4620                    final String internalPackageName = resolveInternalPackageNameLPr(
4621                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4622                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4623                    // Skip unused static shared libs cached less than the min period
4624                    // to prevent pruning a lib needed by a subsequently installed package.
4625                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4626                        continue;
4627                    }
4628                    if (packagesToDelete == null) {
4629                        packagesToDelete = new ArrayList<>();
4630                    }
4631                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4632                            declaringPackage.getVersionCode()));
4633                }
4634            }
4635        }
4636
4637        if (packagesToDelete != null) {
4638            final int packageCount = packagesToDelete.size();
4639            for (int i = 0; i < packageCount; i++) {
4640                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4641                // Delete the package synchronously (will fail of the lib used for any user).
4642                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4643                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4644                                == PackageManager.DELETE_SUCCEEDED) {
4645                    if (volume.getUsableSpace() >= neededSpace) {
4646                        return true;
4647                    }
4648                }
4649            }
4650        }
4651
4652        return false;
4653    }
4654
4655    /**
4656     * Update given flags based on encryption status of current user.
4657     */
4658    private int updateFlags(int flags, int userId) {
4659        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4660                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4661            // Caller expressed an explicit opinion about what encryption
4662            // aware/unaware components they want to see, so fall through and
4663            // give them what they want
4664        } else {
4665            // Caller expressed no opinion, so match based on user state
4666            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4667                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4668            } else {
4669                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4670            }
4671        }
4672        return flags;
4673    }
4674
4675    private UserManagerInternal getUserManagerInternal() {
4676        if (mUserManagerInternal == null) {
4677            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4678        }
4679        return mUserManagerInternal;
4680    }
4681
4682    private DeviceIdleController.LocalService getDeviceIdleController() {
4683        if (mDeviceIdleController == null) {
4684            mDeviceIdleController =
4685                    LocalServices.getService(DeviceIdleController.LocalService.class);
4686        }
4687        return mDeviceIdleController;
4688    }
4689
4690    /**
4691     * Update given flags when being used to request {@link PackageInfo}.
4692     */
4693    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4694        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4695        boolean triaged = true;
4696        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4697                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4698            // Caller is asking for component details, so they'd better be
4699            // asking for specific encryption matching behavior, or be triaged
4700            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4701                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4702                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4703                triaged = false;
4704            }
4705        }
4706        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4707                | PackageManager.MATCH_SYSTEM_ONLY
4708                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4709            triaged = false;
4710        }
4711        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4712            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4713                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4714                    + Debug.getCallers(5));
4715        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4716                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4717            // If the caller wants all packages and has a restricted profile associated with it,
4718            // then match all users. This is to make sure that launchers that need to access work
4719            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4720            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4721            flags |= PackageManager.MATCH_ANY_USER;
4722        }
4723        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4724            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4725                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4726        }
4727        return updateFlags(flags, userId);
4728    }
4729
4730    /**
4731     * Update given flags when being used to request {@link ApplicationInfo}.
4732     */
4733    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4734        return updateFlagsForPackage(flags, userId, cookie);
4735    }
4736
4737    /**
4738     * Update given flags when being used to request {@link ComponentInfo}.
4739     */
4740    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4741        if (cookie instanceof Intent) {
4742            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4743                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4744            }
4745        }
4746
4747        boolean triaged = true;
4748        // Caller is asking for component details, so they'd better be
4749        // asking for specific encryption matching behavior, or be triaged
4750        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4751                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4752                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4753            triaged = false;
4754        }
4755        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4756            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4757                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4758        }
4759
4760        return updateFlags(flags, userId);
4761    }
4762
4763    /**
4764     * Update given intent when being used to request {@link ResolveInfo}.
4765     */
4766    private Intent updateIntentForResolve(Intent intent) {
4767        if (intent.getSelector() != null) {
4768            intent = intent.getSelector();
4769        }
4770        if (DEBUG_PREFERRED) {
4771            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4772        }
4773        return intent;
4774    }
4775
4776    /**
4777     * Update given flags when being used to request {@link ResolveInfo}.
4778     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4779     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4780     * flag set. However, this flag is only honoured in three circumstances:
4781     * <ul>
4782     * <li>when called from a system process</li>
4783     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4784     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4785     * action and a {@code android.intent.category.BROWSABLE} category</li>
4786     * </ul>
4787     */
4788    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4789        return updateFlagsForResolve(flags, userId, intent, callingUid,
4790                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4791    }
4792    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4793            boolean wantInstantApps) {
4794        return updateFlagsForResolve(flags, userId, intent, callingUid,
4795                wantInstantApps, false /*onlyExposedExplicitly*/);
4796    }
4797    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4798            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4799        // Safe mode means we shouldn't match any third-party components
4800        if (mSafeMode) {
4801            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4802        }
4803        if (getInstantAppPackageName(callingUid) != null) {
4804            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4805            if (onlyExposedExplicitly) {
4806                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4807            }
4808            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4809            flags |= PackageManager.MATCH_INSTANT;
4810        } else {
4811            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4812            final boolean allowMatchInstant =
4813                    (wantInstantApps
4814                            && Intent.ACTION_VIEW.equals(intent.getAction())
4815                            && hasWebURI(intent))
4816                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4817            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4818                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4819            if (!allowMatchInstant) {
4820                flags &= ~PackageManager.MATCH_INSTANT;
4821            }
4822        }
4823        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4824    }
4825
4826    @Override
4827    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4828        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4829    }
4830
4831    /**
4832     * Important: The provided filterCallingUid is used exclusively to filter out activities
4833     * that can be seen based on user state. It's typically the original caller uid prior
4834     * to clearing. Because it can only be provided by trusted code, it's value can be
4835     * trusted and will be used as-is; unlike userId which will be validated by this method.
4836     */
4837    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4838            int filterCallingUid, int userId) {
4839        if (!sUserManager.exists(userId)) return null;
4840        flags = updateFlagsForComponent(flags, userId, component);
4841        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4842                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4843        synchronized (mPackages) {
4844            PackageParser.Activity a = mActivities.mActivities.get(component);
4845
4846            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4847            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4848                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4849                if (ps == null) return null;
4850                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4851                    return null;
4852                }
4853                return PackageParser.generateActivityInfo(
4854                        a, flags, ps.readUserState(userId), userId);
4855            }
4856            if (mResolveComponentName.equals(component)) {
4857                return PackageParser.generateActivityInfo(
4858                        mResolveActivity, flags, new PackageUserState(), userId);
4859            }
4860        }
4861        return null;
4862    }
4863
4864    @Override
4865    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4866            String resolvedType) {
4867        synchronized (mPackages) {
4868            if (component.equals(mResolveComponentName)) {
4869                // The resolver supports EVERYTHING!
4870                return true;
4871            }
4872            final int callingUid = Binder.getCallingUid();
4873            final int callingUserId = UserHandle.getUserId(callingUid);
4874            PackageParser.Activity a = mActivities.mActivities.get(component);
4875            if (a == null) {
4876                return false;
4877            }
4878            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4879            if (ps == null) {
4880                return false;
4881            }
4882            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4883                return false;
4884            }
4885            for (int i=0; i<a.intents.size(); i++) {
4886                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4887                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4888                    return true;
4889                }
4890            }
4891            return false;
4892        }
4893    }
4894
4895    @Override
4896    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4897        if (!sUserManager.exists(userId)) return null;
4898        final int callingUid = Binder.getCallingUid();
4899        flags = updateFlagsForComponent(flags, userId, component);
4900        enforceCrossUserPermission(callingUid, userId,
4901                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4902        synchronized (mPackages) {
4903            PackageParser.Activity a = mReceivers.mActivities.get(component);
4904            if (DEBUG_PACKAGE_INFO) Log.v(
4905                TAG, "getReceiverInfo " + component + ": " + a);
4906            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4907                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4908                if (ps == null) return null;
4909                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4910                    return null;
4911                }
4912                return PackageParser.generateActivityInfo(
4913                        a, flags, ps.readUserState(userId), userId);
4914            }
4915        }
4916        return null;
4917    }
4918
4919    @Override
4920    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4921            int flags, int userId) {
4922        if (!sUserManager.exists(userId)) return null;
4923        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4924        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4925            return null;
4926        }
4927
4928        flags = updateFlagsForPackage(flags, userId, null);
4929
4930        final boolean canSeeStaticLibraries =
4931                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4932                        == PERMISSION_GRANTED
4933                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4934                        == PERMISSION_GRANTED
4935                || canRequestPackageInstallsInternal(packageName,
4936                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4937                        false  /* throwIfPermNotDeclared*/)
4938                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4939                        == PERMISSION_GRANTED;
4940
4941        synchronized (mPackages) {
4942            List<SharedLibraryInfo> result = null;
4943
4944            final int libCount = mSharedLibraries.size();
4945            for (int i = 0; i < libCount; i++) {
4946                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4947                if (versionedLib == null) {
4948                    continue;
4949                }
4950
4951                final int versionCount = versionedLib.size();
4952                for (int j = 0; j < versionCount; j++) {
4953                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4954                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4955                        break;
4956                    }
4957                    final long identity = Binder.clearCallingIdentity();
4958                    try {
4959                        PackageInfo packageInfo = getPackageInfoVersioned(
4960                                libInfo.getDeclaringPackage(), flags
4961                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4962                        if (packageInfo == null) {
4963                            continue;
4964                        }
4965                    } finally {
4966                        Binder.restoreCallingIdentity(identity);
4967                    }
4968
4969                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4970                            libInfo.getVersion(), libInfo.getType(),
4971                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4972                            flags, userId));
4973
4974                    if (result == null) {
4975                        result = new ArrayList<>();
4976                    }
4977                    result.add(resLibInfo);
4978                }
4979            }
4980
4981            return result != null ? new ParceledListSlice<>(result) : null;
4982        }
4983    }
4984
4985    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4986            SharedLibraryInfo libInfo, int flags, int userId) {
4987        List<VersionedPackage> versionedPackages = null;
4988        final int packageCount = mSettings.mPackages.size();
4989        for (int i = 0; i < packageCount; i++) {
4990            PackageSetting ps = mSettings.mPackages.valueAt(i);
4991
4992            if (ps == null) {
4993                continue;
4994            }
4995
4996            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4997                continue;
4998            }
4999
5000            final String libName = libInfo.getName();
5001            if (libInfo.isStatic()) {
5002                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5003                if (libIdx < 0) {
5004                    continue;
5005                }
5006                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5007                    continue;
5008                }
5009                if (versionedPackages == null) {
5010                    versionedPackages = new ArrayList<>();
5011                }
5012                // If the dependent is a static shared lib, use the public package name
5013                String dependentPackageName = ps.name;
5014                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5015                    dependentPackageName = ps.pkg.manifestPackageName;
5016                }
5017                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5018            } else if (ps.pkg != null) {
5019                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5020                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5021                    if (versionedPackages == null) {
5022                        versionedPackages = new ArrayList<>();
5023                    }
5024                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5025                }
5026            }
5027        }
5028
5029        return versionedPackages;
5030    }
5031
5032    @Override
5033    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5034        if (!sUserManager.exists(userId)) return null;
5035        final int callingUid = Binder.getCallingUid();
5036        flags = updateFlagsForComponent(flags, userId, component);
5037        enforceCrossUserPermission(callingUid, userId,
5038                false /* requireFullPermission */, false /* checkShell */, "get service info");
5039        synchronized (mPackages) {
5040            PackageParser.Service s = mServices.mServices.get(component);
5041            if (DEBUG_PACKAGE_INFO) Log.v(
5042                TAG, "getServiceInfo " + component + ": " + s);
5043            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5044                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5045                if (ps == null) return null;
5046                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5047                    return null;
5048                }
5049                return PackageParser.generateServiceInfo(
5050                        s, flags, ps.readUserState(userId), userId);
5051            }
5052        }
5053        return null;
5054    }
5055
5056    @Override
5057    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5058        if (!sUserManager.exists(userId)) return null;
5059        final int callingUid = Binder.getCallingUid();
5060        flags = updateFlagsForComponent(flags, userId, component);
5061        enforceCrossUserPermission(callingUid, userId,
5062                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5063        synchronized (mPackages) {
5064            PackageParser.Provider p = mProviders.mProviders.get(component);
5065            if (DEBUG_PACKAGE_INFO) Log.v(
5066                TAG, "getProviderInfo " + component + ": " + p);
5067            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5068                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5069                if (ps == null) return null;
5070                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5071                    return null;
5072                }
5073                return PackageParser.generateProviderInfo(
5074                        p, flags, ps.readUserState(userId), userId);
5075            }
5076        }
5077        return null;
5078    }
5079
5080    @Override
5081    public String[] getSystemSharedLibraryNames() {
5082        // allow instant applications
5083        synchronized (mPackages) {
5084            Set<String> libs = null;
5085            final int libCount = mSharedLibraries.size();
5086            for (int i = 0; i < libCount; i++) {
5087                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5088                if (versionedLib == null) {
5089                    continue;
5090                }
5091                final int versionCount = versionedLib.size();
5092                for (int j = 0; j < versionCount; j++) {
5093                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5094                    if (!libEntry.info.isStatic()) {
5095                        if (libs == null) {
5096                            libs = new ArraySet<>();
5097                        }
5098                        libs.add(libEntry.info.getName());
5099                        break;
5100                    }
5101                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5102                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5103                            UserHandle.getUserId(Binder.getCallingUid()),
5104                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5105                        if (libs == null) {
5106                            libs = new ArraySet<>();
5107                        }
5108                        libs.add(libEntry.info.getName());
5109                        break;
5110                    }
5111                }
5112            }
5113
5114            if (libs != null) {
5115                String[] libsArray = new String[libs.size()];
5116                libs.toArray(libsArray);
5117                return libsArray;
5118            }
5119
5120            return null;
5121        }
5122    }
5123
5124    @Override
5125    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5126        // allow instant applications
5127        synchronized (mPackages) {
5128            return mServicesSystemSharedLibraryPackageName;
5129        }
5130    }
5131
5132    @Override
5133    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5134        // allow instant applications
5135        synchronized (mPackages) {
5136            return mSharedSystemSharedLibraryPackageName;
5137        }
5138    }
5139
5140    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5141        for (int i = userList.length - 1; i >= 0; --i) {
5142            final int userId = userList[i];
5143            // don't add instant app to the list of updates
5144            if (pkgSetting.getInstantApp(userId)) {
5145                continue;
5146            }
5147            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5148            if (changedPackages == null) {
5149                changedPackages = new SparseArray<>();
5150                mChangedPackages.put(userId, changedPackages);
5151            }
5152            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5153            if (sequenceNumbers == null) {
5154                sequenceNumbers = new HashMap<>();
5155                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5156            }
5157            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5158            if (sequenceNumber != null) {
5159                changedPackages.remove(sequenceNumber);
5160            }
5161            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5162            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5163        }
5164        mChangedPackagesSequenceNumber++;
5165    }
5166
5167    @Override
5168    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5169        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5170            return null;
5171        }
5172        synchronized (mPackages) {
5173            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5174                return null;
5175            }
5176            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5177            if (changedPackages == null) {
5178                return null;
5179            }
5180            final List<String> packageNames =
5181                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5182            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5183                final String packageName = changedPackages.get(i);
5184                if (packageName != null) {
5185                    packageNames.add(packageName);
5186                }
5187            }
5188            return packageNames.isEmpty()
5189                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5190        }
5191    }
5192
5193    @Override
5194    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5195        // allow instant applications
5196        ArrayList<FeatureInfo> res;
5197        synchronized (mAvailableFeatures) {
5198            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5199            res.addAll(mAvailableFeatures.values());
5200        }
5201        final FeatureInfo fi = new FeatureInfo();
5202        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5203                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5204        res.add(fi);
5205
5206        return new ParceledListSlice<>(res);
5207    }
5208
5209    @Override
5210    public boolean hasSystemFeature(String name, int version) {
5211        // allow instant applications
5212        synchronized (mAvailableFeatures) {
5213            final FeatureInfo feat = mAvailableFeatures.get(name);
5214            if (feat == null) {
5215                return false;
5216            } else {
5217                return feat.version >= version;
5218            }
5219        }
5220    }
5221
5222    @Override
5223    public int checkPermission(String permName, String pkgName, int userId) {
5224        if (!sUserManager.exists(userId)) {
5225            return PackageManager.PERMISSION_DENIED;
5226        }
5227        final int callingUid = Binder.getCallingUid();
5228
5229        synchronized (mPackages) {
5230            final PackageParser.Package p = mPackages.get(pkgName);
5231            if (p != null && p.mExtras != null) {
5232                final PackageSetting ps = (PackageSetting) p.mExtras;
5233                if (filterAppAccessLPr(ps, callingUid, userId)) {
5234                    return PackageManager.PERMISSION_DENIED;
5235                }
5236                final boolean instantApp = ps.getInstantApp(userId);
5237                final PermissionsState permissionsState = ps.getPermissionsState();
5238                if (permissionsState.hasPermission(permName, userId)) {
5239                    if (instantApp) {
5240                        BasePermission bp = mSettings.mPermissions.get(permName);
5241                        if (bp != null && bp.isInstant()) {
5242                            return PackageManager.PERMISSION_GRANTED;
5243                        }
5244                    } else {
5245                        return PackageManager.PERMISSION_GRANTED;
5246                    }
5247                }
5248                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5249                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5250                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5251                    return PackageManager.PERMISSION_GRANTED;
5252                }
5253            }
5254        }
5255
5256        return PackageManager.PERMISSION_DENIED;
5257    }
5258
5259    @Override
5260    public int checkUidPermission(String permName, int uid) {
5261        final int callingUid = Binder.getCallingUid();
5262        final int callingUserId = UserHandle.getUserId(callingUid);
5263        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5264        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5265        final int userId = UserHandle.getUserId(uid);
5266        if (!sUserManager.exists(userId)) {
5267            return PackageManager.PERMISSION_DENIED;
5268        }
5269
5270        synchronized (mPackages) {
5271            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5272            if (obj != null) {
5273                if (obj instanceof SharedUserSetting) {
5274                    if (isCallerInstantApp) {
5275                        return PackageManager.PERMISSION_DENIED;
5276                    }
5277                } else if (obj instanceof PackageSetting) {
5278                    final PackageSetting ps = (PackageSetting) obj;
5279                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5280                        return PackageManager.PERMISSION_DENIED;
5281                    }
5282                }
5283                final SettingBase settingBase = (SettingBase) obj;
5284                final PermissionsState permissionsState = settingBase.getPermissionsState();
5285                if (permissionsState.hasPermission(permName, userId)) {
5286                    if (isUidInstantApp) {
5287                        BasePermission bp = mSettings.mPermissions.get(permName);
5288                        if (bp != null && bp.isInstant()) {
5289                            return PackageManager.PERMISSION_GRANTED;
5290                        }
5291                    } else {
5292                        return PackageManager.PERMISSION_GRANTED;
5293                    }
5294                }
5295                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5296                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5297                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5298                    return PackageManager.PERMISSION_GRANTED;
5299                }
5300            } else {
5301                ArraySet<String> perms = mSystemPermissions.get(uid);
5302                if (perms != null) {
5303                    if (perms.contains(permName)) {
5304                        return PackageManager.PERMISSION_GRANTED;
5305                    }
5306                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5307                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5308                        return PackageManager.PERMISSION_GRANTED;
5309                    }
5310                }
5311            }
5312        }
5313
5314        return PackageManager.PERMISSION_DENIED;
5315    }
5316
5317    @Override
5318    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5319        if (UserHandle.getCallingUserId() != userId) {
5320            mContext.enforceCallingPermission(
5321                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5322                    "isPermissionRevokedByPolicy for user " + userId);
5323        }
5324
5325        if (checkPermission(permission, packageName, userId)
5326                == PackageManager.PERMISSION_GRANTED) {
5327            return false;
5328        }
5329
5330        final int callingUid = Binder.getCallingUid();
5331        if (getInstantAppPackageName(callingUid) != null) {
5332            if (!isCallerSameApp(packageName, callingUid)) {
5333                return false;
5334            }
5335        } else {
5336            if (isInstantApp(packageName, userId)) {
5337                return false;
5338            }
5339        }
5340
5341        final long identity = Binder.clearCallingIdentity();
5342        try {
5343            final int flags = getPermissionFlags(permission, packageName, userId);
5344            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5345        } finally {
5346            Binder.restoreCallingIdentity(identity);
5347        }
5348    }
5349
5350    @Override
5351    public String getPermissionControllerPackageName() {
5352        synchronized (mPackages) {
5353            return mRequiredInstallerPackage;
5354        }
5355    }
5356
5357    /**
5358     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5359     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5360     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5361     * @param message the message to log on security exception
5362     */
5363    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5364            boolean checkShell, String message) {
5365        if (userId < 0) {
5366            throw new IllegalArgumentException("Invalid userId " + userId);
5367        }
5368        if (checkShell) {
5369            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5370        }
5371        if (userId == UserHandle.getUserId(callingUid)) return;
5372        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5373            if (requireFullPermission) {
5374                mContext.enforceCallingOrSelfPermission(
5375                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5376            } else {
5377                try {
5378                    mContext.enforceCallingOrSelfPermission(
5379                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5380                } catch (SecurityException se) {
5381                    mContext.enforceCallingOrSelfPermission(
5382                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5383                }
5384            }
5385        }
5386    }
5387
5388    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5389        if (callingUid == Process.SHELL_UID) {
5390            if (userHandle >= 0
5391                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5392                throw new SecurityException("Shell does not have permission to access user "
5393                        + userHandle);
5394            } else if (userHandle < 0) {
5395                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5396                        + Debug.getCallers(3));
5397            }
5398        }
5399    }
5400
5401    private BasePermission findPermissionTreeLP(String permName) {
5402        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5403            if (permName.startsWith(bp.name) &&
5404                    permName.length() > bp.name.length() &&
5405                    permName.charAt(bp.name.length()) == '.') {
5406                return bp;
5407            }
5408        }
5409        return null;
5410    }
5411
5412    private BasePermission checkPermissionTreeLP(String permName) {
5413        if (permName != null) {
5414            BasePermission bp = findPermissionTreeLP(permName);
5415            if (bp != null) {
5416                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5417                    return bp;
5418                }
5419                throw new SecurityException("Calling uid "
5420                        + Binder.getCallingUid()
5421                        + " is not allowed to add to permission tree "
5422                        + bp.name + " owned by uid " + bp.uid);
5423            }
5424        }
5425        throw new SecurityException("No permission tree found for " + permName);
5426    }
5427
5428    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5429        if (s1 == null) {
5430            return s2 == null;
5431        }
5432        if (s2 == null) {
5433            return false;
5434        }
5435        if (s1.getClass() != s2.getClass()) {
5436            return false;
5437        }
5438        return s1.equals(s2);
5439    }
5440
5441    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5442        if (pi1.icon != pi2.icon) return false;
5443        if (pi1.logo != pi2.logo) return false;
5444        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5445        if (!compareStrings(pi1.name, pi2.name)) return false;
5446        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5447        // We'll take care of setting this one.
5448        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5449        // These are not currently stored in settings.
5450        //if (!compareStrings(pi1.group, pi2.group)) return false;
5451        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5452        //if (pi1.labelRes != pi2.labelRes) return false;
5453        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5454        return true;
5455    }
5456
5457    int permissionInfoFootprint(PermissionInfo info) {
5458        int size = info.name.length();
5459        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5460        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5461        return size;
5462    }
5463
5464    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5465        int size = 0;
5466        for (BasePermission perm : mSettings.mPermissions.values()) {
5467            if (perm.uid == tree.uid) {
5468                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5469            }
5470        }
5471        return size;
5472    }
5473
5474    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5475        // We calculate the max size of permissions defined by this uid and throw
5476        // if that plus the size of 'info' would exceed our stated maximum.
5477        if (tree.uid != Process.SYSTEM_UID) {
5478            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5479            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5480                throw new SecurityException("Permission tree size cap exceeded");
5481            }
5482        }
5483    }
5484
5485    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5486        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5487            throw new SecurityException("Instant apps can't add permissions");
5488        }
5489        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5490            throw new SecurityException("Label must be specified in permission");
5491        }
5492        BasePermission tree = checkPermissionTreeLP(info.name);
5493        BasePermission bp = mSettings.mPermissions.get(info.name);
5494        boolean added = bp == null;
5495        boolean changed = true;
5496        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5497        if (added) {
5498            enforcePermissionCapLocked(info, tree);
5499            bp = new BasePermission(info.name, tree.sourcePackage,
5500                    BasePermission.TYPE_DYNAMIC);
5501        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5502            throw new SecurityException(
5503                    "Not allowed to modify non-dynamic permission "
5504                    + info.name);
5505        } else {
5506            if (bp.protectionLevel == fixedLevel
5507                    && bp.perm.owner.equals(tree.perm.owner)
5508                    && bp.uid == tree.uid
5509                    && comparePermissionInfos(bp.perm.info, info)) {
5510                changed = false;
5511            }
5512        }
5513        bp.protectionLevel = fixedLevel;
5514        info = new PermissionInfo(info);
5515        info.protectionLevel = fixedLevel;
5516        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5517        bp.perm.info.packageName = tree.perm.info.packageName;
5518        bp.uid = tree.uid;
5519        if (added) {
5520            mSettings.mPermissions.put(info.name, bp);
5521        }
5522        if (changed) {
5523            if (!async) {
5524                mSettings.writeLPr();
5525            } else {
5526                scheduleWriteSettingsLocked();
5527            }
5528        }
5529        return added;
5530    }
5531
5532    @Override
5533    public boolean addPermission(PermissionInfo info) {
5534        synchronized (mPackages) {
5535            return addPermissionLocked(info, false);
5536        }
5537    }
5538
5539    @Override
5540    public boolean addPermissionAsync(PermissionInfo info) {
5541        synchronized (mPackages) {
5542            return addPermissionLocked(info, true);
5543        }
5544    }
5545
5546    @Override
5547    public void removePermission(String name) {
5548        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5549            throw new SecurityException("Instant applications don't have access to this method");
5550        }
5551        synchronized (mPackages) {
5552            checkPermissionTreeLP(name);
5553            BasePermission bp = mSettings.mPermissions.get(name);
5554            if (bp != null) {
5555                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5556                    throw new SecurityException(
5557                            "Not allowed to modify non-dynamic permission "
5558                            + name);
5559                }
5560                mSettings.mPermissions.remove(name);
5561                mSettings.writeLPr();
5562            }
5563        }
5564    }
5565
5566    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5567            PackageParser.Package pkg, BasePermission bp) {
5568        int index = pkg.requestedPermissions.indexOf(bp.name);
5569        if (index == -1) {
5570            throw new SecurityException("Package " + pkg.packageName
5571                    + " has not requested permission " + bp.name);
5572        }
5573        if (!bp.isRuntime() && !bp.isDevelopment()) {
5574            throw new SecurityException("Permission " + bp.name
5575                    + " is not a changeable permission type");
5576        }
5577    }
5578
5579    @Override
5580    public void grantRuntimePermission(String packageName, String name, final int userId) {
5581        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5582    }
5583
5584    private void grantRuntimePermission(String packageName, String name, final int userId,
5585            boolean overridePolicy) {
5586        if (!sUserManager.exists(userId)) {
5587            Log.e(TAG, "No such user:" + userId);
5588            return;
5589        }
5590        final int callingUid = Binder.getCallingUid();
5591
5592        mContext.enforceCallingOrSelfPermission(
5593                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5594                "grantRuntimePermission");
5595
5596        enforceCrossUserPermission(callingUid, userId,
5597                true /* requireFullPermission */, true /* checkShell */,
5598                "grantRuntimePermission");
5599
5600        final int uid;
5601        final PackageSetting ps;
5602
5603        synchronized (mPackages) {
5604            final PackageParser.Package pkg = mPackages.get(packageName);
5605            if (pkg == null) {
5606                throw new IllegalArgumentException("Unknown package: " + packageName);
5607            }
5608            final BasePermission bp = mSettings.mPermissions.get(name);
5609            if (bp == null) {
5610                throw new IllegalArgumentException("Unknown permission: " + name);
5611            }
5612            ps = (PackageSetting) pkg.mExtras;
5613            if (ps == null
5614                    || filterAppAccessLPr(ps, callingUid, userId)) {
5615                throw new IllegalArgumentException("Unknown package: " + packageName);
5616            }
5617
5618            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5619
5620            // If a permission review is required for legacy apps we represent
5621            // their permissions as always granted runtime ones since we need
5622            // to keep the review required permission flag per user while an
5623            // install permission's state is shared across all users.
5624            if (mPermissionReviewRequired
5625                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5626                    && bp.isRuntime()) {
5627                return;
5628            }
5629
5630            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5631
5632            final PermissionsState permissionsState = ps.getPermissionsState();
5633
5634            final int flags = permissionsState.getPermissionFlags(name, userId);
5635            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5636                throw new SecurityException("Cannot grant system fixed permission "
5637                        + name + " for package " + packageName);
5638            }
5639            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5640                throw new SecurityException("Cannot grant policy fixed permission "
5641                        + name + " for package " + packageName);
5642            }
5643
5644            if (bp.isDevelopment()) {
5645                // Development permissions must be handled specially, since they are not
5646                // normal runtime permissions.  For now they apply to all users.
5647                if (permissionsState.grantInstallPermission(bp) !=
5648                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5649                    scheduleWriteSettingsLocked();
5650                }
5651                return;
5652            }
5653
5654            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5655                throw new SecurityException("Cannot grant non-ephemeral permission"
5656                        + name + " for package " + packageName);
5657            }
5658
5659            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5660                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5661                return;
5662            }
5663
5664            final int result = permissionsState.grantRuntimePermission(bp, userId);
5665            switch (result) {
5666                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5667                    return;
5668                }
5669
5670                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5671                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5672                    mHandler.post(new Runnable() {
5673                        @Override
5674                        public void run() {
5675                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5676                        }
5677                    });
5678                }
5679                break;
5680            }
5681
5682            if (bp.isRuntime()) {
5683                logPermissionGranted(mContext, name, packageName);
5684            }
5685
5686            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5687
5688            // Not critical if that is lost - app has to request again.
5689            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5690        }
5691
5692        // Only need to do this if user is initialized. Otherwise it's a new user
5693        // and there are no processes running as the user yet and there's no need
5694        // to make an expensive call to remount processes for the changed permissions.
5695        if (READ_EXTERNAL_STORAGE.equals(name)
5696                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5697            final long token = Binder.clearCallingIdentity();
5698            try {
5699                if (sUserManager.isInitialized(userId)) {
5700                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5701                            StorageManagerInternal.class);
5702                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5703                }
5704            } finally {
5705                Binder.restoreCallingIdentity(token);
5706            }
5707        }
5708    }
5709
5710    @Override
5711    public void revokeRuntimePermission(String packageName, String name, int userId) {
5712        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5713    }
5714
5715    private void revokeRuntimePermission(String packageName, String name, int userId,
5716            boolean overridePolicy) {
5717        if (!sUserManager.exists(userId)) {
5718            Log.e(TAG, "No such user:" + userId);
5719            return;
5720        }
5721
5722        mContext.enforceCallingOrSelfPermission(
5723                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5724                "revokeRuntimePermission");
5725
5726        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5727                true /* requireFullPermission */, true /* checkShell */,
5728                "revokeRuntimePermission");
5729
5730        final int appId;
5731
5732        synchronized (mPackages) {
5733            final PackageParser.Package pkg = mPackages.get(packageName);
5734            if (pkg == null) {
5735                throw new IllegalArgumentException("Unknown package: " + packageName);
5736            }
5737            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5738            if (ps == null
5739                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5740                throw new IllegalArgumentException("Unknown package: " + packageName);
5741            }
5742            final BasePermission bp = mSettings.mPermissions.get(name);
5743            if (bp == null) {
5744                throw new IllegalArgumentException("Unknown permission: " + name);
5745            }
5746
5747            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5748
5749            // If a permission review is required for legacy apps we represent
5750            // their permissions as always granted runtime ones since we need
5751            // to keep the review required permission flag per user while an
5752            // install permission's state is shared across all users.
5753            if (mPermissionReviewRequired
5754                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5755                    && bp.isRuntime()) {
5756                return;
5757            }
5758
5759            final PermissionsState permissionsState = ps.getPermissionsState();
5760
5761            final int flags = permissionsState.getPermissionFlags(name, userId);
5762            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5763                throw new SecurityException("Cannot revoke system fixed permission "
5764                        + name + " for package " + packageName);
5765            }
5766            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5767                throw new SecurityException("Cannot revoke policy fixed permission "
5768                        + name + " for package " + packageName);
5769            }
5770
5771            if (bp.isDevelopment()) {
5772                // Development permissions must be handled specially, since they are not
5773                // normal runtime permissions.  For now they apply to all users.
5774                if (permissionsState.revokeInstallPermission(bp) !=
5775                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5776                    scheduleWriteSettingsLocked();
5777                }
5778                return;
5779            }
5780
5781            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5782                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5783                return;
5784            }
5785
5786            if (bp.isRuntime()) {
5787                logPermissionRevoked(mContext, name, packageName);
5788            }
5789
5790            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5791
5792            // Critical, after this call app should never have the permission.
5793            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5794
5795            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5796        }
5797
5798        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5799    }
5800
5801    /**
5802     * Get the first event id for the permission.
5803     *
5804     * <p>There are four events for each permission: <ul>
5805     *     <li>Request permission: first id + 0</li>
5806     *     <li>Grant permission: first id + 1</li>
5807     *     <li>Request for permission denied: first id + 2</li>
5808     *     <li>Revoke permission: first id + 3</li>
5809     * </ul></p>
5810     *
5811     * @param name name of the permission
5812     *
5813     * @return The first event id for the permission
5814     */
5815    private static int getBaseEventId(@NonNull String name) {
5816        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5817
5818        if (eventIdIndex == -1) {
5819            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5820                    || Build.IS_USER) {
5821                Log.i(TAG, "Unknown permission " + name);
5822
5823                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5824            } else {
5825                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5826                //
5827                // Also update
5828                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5829                // - metrics_constants.proto
5830                throw new IllegalStateException("Unknown permission " + name);
5831            }
5832        }
5833
5834        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5835    }
5836
5837    /**
5838     * Log that a permission was revoked.
5839     *
5840     * @param context Context of the caller
5841     * @param name name of the permission
5842     * @param packageName package permission if for
5843     */
5844    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5845            @NonNull String packageName) {
5846        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5847    }
5848
5849    /**
5850     * Log that a permission request was granted.
5851     *
5852     * @param context Context of the caller
5853     * @param name name of the permission
5854     * @param packageName package permission if for
5855     */
5856    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5857            @NonNull String packageName) {
5858        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5859    }
5860
5861    @Override
5862    public void resetRuntimePermissions() {
5863        mContext.enforceCallingOrSelfPermission(
5864                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5865                "revokeRuntimePermission");
5866
5867        int callingUid = Binder.getCallingUid();
5868        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5869            mContext.enforceCallingOrSelfPermission(
5870                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5871                    "resetRuntimePermissions");
5872        }
5873
5874        synchronized (mPackages) {
5875            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5876            for (int userId : UserManagerService.getInstance().getUserIds()) {
5877                final int packageCount = mPackages.size();
5878                for (int i = 0; i < packageCount; i++) {
5879                    PackageParser.Package pkg = mPackages.valueAt(i);
5880                    if (!(pkg.mExtras instanceof PackageSetting)) {
5881                        continue;
5882                    }
5883                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5884                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5885                }
5886            }
5887        }
5888    }
5889
5890    @Override
5891    public int getPermissionFlags(String name, String packageName, int userId) {
5892        if (!sUserManager.exists(userId)) {
5893            return 0;
5894        }
5895
5896        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5897
5898        final int callingUid = Binder.getCallingUid();
5899        enforceCrossUserPermission(callingUid, userId,
5900                true /* requireFullPermission */, false /* checkShell */,
5901                "getPermissionFlags");
5902
5903        synchronized (mPackages) {
5904            final PackageParser.Package pkg = mPackages.get(packageName);
5905            if (pkg == null) {
5906                return 0;
5907            }
5908            final BasePermission bp = mSettings.mPermissions.get(name);
5909            if (bp == null) {
5910                return 0;
5911            }
5912            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5913            if (ps == null
5914                    || filterAppAccessLPr(ps, callingUid, userId)) {
5915                return 0;
5916            }
5917            PermissionsState permissionsState = ps.getPermissionsState();
5918            return permissionsState.getPermissionFlags(name, userId);
5919        }
5920    }
5921
5922    @Override
5923    public void updatePermissionFlags(String name, String packageName, int flagMask,
5924            int flagValues, int userId) {
5925        if (!sUserManager.exists(userId)) {
5926            return;
5927        }
5928
5929        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5930
5931        final int callingUid = Binder.getCallingUid();
5932        enforceCrossUserPermission(callingUid, userId,
5933                true /* requireFullPermission */, true /* checkShell */,
5934                "updatePermissionFlags");
5935
5936        // Only the system can change these flags and nothing else.
5937        if (getCallingUid() != Process.SYSTEM_UID) {
5938            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5939            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5940            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5941            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5942            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5943        }
5944
5945        synchronized (mPackages) {
5946            final PackageParser.Package pkg = mPackages.get(packageName);
5947            if (pkg == null) {
5948                throw new IllegalArgumentException("Unknown package: " + packageName);
5949            }
5950            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5951            if (ps == null
5952                    || filterAppAccessLPr(ps, callingUid, userId)) {
5953                throw new IllegalArgumentException("Unknown package: " + packageName);
5954            }
5955
5956            final BasePermission bp = mSettings.mPermissions.get(name);
5957            if (bp == null) {
5958                throw new IllegalArgumentException("Unknown permission: " + name);
5959            }
5960
5961            PermissionsState permissionsState = ps.getPermissionsState();
5962
5963            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5964
5965            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5966                // Install and runtime permissions are stored in different places,
5967                // so figure out what permission changed and persist the change.
5968                if (permissionsState.getInstallPermissionState(name) != null) {
5969                    scheduleWriteSettingsLocked();
5970                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5971                        || hadState) {
5972                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5973                }
5974            }
5975        }
5976    }
5977
5978    /**
5979     * Update the permission flags for all packages and runtime permissions of a user in order
5980     * to allow device or profile owner to remove POLICY_FIXED.
5981     */
5982    @Override
5983    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5984        if (!sUserManager.exists(userId)) {
5985            return;
5986        }
5987
5988        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5989
5990        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5991                true /* requireFullPermission */, true /* checkShell */,
5992                "updatePermissionFlagsForAllApps");
5993
5994        // Only the system can change system fixed flags.
5995        if (getCallingUid() != Process.SYSTEM_UID) {
5996            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5997            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5998        }
5999
6000        synchronized (mPackages) {
6001            boolean changed = false;
6002            final int packageCount = mPackages.size();
6003            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6004                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6005                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6006                if (ps == null) {
6007                    continue;
6008                }
6009                PermissionsState permissionsState = ps.getPermissionsState();
6010                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6011                        userId, flagMask, flagValues);
6012            }
6013            if (changed) {
6014                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6015            }
6016        }
6017    }
6018
6019    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6020        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6021                != PackageManager.PERMISSION_GRANTED
6022            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6023                != PackageManager.PERMISSION_GRANTED) {
6024            throw new SecurityException(message + " requires "
6025                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6026                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6027        }
6028    }
6029
6030    @Override
6031    public boolean shouldShowRequestPermissionRationale(String permissionName,
6032            String packageName, int userId) {
6033        if (UserHandle.getCallingUserId() != userId) {
6034            mContext.enforceCallingPermission(
6035                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6036                    "canShowRequestPermissionRationale for user " + userId);
6037        }
6038
6039        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6040        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6041            return false;
6042        }
6043
6044        if (checkPermission(permissionName, packageName, userId)
6045                == PackageManager.PERMISSION_GRANTED) {
6046            return false;
6047        }
6048
6049        final int flags;
6050
6051        final long identity = Binder.clearCallingIdentity();
6052        try {
6053            flags = getPermissionFlags(permissionName,
6054                    packageName, userId);
6055        } finally {
6056            Binder.restoreCallingIdentity(identity);
6057        }
6058
6059        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6060                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6061                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6062
6063        if ((flags & fixedFlags) != 0) {
6064            return false;
6065        }
6066
6067        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6068    }
6069
6070    @Override
6071    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6072        mContext.enforceCallingOrSelfPermission(
6073                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6074                "addOnPermissionsChangeListener");
6075
6076        synchronized (mPackages) {
6077            mOnPermissionChangeListeners.addListenerLocked(listener);
6078        }
6079    }
6080
6081    @Override
6082    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6083        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6084            throw new SecurityException("Instant applications don't have access to this method");
6085        }
6086        synchronized (mPackages) {
6087            mOnPermissionChangeListeners.removeListenerLocked(listener);
6088        }
6089    }
6090
6091    @Override
6092    public boolean isProtectedBroadcast(String actionName) {
6093        // allow instant applications
6094        synchronized (mProtectedBroadcasts) {
6095            if (mProtectedBroadcasts.contains(actionName)) {
6096                return true;
6097            } else if (actionName != null) {
6098                // TODO: remove these terrible hacks
6099                if (actionName.startsWith("android.net.netmon.lingerExpired")
6100                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6101                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6102                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6103                    return true;
6104                }
6105            }
6106        }
6107        return false;
6108    }
6109
6110    @Override
6111    public int checkSignatures(String pkg1, String pkg2) {
6112        synchronized (mPackages) {
6113            final PackageParser.Package p1 = mPackages.get(pkg1);
6114            final PackageParser.Package p2 = mPackages.get(pkg2);
6115            if (p1 == null || p1.mExtras == null
6116                    || p2 == null || p2.mExtras == null) {
6117                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6118            }
6119            final int callingUid = Binder.getCallingUid();
6120            final int callingUserId = UserHandle.getUserId(callingUid);
6121            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6122            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6123            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6124                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6125                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6126            }
6127            return compareSignatures(p1.mSignatures, p2.mSignatures);
6128        }
6129    }
6130
6131    @Override
6132    public int checkUidSignatures(int uid1, int uid2) {
6133        final int callingUid = Binder.getCallingUid();
6134        final int callingUserId = UserHandle.getUserId(callingUid);
6135        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6136        // Map to base uids.
6137        uid1 = UserHandle.getAppId(uid1);
6138        uid2 = UserHandle.getAppId(uid2);
6139        // reader
6140        synchronized (mPackages) {
6141            Signature[] s1;
6142            Signature[] s2;
6143            Object obj = mSettings.getUserIdLPr(uid1);
6144            if (obj != null) {
6145                if (obj instanceof SharedUserSetting) {
6146                    if (isCallerInstantApp) {
6147                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6148                    }
6149                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6150                } else if (obj instanceof PackageSetting) {
6151                    final PackageSetting ps = (PackageSetting) obj;
6152                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6153                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6154                    }
6155                    s1 = ps.signatures.mSignatures;
6156                } else {
6157                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6158                }
6159            } else {
6160                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6161            }
6162            obj = mSettings.getUserIdLPr(uid2);
6163            if (obj != null) {
6164                if (obj instanceof SharedUserSetting) {
6165                    if (isCallerInstantApp) {
6166                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6167                    }
6168                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6169                } else if (obj instanceof PackageSetting) {
6170                    final PackageSetting ps = (PackageSetting) obj;
6171                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6172                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6173                    }
6174                    s2 = ps.signatures.mSignatures;
6175                } else {
6176                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6177                }
6178            } else {
6179                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6180            }
6181            return compareSignatures(s1, s2);
6182        }
6183    }
6184
6185    /**
6186     * This method should typically only be used when granting or revoking
6187     * permissions, since the app may immediately restart after this call.
6188     * <p>
6189     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6190     * guard your work against the app being relaunched.
6191     */
6192    private void killUid(int appId, int userId, String reason) {
6193        final long identity = Binder.clearCallingIdentity();
6194        try {
6195            IActivityManager am = ActivityManager.getService();
6196            if (am != null) {
6197                try {
6198                    am.killUid(appId, userId, reason);
6199                } catch (RemoteException e) {
6200                    /* ignore - same process */
6201                }
6202            }
6203        } finally {
6204            Binder.restoreCallingIdentity(identity);
6205        }
6206    }
6207
6208    /**
6209     * Compares two sets of signatures. Returns:
6210     * <br />
6211     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6212     * <br />
6213     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6214     * <br />
6215     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6216     * <br />
6217     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6218     * <br />
6219     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6220     */
6221    static int compareSignatures(Signature[] s1, Signature[] s2) {
6222        if (s1 == null) {
6223            return s2 == null
6224                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6225                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6226        }
6227
6228        if (s2 == null) {
6229            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6230        }
6231
6232        if (s1.length != s2.length) {
6233            return PackageManager.SIGNATURE_NO_MATCH;
6234        }
6235
6236        // Since both signature sets are of size 1, we can compare without HashSets.
6237        if (s1.length == 1) {
6238            return s1[0].equals(s2[0]) ?
6239                    PackageManager.SIGNATURE_MATCH :
6240                    PackageManager.SIGNATURE_NO_MATCH;
6241        }
6242
6243        ArraySet<Signature> set1 = new ArraySet<Signature>();
6244        for (Signature sig : s1) {
6245            set1.add(sig);
6246        }
6247        ArraySet<Signature> set2 = new ArraySet<Signature>();
6248        for (Signature sig : s2) {
6249            set2.add(sig);
6250        }
6251        // Make sure s2 contains all signatures in s1.
6252        if (set1.equals(set2)) {
6253            return PackageManager.SIGNATURE_MATCH;
6254        }
6255        return PackageManager.SIGNATURE_NO_MATCH;
6256    }
6257
6258    /**
6259     * If the database version for this type of package (internal storage or
6260     * external storage) is less than the version where package signatures
6261     * were updated, return true.
6262     */
6263    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6264        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6265        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6266    }
6267
6268    /**
6269     * Used for backward compatibility to make sure any packages with
6270     * certificate chains get upgraded to the new style. {@code existingSigs}
6271     * will be in the old format (since they were stored on disk from before the
6272     * system upgrade) and {@code scannedSigs} will be in the newer format.
6273     */
6274    private int compareSignaturesCompat(PackageSignatures existingSigs,
6275            PackageParser.Package scannedPkg) {
6276        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6277            return PackageManager.SIGNATURE_NO_MATCH;
6278        }
6279
6280        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6281        for (Signature sig : existingSigs.mSignatures) {
6282            existingSet.add(sig);
6283        }
6284        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6285        for (Signature sig : scannedPkg.mSignatures) {
6286            try {
6287                Signature[] chainSignatures = sig.getChainSignatures();
6288                for (Signature chainSig : chainSignatures) {
6289                    scannedCompatSet.add(chainSig);
6290                }
6291            } catch (CertificateEncodingException e) {
6292                scannedCompatSet.add(sig);
6293            }
6294        }
6295        /*
6296         * Make sure the expanded scanned set contains all signatures in the
6297         * existing one.
6298         */
6299        if (scannedCompatSet.equals(existingSet)) {
6300            // Migrate the old signatures to the new scheme.
6301            existingSigs.assignSignatures(scannedPkg.mSignatures);
6302            // The new KeySets will be re-added later in the scanning process.
6303            synchronized (mPackages) {
6304                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6305            }
6306            return PackageManager.SIGNATURE_MATCH;
6307        }
6308        return PackageManager.SIGNATURE_NO_MATCH;
6309    }
6310
6311    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6312        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6313        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6314    }
6315
6316    private int compareSignaturesRecover(PackageSignatures existingSigs,
6317            PackageParser.Package scannedPkg) {
6318        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6319            return PackageManager.SIGNATURE_NO_MATCH;
6320        }
6321
6322        String msg = null;
6323        try {
6324            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6325                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6326                        + scannedPkg.packageName);
6327                return PackageManager.SIGNATURE_MATCH;
6328            }
6329        } catch (CertificateException e) {
6330            msg = e.getMessage();
6331        }
6332
6333        logCriticalInfo(Log.INFO,
6334                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6335        return PackageManager.SIGNATURE_NO_MATCH;
6336    }
6337
6338    @Override
6339    public List<String> getAllPackages() {
6340        final int callingUid = Binder.getCallingUid();
6341        final int callingUserId = UserHandle.getUserId(callingUid);
6342        synchronized (mPackages) {
6343            if (canViewInstantApps(callingUid, callingUserId)) {
6344                return new ArrayList<String>(mPackages.keySet());
6345            }
6346            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6347            final List<String> result = new ArrayList<>();
6348            if (instantAppPkgName != null) {
6349                // caller is an instant application; filter unexposed applications
6350                for (PackageParser.Package pkg : mPackages.values()) {
6351                    if (!pkg.visibleToInstantApps) {
6352                        continue;
6353                    }
6354                    result.add(pkg.packageName);
6355                }
6356            } else {
6357                // caller is a normal application; filter instant applications
6358                for (PackageParser.Package pkg : mPackages.values()) {
6359                    final PackageSetting ps =
6360                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6361                    if (ps != null
6362                            && ps.getInstantApp(callingUserId)
6363                            && !mInstantAppRegistry.isInstantAccessGranted(
6364                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6365                        continue;
6366                    }
6367                    result.add(pkg.packageName);
6368                }
6369            }
6370            return result;
6371        }
6372    }
6373
6374    @Override
6375    public String[] getPackagesForUid(int uid) {
6376        final int callingUid = Binder.getCallingUid();
6377        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6378        final int userId = UserHandle.getUserId(uid);
6379        uid = UserHandle.getAppId(uid);
6380        // reader
6381        synchronized (mPackages) {
6382            Object obj = mSettings.getUserIdLPr(uid);
6383            if (obj instanceof SharedUserSetting) {
6384                if (isCallerInstantApp) {
6385                    return null;
6386                }
6387                final SharedUserSetting sus = (SharedUserSetting) obj;
6388                final int N = sus.packages.size();
6389                String[] res = new String[N];
6390                final Iterator<PackageSetting> it = sus.packages.iterator();
6391                int i = 0;
6392                while (it.hasNext()) {
6393                    PackageSetting ps = it.next();
6394                    if (ps.getInstalled(userId)) {
6395                        res[i++] = ps.name;
6396                    } else {
6397                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6398                    }
6399                }
6400                return res;
6401            } else if (obj instanceof PackageSetting) {
6402                final PackageSetting ps = (PackageSetting) obj;
6403                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6404                    return new String[]{ps.name};
6405                }
6406            }
6407        }
6408        return null;
6409    }
6410
6411    @Override
6412    public String getNameForUid(int uid) {
6413        final int callingUid = Binder.getCallingUid();
6414        if (getInstantAppPackageName(callingUid) != null) {
6415            return null;
6416        }
6417        synchronized (mPackages) {
6418            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6419            if (obj instanceof SharedUserSetting) {
6420                final SharedUserSetting sus = (SharedUserSetting) obj;
6421                return sus.name + ":" + sus.userId;
6422            } else if (obj instanceof PackageSetting) {
6423                final PackageSetting ps = (PackageSetting) obj;
6424                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6425                    return null;
6426                }
6427                return ps.name;
6428            }
6429            return null;
6430        }
6431    }
6432
6433    @Override
6434    public String[] getNamesForUids(int[] uids) {
6435        if (uids == null || uids.length == 0) {
6436            return null;
6437        }
6438        final int callingUid = Binder.getCallingUid();
6439        if (getInstantAppPackageName(callingUid) != null) {
6440            return null;
6441        }
6442        final String[] names = new String[uids.length];
6443        synchronized (mPackages) {
6444            for (int i = uids.length - 1; i >= 0; i--) {
6445                final int uid = uids[i];
6446                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6447                if (obj instanceof SharedUserSetting) {
6448                    final SharedUserSetting sus = (SharedUserSetting) obj;
6449                    names[i] = "shared:" + sus.name;
6450                } else if (obj instanceof PackageSetting) {
6451                    final PackageSetting ps = (PackageSetting) obj;
6452                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6453                        names[i] = null;
6454                    } else {
6455                        names[i] = ps.name;
6456                    }
6457                } else {
6458                    names[i] = null;
6459                }
6460            }
6461        }
6462        return names;
6463    }
6464
6465    @Override
6466    public int getUidForSharedUser(String sharedUserName) {
6467        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6468            return -1;
6469        }
6470        if (sharedUserName == null) {
6471            return -1;
6472        }
6473        // reader
6474        synchronized (mPackages) {
6475            SharedUserSetting suid;
6476            try {
6477                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6478                if (suid != null) {
6479                    return suid.userId;
6480                }
6481            } catch (PackageManagerException ignore) {
6482                // can't happen, but, still need to catch it
6483            }
6484            return -1;
6485        }
6486    }
6487
6488    @Override
6489    public int getFlagsForUid(int uid) {
6490        final int callingUid = Binder.getCallingUid();
6491        if (getInstantAppPackageName(callingUid) != null) {
6492            return 0;
6493        }
6494        synchronized (mPackages) {
6495            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6496            if (obj instanceof SharedUserSetting) {
6497                final SharedUserSetting sus = (SharedUserSetting) obj;
6498                return sus.pkgFlags;
6499            } else if (obj instanceof PackageSetting) {
6500                final PackageSetting ps = (PackageSetting) obj;
6501                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6502                    return 0;
6503                }
6504                return ps.pkgFlags;
6505            }
6506        }
6507        return 0;
6508    }
6509
6510    @Override
6511    public int getPrivateFlagsForUid(int uid) {
6512        final int callingUid = Binder.getCallingUid();
6513        if (getInstantAppPackageName(callingUid) != null) {
6514            return 0;
6515        }
6516        synchronized (mPackages) {
6517            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6518            if (obj instanceof SharedUserSetting) {
6519                final SharedUserSetting sus = (SharedUserSetting) obj;
6520                return sus.pkgPrivateFlags;
6521            } else if (obj instanceof PackageSetting) {
6522                final PackageSetting ps = (PackageSetting) obj;
6523                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6524                    return 0;
6525                }
6526                return ps.pkgPrivateFlags;
6527            }
6528        }
6529        return 0;
6530    }
6531
6532    @Override
6533    public boolean isUidPrivileged(int uid) {
6534        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6535            return false;
6536        }
6537        uid = UserHandle.getAppId(uid);
6538        // reader
6539        synchronized (mPackages) {
6540            Object obj = mSettings.getUserIdLPr(uid);
6541            if (obj instanceof SharedUserSetting) {
6542                final SharedUserSetting sus = (SharedUserSetting) obj;
6543                final Iterator<PackageSetting> it = sus.packages.iterator();
6544                while (it.hasNext()) {
6545                    if (it.next().isPrivileged()) {
6546                        return true;
6547                    }
6548                }
6549            } else if (obj instanceof PackageSetting) {
6550                final PackageSetting ps = (PackageSetting) obj;
6551                return ps.isPrivileged();
6552            }
6553        }
6554        return false;
6555    }
6556
6557    @Override
6558    public String[] getAppOpPermissionPackages(String permissionName) {
6559        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6560            return null;
6561        }
6562        synchronized (mPackages) {
6563            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6564            if (pkgs == null) {
6565                return null;
6566            }
6567            return pkgs.toArray(new String[pkgs.size()]);
6568        }
6569    }
6570
6571    @Override
6572    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6573            int flags, int userId) {
6574        return resolveIntentInternal(
6575                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6576    }
6577
6578    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6579            int flags, int userId, boolean resolveForStart) {
6580        try {
6581            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6582
6583            if (!sUserManager.exists(userId)) return null;
6584            final int callingUid = Binder.getCallingUid();
6585            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6586            enforceCrossUserPermission(callingUid, userId,
6587                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6588
6589            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6590            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6591                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6592            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6593
6594            final ResolveInfo bestChoice =
6595                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6596            return bestChoice;
6597        } finally {
6598            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6599        }
6600    }
6601
6602    @Override
6603    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6604        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6605            throw new SecurityException(
6606                    "findPersistentPreferredActivity can only be run by the system");
6607        }
6608        if (!sUserManager.exists(userId)) {
6609            return null;
6610        }
6611        final int callingUid = Binder.getCallingUid();
6612        intent = updateIntentForResolve(intent);
6613        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6614        final int flags = updateFlagsForResolve(
6615                0, userId, intent, callingUid, false /*includeInstantApps*/);
6616        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6617                userId);
6618        synchronized (mPackages) {
6619            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6620                    userId);
6621        }
6622    }
6623
6624    @Override
6625    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6626            IntentFilter filter, int match, ComponentName activity) {
6627        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6628            return;
6629        }
6630        final int userId = UserHandle.getCallingUserId();
6631        if (DEBUG_PREFERRED) {
6632            Log.v(TAG, "setLastChosenActivity intent=" + intent
6633                + " resolvedType=" + resolvedType
6634                + " flags=" + flags
6635                + " filter=" + filter
6636                + " match=" + match
6637                + " activity=" + activity);
6638            filter.dump(new PrintStreamPrinter(System.out), "    ");
6639        }
6640        intent.setComponent(null);
6641        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6642                userId);
6643        // Find any earlier preferred or last chosen entries and nuke them
6644        findPreferredActivity(intent, resolvedType,
6645                flags, query, 0, false, true, false, userId);
6646        // Add the new activity as the last chosen for this filter
6647        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6648                "Setting last chosen");
6649    }
6650
6651    @Override
6652    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6653        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6654            return null;
6655        }
6656        final int userId = UserHandle.getCallingUserId();
6657        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6658        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6659                userId);
6660        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6661                false, false, false, userId);
6662    }
6663
6664    /**
6665     * Returns whether or not instant apps have been disabled remotely.
6666     */
6667    private boolean isEphemeralDisabled() {
6668        return mEphemeralAppsDisabled;
6669    }
6670
6671    private boolean isInstantAppAllowed(
6672            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6673            boolean skipPackageCheck) {
6674        if (mInstantAppResolverConnection == null) {
6675            return false;
6676        }
6677        if (mInstantAppInstallerActivity == null) {
6678            return false;
6679        }
6680        if (intent.getComponent() != null) {
6681            return false;
6682        }
6683        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6684            return false;
6685        }
6686        if (!skipPackageCheck && intent.getPackage() != null) {
6687            return false;
6688        }
6689        final boolean isWebUri = hasWebURI(intent);
6690        if (!isWebUri || intent.getData().getHost() == null) {
6691            return false;
6692        }
6693        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6694        // Or if there's already an ephemeral app installed that handles the action
6695        synchronized (mPackages) {
6696            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6697            for (int n = 0; n < count; n++) {
6698                final ResolveInfo info = resolvedActivities.get(n);
6699                final String packageName = info.activityInfo.packageName;
6700                final PackageSetting ps = mSettings.mPackages.get(packageName);
6701                if (ps != null) {
6702                    // only check domain verification status if the app is not a browser
6703                    if (!info.handleAllWebDataURI) {
6704                        // Try to get the status from User settings first
6705                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6706                        final int status = (int) (packedStatus >> 32);
6707                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6708                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6709                            if (DEBUG_EPHEMERAL) {
6710                                Slog.v(TAG, "DENY instant app;"
6711                                    + " pkg: " + packageName + ", status: " + status);
6712                            }
6713                            return false;
6714                        }
6715                    }
6716                    if (ps.getInstantApp(userId)) {
6717                        if (DEBUG_EPHEMERAL) {
6718                            Slog.v(TAG, "DENY instant app installed;"
6719                                    + " pkg: " + packageName);
6720                        }
6721                        return false;
6722                    }
6723                }
6724            }
6725        }
6726        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6727        return true;
6728    }
6729
6730    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6731            Intent origIntent, String resolvedType, String callingPackage,
6732            Bundle verificationBundle, int userId) {
6733        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6734                new InstantAppRequest(responseObj, origIntent, resolvedType,
6735                        callingPackage, userId, verificationBundle));
6736        mHandler.sendMessage(msg);
6737    }
6738
6739    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6740            int flags, List<ResolveInfo> query, int userId) {
6741        if (query != null) {
6742            final int N = query.size();
6743            if (N == 1) {
6744                return query.get(0);
6745            } else if (N > 1) {
6746                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6747                // If there is more than one activity with the same priority,
6748                // then let the user decide between them.
6749                ResolveInfo r0 = query.get(0);
6750                ResolveInfo r1 = query.get(1);
6751                if (DEBUG_INTENT_MATCHING || debug) {
6752                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6753                            + r1.activityInfo.name + "=" + r1.priority);
6754                }
6755                // If the first activity has a higher priority, or a different
6756                // default, then it is always desirable to pick it.
6757                if (r0.priority != r1.priority
6758                        || r0.preferredOrder != r1.preferredOrder
6759                        || r0.isDefault != r1.isDefault) {
6760                    return query.get(0);
6761                }
6762                // If we have saved a preference for a preferred activity for
6763                // this Intent, use that.
6764                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6765                        flags, query, r0.priority, true, false, debug, userId);
6766                if (ri != null) {
6767                    return ri;
6768                }
6769                // If we have an ephemeral app, use it
6770                for (int i = 0; i < N; i++) {
6771                    ri = query.get(i);
6772                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6773                        final String packageName = ri.activityInfo.packageName;
6774                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6775                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6776                        final int status = (int)(packedStatus >> 32);
6777                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6778                            return ri;
6779                        }
6780                    }
6781                }
6782                ri = new ResolveInfo(mResolveInfo);
6783                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6784                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6785                // If all of the options come from the same package, show the application's
6786                // label and icon instead of the generic resolver's.
6787                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6788                // and then throw away the ResolveInfo itself, meaning that the caller loses
6789                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6790                // a fallback for this case; we only set the target package's resources on
6791                // the ResolveInfo, not the ActivityInfo.
6792                final String intentPackage = intent.getPackage();
6793                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6794                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6795                    ri.resolvePackageName = intentPackage;
6796                    if (userNeedsBadging(userId)) {
6797                        ri.noResourceId = true;
6798                    } else {
6799                        ri.icon = appi.icon;
6800                    }
6801                    ri.iconResourceId = appi.icon;
6802                    ri.labelRes = appi.labelRes;
6803                }
6804                ri.activityInfo.applicationInfo = new ApplicationInfo(
6805                        ri.activityInfo.applicationInfo);
6806                if (userId != 0) {
6807                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6808                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6809                }
6810                // Make sure that the resolver is displayable in car mode
6811                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6812                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6813                return ri;
6814            }
6815        }
6816        return null;
6817    }
6818
6819    /**
6820     * Return true if the given list is not empty and all of its contents have
6821     * an activityInfo with the given package name.
6822     */
6823    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6824        if (ArrayUtils.isEmpty(list)) {
6825            return false;
6826        }
6827        for (int i = 0, N = list.size(); i < N; i++) {
6828            final ResolveInfo ri = list.get(i);
6829            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6830            if (ai == null || !packageName.equals(ai.packageName)) {
6831                return false;
6832            }
6833        }
6834        return true;
6835    }
6836
6837    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6838            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6839        final int N = query.size();
6840        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6841                .get(userId);
6842        // Get the list of persistent preferred activities that handle the intent
6843        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6844        List<PersistentPreferredActivity> pprefs = ppir != null
6845                ? ppir.queryIntent(intent, resolvedType,
6846                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6847                        userId)
6848                : null;
6849        if (pprefs != null && pprefs.size() > 0) {
6850            final int M = pprefs.size();
6851            for (int i=0; i<M; i++) {
6852                final PersistentPreferredActivity ppa = pprefs.get(i);
6853                if (DEBUG_PREFERRED || debug) {
6854                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6855                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6856                            + "\n  component=" + ppa.mComponent);
6857                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6858                }
6859                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6860                        flags | MATCH_DISABLED_COMPONENTS, userId);
6861                if (DEBUG_PREFERRED || debug) {
6862                    Slog.v(TAG, "Found persistent preferred activity:");
6863                    if (ai != null) {
6864                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6865                    } else {
6866                        Slog.v(TAG, "  null");
6867                    }
6868                }
6869                if (ai == null) {
6870                    // This previously registered persistent preferred activity
6871                    // component is no longer known. Ignore it and do NOT remove it.
6872                    continue;
6873                }
6874                for (int j=0; j<N; j++) {
6875                    final ResolveInfo ri = query.get(j);
6876                    if (!ri.activityInfo.applicationInfo.packageName
6877                            .equals(ai.applicationInfo.packageName)) {
6878                        continue;
6879                    }
6880                    if (!ri.activityInfo.name.equals(ai.name)) {
6881                        continue;
6882                    }
6883                    //  Found a persistent preference that can handle the intent.
6884                    if (DEBUG_PREFERRED || debug) {
6885                        Slog.v(TAG, "Returning persistent preferred activity: " +
6886                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6887                    }
6888                    return ri;
6889                }
6890            }
6891        }
6892        return null;
6893    }
6894
6895    // TODO: handle preferred activities missing while user has amnesia
6896    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6897            List<ResolveInfo> query, int priority, boolean always,
6898            boolean removeMatches, boolean debug, int userId) {
6899        if (!sUserManager.exists(userId)) return null;
6900        final int callingUid = Binder.getCallingUid();
6901        flags = updateFlagsForResolve(
6902                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6903        intent = updateIntentForResolve(intent);
6904        // writer
6905        synchronized (mPackages) {
6906            // Try to find a matching persistent preferred activity.
6907            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6908                    debug, userId);
6909
6910            // If a persistent preferred activity matched, use it.
6911            if (pri != null) {
6912                return pri;
6913            }
6914
6915            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6916            // Get the list of preferred activities that handle the intent
6917            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6918            List<PreferredActivity> prefs = pir != null
6919                    ? pir.queryIntent(intent, resolvedType,
6920                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6921                            userId)
6922                    : null;
6923            if (prefs != null && prefs.size() > 0) {
6924                boolean changed = false;
6925                try {
6926                    // First figure out how good the original match set is.
6927                    // We will only allow preferred activities that came
6928                    // from the same match quality.
6929                    int match = 0;
6930
6931                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6932
6933                    final int N = query.size();
6934                    for (int j=0; j<N; j++) {
6935                        final ResolveInfo ri = query.get(j);
6936                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6937                                + ": 0x" + Integer.toHexString(match));
6938                        if (ri.match > match) {
6939                            match = ri.match;
6940                        }
6941                    }
6942
6943                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6944                            + Integer.toHexString(match));
6945
6946                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6947                    final int M = prefs.size();
6948                    for (int i=0; i<M; i++) {
6949                        final PreferredActivity pa = prefs.get(i);
6950                        if (DEBUG_PREFERRED || debug) {
6951                            Slog.v(TAG, "Checking PreferredActivity ds="
6952                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6953                                    + "\n  component=" + pa.mPref.mComponent);
6954                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6955                        }
6956                        if (pa.mPref.mMatch != match) {
6957                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6958                                    + Integer.toHexString(pa.mPref.mMatch));
6959                            continue;
6960                        }
6961                        // If it's not an "always" type preferred activity and that's what we're
6962                        // looking for, skip it.
6963                        if (always && !pa.mPref.mAlways) {
6964                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6965                            continue;
6966                        }
6967                        final ActivityInfo ai = getActivityInfo(
6968                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6969                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6970                                userId);
6971                        if (DEBUG_PREFERRED || debug) {
6972                            Slog.v(TAG, "Found preferred activity:");
6973                            if (ai != null) {
6974                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6975                            } else {
6976                                Slog.v(TAG, "  null");
6977                            }
6978                        }
6979                        if (ai == null) {
6980                            // This previously registered preferred activity
6981                            // component is no longer known.  Most likely an update
6982                            // to the app was installed and in the new version this
6983                            // component no longer exists.  Clean it up by removing
6984                            // it from the preferred activities list, and skip it.
6985                            Slog.w(TAG, "Removing dangling preferred activity: "
6986                                    + pa.mPref.mComponent);
6987                            pir.removeFilter(pa);
6988                            changed = true;
6989                            continue;
6990                        }
6991                        for (int j=0; j<N; j++) {
6992                            final ResolveInfo ri = query.get(j);
6993                            if (!ri.activityInfo.applicationInfo.packageName
6994                                    .equals(ai.applicationInfo.packageName)) {
6995                                continue;
6996                            }
6997                            if (!ri.activityInfo.name.equals(ai.name)) {
6998                                continue;
6999                            }
7000
7001                            if (removeMatches) {
7002                                pir.removeFilter(pa);
7003                                changed = true;
7004                                if (DEBUG_PREFERRED) {
7005                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7006                                }
7007                                break;
7008                            }
7009
7010                            // Okay we found a previously set preferred or last chosen app.
7011                            // If the result set is different from when this
7012                            // was created, we need to clear it and re-ask the
7013                            // user their preference, if we're looking for an "always" type entry.
7014                            if (always && !pa.mPref.sameSet(query)) {
7015                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
7016                                        + intent + " type " + resolvedType);
7017                                if (DEBUG_PREFERRED) {
7018                                    Slog.v(TAG, "Removing preferred activity since set changed "
7019                                            + pa.mPref.mComponent);
7020                                }
7021                                pir.removeFilter(pa);
7022                                // Re-add the filter as a "last chosen" entry (!always)
7023                                PreferredActivity lastChosen = new PreferredActivity(
7024                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7025                                pir.addFilter(lastChosen);
7026                                changed = true;
7027                                return null;
7028                            }
7029
7030                            // Yay! Either the set matched or we're looking for the last chosen
7031                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7032                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7033                            return ri;
7034                        }
7035                    }
7036                } finally {
7037                    if (changed) {
7038                        if (DEBUG_PREFERRED) {
7039                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7040                        }
7041                        scheduleWritePackageRestrictionsLocked(userId);
7042                    }
7043                }
7044            }
7045        }
7046        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7047        return null;
7048    }
7049
7050    /*
7051     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7052     */
7053    @Override
7054    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7055            int targetUserId) {
7056        mContext.enforceCallingOrSelfPermission(
7057                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7058        List<CrossProfileIntentFilter> matches =
7059                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7060        if (matches != null) {
7061            int size = matches.size();
7062            for (int i = 0; i < size; i++) {
7063                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7064            }
7065        }
7066        if (hasWebURI(intent)) {
7067            // cross-profile app linking works only towards the parent.
7068            final int callingUid = Binder.getCallingUid();
7069            final UserInfo parent = getProfileParent(sourceUserId);
7070            synchronized(mPackages) {
7071                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7072                        false /*includeInstantApps*/);
7073                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7074                        intent, resolvedType, flags, sourceUserId, parent.id);
7075                return xpDomainInfo != null;
7076            }
7077        }
7078        return false;
7079    }
7080
7081    private UserInfo getProfileParent(int userId) {
7082        final long identity = Binder.clearCallingIdentity();
7083        try {
7084            return sUserManager.getProfileParent(userId);
7085        } finally {
7086            Binder.restoreCallingIdentity(identity);
7087        }
7088    }
7089
7090    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7091            String resolvedType, int userId) {
7092        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7093        if (resolver != null) {
7094            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7095        }
7096        return null;
7097    }
7098
7099    @Override
7100    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7101            String resolvedType, int flags, int userId) {
7102        try {
7103            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7104
7105            return new ParceledListSlice<>(
7106                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7107        } finally {
7108            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7109        }
7110    }
7111
7112    /**
7113     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7114     * instant, returns {@code null}.
7115     */
7116    private String getInstantAppPackageName(int callingUid) {
7117        synchronized (mPackages) {
7118            // If the caller is an isolated app use the owner's uid for the lookup.
7119            if (Process.isIsolated(callingUid)) {
7120                callingUid = mIsolatedOwners.get(callingUid);
7121            }
7122            final int appId = UserHandle.getAppId(callingUid);
7123            final Object obj = mSettings.getUserIdLPr(appId);
7124            if (obj instanceof PackageSetting) {
7125                final PackageSetting ps = (PackageSetting) obj;
7126                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7127                return isInstantApp ? ps.pkg.packageName : null;
7128            }
7129        }
7130        return null;
7131    }
7132
7133    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7134            String resolvedType, int flags, int userId) {
7135        return queryIntentActivitiesInternal(
7136                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7137                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7138    }
7139
7140    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7141            String resolvedType, int flags, int filterCallingUid, int userId,
7142            boolean resolveForStart, boolean allowDynamicSplits) {
7143        if (!sUserManager.exists(userId)) return Collections.emptyList();
7144        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7145        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7146                false /* requireFullPermission */, false /* checkShell */,
7147                "query intent activities");
7148        final String pkgName = intent.getPackage();
7149        ComponentName comp = intent.getComponent();
7150        if (comp == null) {
7151            if (intent.getSelector() != null) {
7152                intent = intent.getSelector();
7153                comp = intent.getComponent();
7154            }
7155        }
7156
7157        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7158                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7159        if (comp != null) {
7160            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7161            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7162            if (ai != null) {
7163                // When specifying an explicit component, we prevent the activity from being
7164                // used when either 1) the calling package is normal and the activity is within
7165                // an ephemeral application or 2) the calling package is ephemeral and the
7166                // activity is not visible to ephemeral applications.
7167                final boolean matchInstantApp =
7168                        (flags & PackageManager.MATCH_INSTANT) != 0;
7169                final boolean matchVisibleToInstantAppOnly =
7170                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7171                final boolean matchExplicitlyVisibleOnly =
7172                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7173                final boolean isCallerInstantApp =
7174                        instantAppPkgName != null;
7175                final boolean isTargetSameInstantApp =
7176                        comp.getPackageName().equals(instantAppPkgName);
7177                final boolean isTargetInstantApp =
7178                        (ai.applicationInfo.privateFlags
7179                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7180                final boolean isTargetVisibleToInstantApp =
7181                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7182                final boolean isTargetExplicitlyVisibleToInstantApp =
7183                        isTargetVisibleToInstantApp
7184                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7185                final boolean isTargetHiddenFromInstantApp =
7186                        !isTargetVisibleToInstantApp
7187                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7188                final boolean blockResolution =
7189                        !isTargetSameInstantApp
7190                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7191                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7192                                        && isTargetHiddenFromInstantApp));
7193                if (!blockResolution) {
7194                    final ResolveInfo ri = new ResolveInfo();
7195                    ri.activityInfo = ai;
7196                    list.add(ri);
7197                }
7198            }
7199            return applyPostResolutionFilter(
7200                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7201        }
7202
7203        // reader
7204        boolean sortResult = false;
7205        boolean addEphemeral = false;
7206        List<ResolveInfo> result;
7207        final boolean ephemeralDisabled = isEphemeralDisabled();
7208        synchronized (mPackages) {
7209            if (pkgName == null) {
7210                List<CrossProfileIntentFilter> matchingFilters =
7211                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7212                // Check for results that need to skip the current profile.
7213                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7214                        resolvedType, flags, userId);
7215                if (xpResolveInfo != null) {
7216                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7217                    xpResult.add(xpResolveInfo);
7218                    return applyPostResolutionFilter(
7219                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7220                            allowDynamicSplits, filterCallingUid, userId);
7221                }
7222
7223                // Check for results in the current profile.
7224                result = filterIfNotSystemUser(mActivities.queryIntent(
7225                        intent, resolvedType, flags, userId), userId);
7226                addEphemeral = !ephemeralDisabled
7227                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7228                // Check for cross profile results.
7229                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7230                xpResolveInfo = queryCrossProfileIntents(
7231                        matchingFilters, intent, resolvedType, flags, userId,
7232                        hasNonNegativePriorityResult);
7233                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7234                    boolean isVisibleToUser = filterIfNotSystemUser(
7235                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7236                    if (isVisibleToUser) {
7237                        result.add(xpResolveInfo);
7238                        sortResult = true;
7239                    }
7240                }
7241                if (hasWebURI(intent)) {
7242                    CrossProfileDomainInfo xpDomainInfo = null;
7243                    final UserInfo parent = getProfileParent(userId);
7244                    if (parent != null) {
7245                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7246                                flags, userId, parent.id);
7247                    }
7248                    if (xpDomainInfo != null) {
7249                        if (xpResolveInfo != null) {
7250                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7251                            // in the result.
7252                            result.remove(xpResolveInfo);
7253                        }
7254                        if (result.size() == 0 && !addEphemeral) {
7255                            // No result in current profile, but found candidate in parent user.
7256                            // And we are not going to add emphemeral app, so we can return the
7257                            // result straight away.
7258                            result.add(xpDomainInfo.resolveInfo);
7259                            return applyPostResolutionFilter(result, instantAppPkgName,
7260                                    allowDynamicSplits, filterCallingUid, userId);
7261                        }
7262                    } else if (result.size() <= 1 && !addEphemeral) {
7263                        // No result in parent user and <= 1 result in current profile, and we
7264                        // are not going to add emphemeral app, so we can return the result without
7265                        // further processing.
7266                        return applyPostResolutionFilter(result, instantAppPkgName,
7267                                allowDynamicSplits, filterCallingUid, userId);
7268                    }
7269                    // We have more than one candidate (combining results from current and parent
7270                    // profile), so we need filtering and sorting.
7271                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7272                            intent, flags, result, xpDomainInfo, userId);
7273                    sortResult = true;
7274                }
7275            } else {
7276                final PackageParser.Package pkg = mPackages.get(pkgName);
7277                result = null;
7278                if (pkg != null) {
7279                    result = filterIfNotSystemUser(
7280                            mActivities.queryIntentForPackage(
7281                                    intent, resolvedType, flags, pkg.activities, userId),
7282                            userId);
7283                }
7284                if (result == null || result.size() == 0) {
7285                    // the caller wants to resolve for a particular package; however, there
7286                    // were no installed results, so, try to find an ephemeral result
7287                    addEphemeral = !ephemeralDisabled
7288                            && isInstantAppAllowed(
7289                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7290                    if (result == null) {
7291                        result = new ArrayList<>();
7292                    }
7293                }
7294            }
7295        }
7296        if (addEphemeral) {
7297            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7298        }
7299        if (sortResult) {
7300            Collections.sort(result, mResolvePrioritySorter);
7301        }
7302        return applyPostResolutionFilter(
7303                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7304    }
7305
7306    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7307            String resolvedType, int flags, int userId) {
7308        // first, check to see if we've got an instant app already installed
7309        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7310        ResolveInfo localInstantApp = null;
7311        boolean blockResolution = false;
7312        if (!alreadyResolvedLocally) {
7313            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7314                    flags
7315                        | PackageManager.GET_RESOLVED_FILTER
7316                        | PackageManager.MATCH_INSTANT
7317                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7318                    userId);
7319            for (int i = instantApps.size() - 1; i >= 0; --i) {
7320                final ResolveInfo info = instantApps.get(i);
7321                final String packageName = info.activityInfo.packageName;
7322                final PackageSetting ps = mSettings.mPackages.get(packageName);
7323                if (ps.getInstantApp(userId)) {
7324                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7325                    final int status = (int)(packedStatus >> 32);
7326                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7327                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7328                        // there's a local instant application installed, but, the user has
7329                        // chosen to never use it; skip resolution and don't acknowledge
7330                        // an instant application is even available
7331                        if (DEBUG_EPHEMERAL) {
7332                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7333                        }
7334                        blockResolution = true;
7335                        break;
7336                    } else {
7337                        // we have a locally installed instant application; skip resolution
7338                        // but acknowledge there's an instant application available
7339                        if (DEBUG_EPHEMERAL) {
7340                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7341                        }
7342                        localInstantApp = info;
7343                        break;
7344                    }
7345                }
7346            }
7347        }
7348        // no app installed, let's see if one's available
7349        AuxiliaryResolveInfo auxiliaryResponse = null;
7350        if (!blockResolution) {
7351            if (localInstantApp == null) {
7352                // we don't have an instant app locally, resolve externally
7353                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7354                final InstantAppRequest requestObject = new InstantAppRequest(
7355                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7356                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7357                auxiliaryResponse =
7358                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7359                                mContext, mInstantAppResolverConnection, requestObject);
7360                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7361            } else {
7362                // we have an instant application locally, but, we can't admit that since
7363                // callers shouldn't be able to determine prior browsing. create a dummy
7364                // auxiliary response so the downstream code behaves as if there's an
7365                // instant application available externally. when it comes time to start
7366                // the instant application, we'll do the right thing.
7367                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7368                auxiliaryResponse = new AuxiliaryResolveInfo(
7369                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7370                        ai.versionCode, null /*failureIntent*/);
7371            }
7372        }
7373        if (auxiliaryResponse != null) {
7374            if (DEBUG_EPHEMERAL) {
7375                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7376            }
7377            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7378            final PackageSetting ps =
7379                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7380            if (ps != null) {
7381                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7382                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7383                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7384                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7385                // make sure this resolver is the default
7386                ephemeralInstaller.isDefault = true;
7387                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7388                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7389                // add a non-generic filter
7390                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7391                ephemeralInstaller.filter.addDataPath(
7392                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7393                ephemeralInstaller.isInstantAppAvailable = true;
7394                result.add(ephemeralInstaller);
7395            }
7396        }
7397        return result;
7398    }
7399
7400    private static class CrossProfileDomainInfo {
7401        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7402        ResolveInfo resolveInfo;
7403        /* Best domain verification status of the activities found in the other profile */
7404        int bestDomainVerificationStatus;
7405    }
7406
7407    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7408            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7409        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7410                sourceUserId)) {
7411            return null;
7412        }
7413        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7414                resolvedType, flags, parentUserId);
7415
7416        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7417            return null;
7418        }
7419        CrossProfileDomainInfo result = null;
7420        int size = resultTargetUser.size();
7421        for (int i = 0; i < size; i++) {
7422            ResolveInfo riTargetUser = resultTargetUser.get(i);
7423            // Intent filter verification is only for filters that specify a host. So don't return
7424            // those that handle all web uris.
7425            if (riTargetUser.handleAllWebDataURI) {
7426                continue;
7427            }
7428            String packageName = riTargetUser.activityInfo.packageName;
7429            PackageSetting ps = mSettings.mPackages.get(packageName);
7430            if (ps == null) {
7431                continue;
7432            }
7433            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7434            int status = (int)(verificationState >> 32);
7435            if (result == null) {
7436                result = new CrossProfileDomainInfo();
7437                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7438                        sourceUserId, parentUserId);
7439                result.bestDomainVerificationStatus = status;
7440            } else {
7441                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7442                        result.bestDomainVerificationStatus);
7443            }
7444        }
7445        // Don't consider matches with status NEVER across profiles.
7446        if (result != null && result.bestDomainVerificationStatus
7447                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7448            return null;
7449        }
7450        return result;
7451    }
7452
7453    /**
7454     * Verification statuses are ordered from the worse to the best, except for
7455     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7456     */
7457    private int bestDomainVerificationStatus(int status1, int status2) {
7458        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7459            return status2;
7460        }
7461        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7462            return status1;
7463        }
7464        return (int) MathUtils.max(status1, status2);
7465    }
7466
7467    private boolean isUserEnabled(int userId) {
7468        long callingId = Binder.clearCallingIdentity();
7469        try {
7470            UserInfo userInfo = sUserManager.getUserInfo(userId);
7471            return userInfo != null && userInfo.isEnabled();
7472        } finally {
7473            Binder.restoreCallingIdentity(callingId);
7474        }
7475    }
7476
7477    /**
7478     * Filter out activities with systemUserOnly flag set, when current user is not System.
7479     *
7480     * @return filtered list
7481     */
7482    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7483        if (userId == UserHandle.USER_SYSTEM) {
7484            return resolveInfos;
7485        }
7486        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7487            ResolveInfo info = resolveInfos.get(i);
7488            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7489                resolveInfos.remove(i);
7490            }
7491        }
7492        return resolveInfos;
7493    }
7494
7495    /**
7496     * Filters out ephemeral activities.
7497     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7498     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7499     *
7500     * @param resolveInfos The pre-filtered list of resolved activities
7501     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7502     *          is performed.
7503     * @return A filtered list of resolved activities.
7504     */
7505    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7506            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7507        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7508            final ResolveInfo info = resolveInfos.get(i);
7509            // allow activities that are defined in the provided package
7510            if (allowDynamicSplits
7511                    && info.activityInfo.splitName != null
7512                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7513                            info.activityInfo.splitName)) {
7514                // requested activity is defined in a split that hasn't been installed yet.
7515                // add the installer to the resolve list
7516                if (DEBUG_INSTALL) {
7517                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7518                }
7519                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7520                final ComponentName installFailureActivity = findInstallFailureActivity(
7521                        info.activityInfo.packageName,  filterCallingUid, userId);
7522                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7523                        info.activityInfo.packageName, info.activityInfo.splitName,
7524                        installFailureActivity,
7525                        info.activityInfo.applicationInfo.versionCode,
7526                        null /*failureIntent*/);
7527                // make sure this resolver is the default
7528                installerInfo.isDefault = true;
7529                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7530                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7531                // add a non-generic filter
7532                installerInfo.filter = new IntentFilter();
7533                // load resources from the correct package
7534                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7535                resolveInfos.set(i, installerInfo);
7536                continue;
7537            }
7538            // caller is a full app, don't need to apply any other filtering
7539            if (ephemeralPkgName == null) {
7540                continue;
7541            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7542                // caller is same app; don't need to apply any other filtering
7543                continue;
7544            }
7545            // allow activities that have been explicitly exposed to ephemeral apps
7546            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7547            if (!isEphemeralApp
7548                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7549                continue;
7550            }
7551            resolveInfos.remove(i);
7552        }
7553        return resolveInfos;
7554    }
7555
7556    /**
7557     * Returns the activity component that can handle install failures.
7558     * <p>By default, the instant application installer handles failures. However, an
7559     * application may want to handle failures on its own. Applications do this by
7560     * creating an activity with an intent filter that handles the action
7561     * {@link Intent#ACTION_INSTALL_FAILURE}.
7562     */
7563    private @Nullable ComponentName findInstallFailureActivity(
7564            String packageName, int filterCallingUid, int userId) {
7565        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7566        failureActivityIntent.setPackage(packageName);
7567        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7568        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7569                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7570                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7571        final int NR = result.size();
7572        if (NR > 0) {
7573            for (int i = 0; i < NR; i++) {
7574                final ResolveInfo info = result.get(i);
7575                if (info.activityInfo.splitName != null) {
7576                    continue;
7577                }
7578                return new ComponentName(packageName, info.activityInfo.name);
7579            }
7580        }
7581        return null;
7582    }
7583
7584    /**
7585     * @param resolveInfos list of resolve infos in descending priority order
7586     * @return if the list contains a resolve info with non-negative priority
7587     */
7588    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7589        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7590    }
7591
7592    private static boolean hasWebURI(Intent intent) {
7593        if (intent.getData() == null) {
7594            return false;
7595        }
7596        final String scheme = intent.getScheme();
7597        if (TextUtils.isEmpty(scheme)) {
7598            return false;
7599        }
7600        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7601    }
7602
7603    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7604            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7605            int userId) {
7606        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7607
7608        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7609            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7610                    candidates.size());
7611        }
7612
7613        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7614        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7615        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7616        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7617        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7618        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7619
7620        synchronized (mPackages) {
7621            final int count = candidates.size();
7622            // First, try to use linked apps. Partition the candidates into four lists:
7623            // one for the final results, one for the "do not use ever", one for "undefined status"
7624            // and finally one for "browser app type".
7625            for (int n=0; n<count; n++) {
7626                ResolveInfo info = candidates.get(n);
7627                String packageName = info.activityInfo.packageName;
7628                PackageSetting ps = mSettings.mPackages.get(packageName);
7629                if (ps != null) {
7630                    // Add to the special match all list (Browser use case)
7631                    if (info.handleAllWebDataURI) {
7632                        matchAllList.add(info);
7633                        continue;
7634                    }
7635                    // Try to get the status from User settings first
7636                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7637                    int status = (int)(packedStatus >> 32);
7638                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7639                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7640                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7641                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7642                                    + " : linkgen=" + linkGeneration);
7643                        }
7644                        // Use link-enabled generation as preferredOrder, i.e.
7645                        // prefer newly-enabled over earlier-enabled.
7646                        info.preferredOrder = linkGeneration;
7647                        alwaysList.add(info);
7648                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7649                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7650                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7651                        }
7652                        neverList.add(info);
7653                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7654                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7655                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7656                        }
7657                        alwaysAskList.add(info);
7658                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7659                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7660                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7661                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7662                        }
7663                        undefinedList.add(info);
7664                    }
7665                }
7666            }
7667
7668            // We'll want to include browser possibilities in a few cases
7669            boolean includeBrowser = false;
7670
7671            // First try to add the "always" resolution(s) for the current user, if any
7672            if (alwaysList.size() > 0) {
7673                result.addAll(alwaysList);
7674            } else {
7675                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7676                result.addAll(undefinedList);
7677                // Maybe add one for the other profile.
7678                if (xpDomainInfo != null && (
7679                        xpDomainInfo.bestDomainVerificationStatus
7680                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7681                    result.add(xpDomainInfo.resolveInfo);
7682                }
7683                includeBrowser = true;
7684            }
7685
7686            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7687            // If there were 'always' entries their preferred order has been set, so we also
7688            // back that off to make the alternatives equivalent
7689            if (alwaysAskList.size() > 0) {
7690                for (ResolveInfo i : result) {
7691                    i.preferredOrder = 0;
7692                }
7693                result.addAll(alwaysAskList);
7694                includeBrowser = true;
7695            }
7696
7697            if (includeBrowser) {
7698                // Also add browsers (all of them or only the default one)
7699                if (DEBUG_DOMAIN_VERIFICATION) {
7700                    Slog.v(TAG, "   ...including browsers in candidate set");
7701                }
7702                if ((matchFlags & MATCH_ALL) != 0) {
7703                    result.addAll(matchAllList);
7704                } else {
7705                    // Browser/generic handling case.  If there's a default browser, go straight
7706                    // to that (but only if there is no other higher-priority match).
7707                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7708                    int maxMatchPrio = 0;
7709                    ResolveInfo defaultBrowserMatch = null;
7710                    final int numCandidates = matchAllList.size();
7711                    for (int n = 0; n < numCandidates; n++) {
7712                        ResolveInfo info = matchAllList.get(n);
7713                        // track the highest overall match priority...
7714                        if (info.priority > maxMatchPrio) {
7715                            maxMatchPrio = info.priority;
7716                        }
7717                        // ...and the highest-priority default browser match
7718                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7719                            if (defaultBrowserMatch == null
7720                                    || (defaultBrowserMatch.priority < info.priority)) {
7721                                if (debug) {
7722                                    Slog.v(TAG, "Considering default browser match " + info);
7723                                }
7724                                defaultBrowserMatch = info;
7725                            }
7726                        }
7727                    }
7728                    if (defaultBrowserMatch != null
7729                            && defaultBrowserMatch.priority >= maxMatchPrio
7730                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7731                    {
7732                        if (debug) {
7733                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7734                        }
7735                        result.add(defaultBrowserMatch);
7736                    } else {
7737                        result.addAll(matchAllList);
7738                    }
7739                }
7740
7741                // If there is nothing selected, add all candidates and remove the ones that the user
7742                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7743                if (result.size() == 0) {
7744                    result.addAll(candidates);
7745                    result.removeAll(neverList);
7746                }
7747            }
7748        }
7749        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7750            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7751                    result.size());
7752            for (ResolveInfo info : result) {
7753                Slog.v(TAG, "  + " + info.activityInfo);
7754            }
7755        }
7756        return result;
7757    }
7758
7759    // Returns a packed value as a long:
7760    //
7761    // high 'int'-sized word: link status: undefined/ask/never/always.
7762    // low 'int'-sized word: relative priority among 'always' results.
7763    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7764        long result = ps.getDomainVerificationStatusForUser(userId);
7765        // if none available, get the master status
7766        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7767            if (ps.getIntentFilterVerificationInfo() != null) {
7768                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7769            }
7770        }
7771        return result;
7772    }
7773
7774    private ResolveInfo querySkipCurrentProfileIntents(
7775            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7776            int flags, int sourceUserId) {
7777        if (matchingFilters != null) {
7778            int size = matchingFilters.size();
7779            for (int i = 0; i < size; i ++) {
7780                CrossProfileIntentFilter filter = matchingFilters.get(i);
7781                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7782                    // Checking if there are activities in the target user that can handle the
7783                    // intent.
7784                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7785                            resolvedType, flags, sourceUserId);
7786                    if (resolveInfo != null) {
7787                        return resolveInfo;
7788                    }
7789                }
7790            }
7791        }
7792        return null;
7793    }
7794
7795    // Return matching ResolveInfo in target user if any.
7796    private ResolveInfo queryCrossProfileIntents(
7797            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7798            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7799        if (matchingFilters != null) {
7800            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7801            // match the same intent. For performance reasons, it is better not to
7802            // run queryIntent twice for the same userId
7803            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7804            int size = matchingFilters.size();
7805            for (int i = 0; i < size; i++) {
7806                CrossProfileIntentFilter filter = matchingFilters.get(i);
7807                int targetUserId = filter.getTargetUserId();
7808                boolean skipCurrentProfile =
7809                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7810                boolean skipCurrentProfileIfNoMatchFound =
7811                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7812                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7813                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7814                    // Checking if there are activities in the target user that can handle the
7815                    // intent.
7816                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7817                            resolvedType, flags, sourceUserId);
7818                    if (resolveInfo != null) return resolveInfo;
7819                    alreadyTriedUserIds.put(targetUserId, true);
7820                }
7821            }
7822        }
7823        return null;
7824    }
7825
7826    /**
7827     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7828     * will forward the intent to the filter's target user.
7829     * Otherwise, returns null.
7830     */
7831    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7832            String resolvedType, int flags, int sourceUserId) {
7833        int targetUserId = filter.getTargetUserId();
7834        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7835                resolvedType, flags, targetUserId);
7836        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7837            // If all the matches in the target profile are suspended, return null.
7838            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7839                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7840                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7841                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7842                            targetUserId);
7843                }
7844            }
7845        }
7846        return null;
7847    }
7848
7849    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7850            int sourceUserId, int targetUserId) {
7851        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7852        long ident = Binder.clearCallingIdentity();
7853        boolean targetIsProfile;
7854        try {
7855            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7856        } finally {
7857            Binder.restoreCallingIdentity(ident);
7858        }
7859        String className;
7860        if (targetIsProfile) {
7861            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7862        } else {
7863            className = FORWARD_INTENT_TO_PARENT;
7864        }
7865        ComponentName forwardingActivityComponentName = new ComponentName(
7866                mAndroidApplication.packageName, className);
7867        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7868                sourceUserId);
7869        if (!targetIsProfile) {
7870            forwardingActivityInfo.showUserIcon = targetUserId;
7871            forwardingResolveInfo.noResourceId = true;
7872        }
7873        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7874        forwardingResolveInfo.priority = 0;
7875        forwardingResolveInfo.preferredOrder = 0;
7876        forwardingResolveInfo.match = 0;
7877        forwardingResolveInfo.isDefault = true;
7878        forwardingResolveInfo.filter = filter;
7879        forwardingResolveInfo.targetUserId = targetUserId;
7880        return forwardingResolveInfo;
7881    }
7882
7883    @Override
7884    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7885            Intent[] specifics, String[] specificTypes, Intent intent,
7886            String resolvedType, int flags, int userId) {
7887        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7888                specificTypes, intent, resolvedType, flags, userId));
7889    }
7890
7891    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7892            Intent[] specifics, String[] specificTypes, Intent intent,
7893            String resolvedType, int flags, int userId) {
7894        if (!sUserManager.exists(userId)) return Collections.emptyList();
7895        final int callingUid = Binder.getCallingUid();
7896        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7897                false /*includeInstantApps*/);
7898        enforceCrossUserPermission(callingUid, userId,
7899                false /*requireFullPermission*/, false /*checkShell*/,
7900                "query intent activity options");
7901        final String resultsAction = intent.getAction();
7902
7903        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7904                | PackageManager.GET_RESOLVED_FILTER, userId);
7905
7906        if (DEBUG_INTENT_MATCHING) {
7907            Log.v(TAG, "Query " + intent + ": " + results);
7908        }
7909
7910        int specificsPos = 0;
7911        int N;
7912
7913        // todo: note that the algorithm used here is O(N^2).  This
7914        // isn't a problem in our current environment, but if we start running
7915        // into situations where we have more than 5 or 10 matches then this
7916        // should probably be changed to something smarter...
7917
7918        // First we go through and resolve each of the specific items
7919        // that were supplied, taking care of removing any corresponding
7920        // duplicate items in the generic resolve list.
7921        if (specifics != null) {
7922            for (int i=0; i<specifics.length; i++) {
7923                final Intent sintent = specifics[i];
7924                if (sintent == null) {
7925                    continue;
7926                }
7927
7928                if (DEBUG_INTENT_MATCHING) {
7929                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7930                }
7931
7932                String action = sintent.getAction();
7933                if (resultsAction != null && resultsAction.equals(action)) {
7934                    // If this action was explicitly requested, then don't
7935                    // remove things that have it.
7936                    action = null;
7937                }
7938
7939                ResolveInfo ri = null;
7940                ActivityInfo ai = null;
7941
7942                ComponentName comp = sintent.getComponent();
7943                if (comp == null) {
7944                    ri = resolveIntent(
7945                        sintent,
7946                        specificTypes != null ? specificTypes[i] : null,
7947                            flags, userId);
7948                    if (ri == null) {
7949                        continue;
7950                    }
7951                    if (ri == mResolveInfo) {
7952                        // ACK!  Must do something better with this.
7953                    }
7954                    ai = ri.activityInfo;
7955                    comp = new ComponentName(ai.applicationInfo.packageName,
7956                            ai.name);
7957                } else {
7958                    ai = getActivityInfo(comp, flags, userId);
7959                    if (ai == null) {
7960                        continue;
7961                    }
7962                }
7963
7964                // Look for any generic query activities that are duplicates
7965                // of this specific one, and remove them from the results.
7966                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7967                N = results.size();
7968                int j;
7969                for (j=specificsPos; j<N; j++) {
7970                    ResolveInfo sri = results.get(j);
7971                    if ((sri.activityInfo.name.equals(comp.getClassName())
7972                            && sri.activityInfo.applicationInfo.packageName.equals(
7973                                    comp.getPackageName()))
7974                        || (action != null && sri.filter.matchAction(action))) {
7975                        results.remove(j);
7976                        if (DEBUG_INTENT_MATCHING) Log.v(
7977                            TAG, "Removing duplicate item from " + j
7978                            + " due to specific " + specificsPos);
7979                        if (ri == null) {
7980                            ri = sri;
7981                        }
7982                        j--;
7983                        N--;
7984                    }
7985                }
7986
7987                // Add this specific item to its proper place.
7988                if (ri == null) {
7989                    ri = new ResolveInfo();
7990                    ri.activityInfo = ai;
7991                }
7992                results.add(specificsPos, ri);
7993                ri.specificIndex = i;
7994                specificsPos++;
7995            }
7996        }
7997
7998        // Now we go through the remaining generic results and remove any
7999        // duplicate actions that are found here.
8000        N = results.size();
8001        for (int i=specificsPos; i<N-1; i++) {
8002            final ResolveInfo rii = results.get(i);
8003            if (rii.filter == null) {
8004                continue;
8005            }
8006
8007            // Iterate over all of the actions of this result's intent
8008            // filter...  typically this should be just one.
8009            final Iterator<String> it = rii.filter.actionsIterator();
8010            if (it == null) {
8011                continue;
8012            }
8013            while (it.hasNext()) {
8014                final String action = it.next();
8015                if (resultsAction != null && resultsAction.equals(action)) {
8016                    // If this action was explicitly requested, then don't
8017                    // remove things that have it.
8018                    continue;
8019                }
8020                for (int j=i+1; j<N; j++) {
8021                    final ResolveInfo rij = results.get(j);
8022                    if (rij.filter != null && rij.filter.hasAction(action)) {
8023                        results.remove(j);
8024                        if (DEBUG_INTENT_MATCHING) Log.v(
8025                            TAG, "Removing duplicate item from " + j
8026                            + " due to action " + action + " at " + i);
8027                        j--;
8028                        N--;
8029                    }
8030                }
8031            }
8032
8033            // If the caller didn't request filter information, drop it now
8034            // so we don't have to marshall/unmarshall it.
8035            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8036                rii.filter = null;
8037            }
8038        }
8039
8040        // Filter out the caller activity if so requested.
8041        if (caller != null) {
8042            N = results.size();
8043            for (int i=0; i<N; i++) {
8044                ActivityInfo ainfo = results.get(i).activityInfo;
8045                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8046                        && caller.getClassName().equals(ainfo.name)) {
8047                    results.remove(i);
8048                    break;
8049                }
8050            }
8051        }
8052
8053        // If the caller didn't request filter information,
8054        // drop them now so we don't have to
8055        // marshall/unmarshall it.
8056        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8057            N = results.size();
8058            for (int i=0; i<N; i++) {
8059                results.get(i).filter = null;
8060            }
8061        }
8062
8063        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8064        return results;
8065    }
8066
8067    @Override
8068    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8069            String resolvedType, int flags, int userId) {
8070        return new ParceledListSlice<>(
8071                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8072                        false /*allowDynamicSplits*/));
8073    }
8074
8075    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8076            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8077        if (!sUserManager.exists(userId)) return Collections.emptyList();
8078        final int callingUid = Binder.getCallingUid();
8079        enforceCrossUserPermission(callingUid, userId,
8080                false /*requireFullPermission*/, false /*checkShell*/,
8081                "query intent receivers");
8082        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8083        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8084                false /*includeInstantApps*/);
8085        ComponentName comp = intent.getComponent();
8086        if (comp == null) {
8087            if (intent.getSelector() != null) {
8088                intent = intent.getSelector();
8089                comp = intent.getComponent();
8090            }
8091        }
8092        if (comp != null) {
8093            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8094            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8095            if (ai != null) {
8096                // When specifying an explicit component, we prevent the activity from being
8097                // used when either 1) the calling package is normal and the activity is within
8098                // an instant application or 2) the calling package is ephemeral and the
8099                // activity is not visible to instant applications.
8100                final boolean matchInstantApp =
8101                        (flags & PackageManager.MATCH_INSTANT) != 0;
8102                final boolean matchVisibleToInstantAppOnly =
8103                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8104                final boolean matchExplicitlyVisibleOnly =
8105                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8106                final boolean isCallerInstantApp =
8107                        instantAppPkgName != null;
8108                final boolean isTargetSameInstantApp =
8109                        comp.getPackageName().equals(instantAppPkgName);
8110                final boolean isTargetInstantApp =
8111                        (ai.applicationInfo.privateFlags
8112                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8113                final boolean isTargetVisibleToInstantApp =
8114                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8115                final boolean isTargetExplicitlyVisibleToInstantApp =
8116                        isTargetVisibleToInstantApp
8117                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8118                final boolean isTargetHiddenFromInstantApp =
8119                        !isTargetVisibleToInstantApp
8120                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8121                final boolean blockResolution =
8122                        !isTargetSameInstantApp
8123                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8124                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8125                                        && isTargetHiddenFromInstantApp));
8126                if (!blockResolution) {
8127                    ResolveInfo ri = new ResolveInfo();
8128                    ri.activityInfo = ai;
8129                    list.add(ri);
8130                }
8131            }
8132            return applyPostResolutionFilter(
8133                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8134        }
8135
8136        // reader
8137        synchronized (mPackages) {
8138            String pkgName = intent.getPackage();
8139            if (pkgName == null) {
8140                final List<ResolveInfo> result =
8141                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8142                return applyPostResolutionFilter(
8143                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8144            }
8145            final PackageParser.Package pkg = mPackages.get(pkgName);
8146            if (pkg != null) {
8147                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8148                        intent, resolvedType, flags, pkg.receivers, userId);
8149                return applyPostResolutionFilter(
8150                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8151            }
8152            return Collections.emptyList();
8153        }
8154    }
8155
8156    @Override
8157    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8158        final int callingUid = Binder.getCallingUid();
8159        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8160    }
8161
8162    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8163            int userId, int callingUid) {
8164        if (!sUserManager.exists(userId)) return null;
8165        flags = updateFlagsForResolve(
8166                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8167        List<ResolveInfo> query = queryIntentServicesInternal(
8168                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8169        if (query != null) {
8170            if (query.size() >= 1) {
8171                // If there is more than one service with the same priority,
8172                // just arbitrarily pick the first one.
8173                return query.get(0);
8174            }
8175        }
8176        return null;
8177    }
8178
8179    @Override
8180    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8181            String resolvedType, int flags, int userId) {
8182        final int callingUid = Binder.getCallingUid();
8183        return new ParceledListSlice<>(queryIntentServicesInternal(
8184                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8185    }
8186
8187    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8188            String resolvedType, int flags, int userId, int callingUid,
8189            boolean includeInstantApps) {
8190        if (!sUserManager.exists(userId)) return Collections.emptyList();
8191        enforceCrossUserPermission(callingUid, userId,
8192                false /*requireFullPermission*/, false /*checkShell*/,
8193                "query intent receivers");
8194        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8195        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8196        ComponentName comp = intent.getComponent();
8197        if (comp == null) {
8198            if (intent.getSelector() != null) {
8199                intent = intent.getSelector();
8200                comp = intent.getComponent();
8201            }
8202        }
8203        if (comp != null) {
8204            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8205            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8206            if (si != null) {
8207                // When specifying an explicit component, we prevent the service from being
8208                // used when either 1) the service is in an instant application and the
8209                // caller is not the same instant application or 2) the calling package is
8210                // ephemeral and the activity is not visible to ephemeral applications.
8211                final boolean matchInstantApp =
8212                        (flags & PackageManager.MATCH_INSTANT) != 0;
8213                final boolean matchVisibleToInstantAppOnly =
8214                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8215                final boolean isCallerInstantApp =
8216                        instantAppPkgName != null;
8217                final boolean isTargetSameInstantApp =
8218                        comp.getPackageName().equals(instantAppPkgName);
8219                final boolean isTargetInstantApp =
8220                        (si.applicationInfo.privateFlags
8221                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8222                final boolean isTargetHiddenFromInstantApp =
8223                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8224                final boolean blockResolution =
8225                        !isTargetSameInstantApp
8226                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8227                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8228                                        && isTargetHiddenFromInstantApp));
8229                if (!blockResolution) {
8230                    final ResolveInfo ri = new ResolveInfo();
8231                    ri.serviceInfo = si;
8232                    list.add(ri);
8233                }
8234            }
8235            return list;
8236        }
8237
8238        // reader
8239        synchronized (mPackages) {
8240            String pkgName = intent.getPackage();
8241            if (pkgName == null) {
8242                return applyPostServiceResolutionFilter(
8243                        mServices.queryIntent(intent, resolvedType, flags, userId),
8244                        instantAppPkgName);
8245            }
8246            final PackageParser.Package pkg = mPackages.get(pkgName);
8247            if (pkg != null) {
8248                return applyPostServiceResolutionFilter(
8249                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8250                                userId),
8251                        instantAppPkgName);
8252            }
8253            return Collections.emptyList();
8254        }
8255    }
8256
8257    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8258            String instantAppPkgName) {
8259        if (instantAppPkgName == null) {
8260            return resolveInfos;
8261        }
8262        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8263            final ResolveInfo info = resolveInfos.get(i);
8264            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8265            // allow services that are defined in the provided package
8266            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8267                if (info.serviceInfo.splitName != null
8268                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8269                                info.serviceInfo.splitName)) {
8270                    // requested service is defined in a split that hasn't been installed yet.
8271                    // add the installer to the resolve list
8272                    if (DEBUG_EPHEMERAL) {
8273                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8274                    }
8275                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8276                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8277                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8278                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8279                            null /*failureIntent*/);
8280                    // make sure this resolver is the default
8281                    installerInfo.isDefault = true;
8282                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8283                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8284                    // add a non-generic filter
8285                    installerInfo.filter = new IntentFilter();
8286                    // load resources from the correct package
8287                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8288                    resolveInfos.set(i, installerInfo);
8289                }
8290                continue;
8291            }
8292            // allow services that have been explicitly exposed to ephemeral apps
8293            if (!isEphemeralApp
8294                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8295                continue;
8296            }
8297            resolveInfos.remove(i);
8298        }
8299        return resolveInfos;
8300    }
8301
8302    @Override
8303    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8304            String resolvedType, int flags, int userId) {
8305        return new ParceledListSlice<>(
8306                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8307    }
8308
8309    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8310            Intent intent, String resolvedType, int flags, int userId) {
8311        if (!sUserManager.exists(userId)) return Collections.emptyList();
8312        final int callingUid = Binder.getCallingUid();
8313        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8314        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8315                false /*includeInstantApps*/);
8316        ComponentName comp = intent.getComponent();
8317        if (comp == null) {
8318            if (intent.getSelector() != null) {
8319                intent = intent.getSelector();
8320                comp = intent.getComponent();
8321            }
8322        }
8323        if (comp != null) {
8324            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8325            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8326            if (pi != null) {
8327                // When specifying an explicit component, we prevent the provider from being
8328                // used when either 1) the provider is in an instant application and the
8329                // caller is not the same instant application or 2) the calling package is an
8330                // instant application and the provider is not visible to instant applications.
8331                final boolean matchInstantApp =
8332                        (flags & PackageManager.MATCH_INSTANT) != 0;
8333                final boolean matchVisibleToInstantAppOnly =
8334                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8335                final boolean isCallerInstantApp =
8336                        instantAppPkgName != null;
8337                final boolean isTargetSameInstantApp =
8338                        comp.getPackageName().equals(instantAppPkgName);
8339                final boolean isTargetInstantApp =
8340                        (pi.applicationInfo.privateFlags
8341                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8342                final boolean isTargetHiddenFromInstantApp =
8343                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8344                final boolean blockResolution =
8345                        !isTargetSameInstantApp
8346                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8347                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8348                                        && isTargetHiddenFromInstantApp));
8349                if (!blockResolution) {
8350                    final ResolveInfo ri = new ResolveInfo();
8351                    ri.providerInfo = pi;
8352                    list.add(ri);
8353                }
8354            }
8355            return list;
8356        }
8357
8358        // reader
8359        synchronized (mPackages) {
8360            String pkgName = intent.getPackage();
8361            if (pkgName == null) {
8362                return applyPostContentProviderResolutionFilter(
8363                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8364                        instantAppPkgName);
8365            }
8366            final PackageParser.Package pkg = mPackages.get(pkgName);
8367            if (pkg != null) {
8368                return applyPostContentProviderResolutionFilter(
8369                        mProviders.queryIntentForPackage(
8370                        intent, resolvedType, flags, pkg.providers, userId),
8371                        instantAppPkgName);
8372            }
8373            return Collections.emptyList();
8374        }
8375    }
8376
8377    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8378            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8379        if (instantAppPkgName == null) {
8380            return resolveInfos;
8381        }
8382        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8383            final ResolveInfo info = resolveInfos.get(i);
8384            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8385            // allow providers that are defined in the provided package
8386            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8387                if (info.providerInfo.splitName != null
8388                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8389                                info.providerInfo.splitName)) {
8390                    // requested provider is defined in a split that hasn't been installed yet.
8391                    // add the installer to the resolve list
8392                    if (DEBUG_EPHEMERAL) {
8393                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8394                    }
8395                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8396                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8397                            info.providerInfo.packageName, info.providerInfo.splitName,
8398                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8399                            null /*failureIntent*/);
8400                    // make sure this resolver is the default
8401                    installerInfo.isDefault = true;
8402                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8403                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8404                    // add a non-generic filter
8405                    installerInfo.filter = new IntentFilter();
8406                    // load resources from the correct package
8407                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8408                    resolveInfos.set(i, installerInfo);
8409                }
8410                continue;
8411            }
8412            // allow providers that have been explicitly exposed to instant applications
8413            if (!isEphemeralApp
8414                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8415                continue;
8416            }
8417            resolveInfos.remove(i);
8418        }
8419        return resolveInfos;
8420    }
8421
8422    @Override
8423    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8424        final int callingUid = Binder.getCallingUid();
8425        if (getInstantAppPackageName(callingUid) != null) {
8426            return ParceledListSlice.emptyList();
8427        }
8428        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8429        flags = updateFlagsForPackage(flags, userId, null);
8430        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8431        enforceCrossUserPermission(callingUid, userId,
8432                true /* requireFullPermission */, false /* checkShell */,
8433                "get installed packages");
8434
8435        // writer
8436        synchronized (mPackages) {
8437            ArrayList<PackageInfo> list;
8438            if (listUninstalled) {
8439                list = new ArrayList<>(mSettings.mPackages.size());
8440                for (PackageSetting ps : mSettings.mPackages.values()) {
8441                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8442                        continue;
8443                    }
8444                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8445                        return null;
8446                    }
8447                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8448                    if (pi != null) {
8449                        list.add(pi);
8450                    }
8451                }
8452            } else {
8453                list = new ArrayList<>(mPackages.size());
8454                for (PackageParser.Package p : mPackages.values()) {
8455                    final PackageSetting ps = (PackageSetting) p.mExtras;
8456                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8457                        continue;
8458                    }
8459                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8460                        return null;
8461                    }
8462                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8463                            p.mExtras, flags, userId);
8464                    if (pi != null) {
8465                        list.add(pi);
8466                    }
8467                }
8468            }
8469
8470            return new ParceledListSlice<>(list);
8471        }
8472    }
8473
8474    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8475            String[] permissions, boolean[] tmp, int flags, int userId) {
8476        int numMatch = 0;
8477        final PermissionsState permissionsState = ps.getPermissionsState();
8478        for (int i=0; i<permissions.length; i++) {
8479            final String permission = permissions[i];
8480            if (permissionsState.hasPermission(permission, userId)) {
8481                tmp[i] = true;
8482                numMatch++;
8483            } else {
8484                tmp[i] = false;
8485            }
8486        }
8487        if (numMatch == 0) {
8488            return;
8489        }
8490        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8491
8492        // The above might return null in cases of uninstalled apps or install-state
8493        // skew across users/profiles.
8494        if (pi != null) {
8495            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8496                if (numMatch == permissions.length) {
8497                    pi.requestedPermissions = permissions;
8498                } else {
8499                    pi.requestedPermissions = new String[numMatch];
8500                    numMatch = 0;
8501                    for (int i=0; i<permissions.length; i++) {
8502                        if (tmp[i]) {
8503                            pi.requestedPermissions[numMatch] = permissions[i];
8504                            numMatch++;
8505                        }
8506                    }
8507                }
8508            }
8509            list.add(pi);
8510        }
8511    }
8512
8513    @Override
8514    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8515            String[] permissions, int flags, int userId) {
8516        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8517        flags = updateFlagsForPackage(flags, userId, permissions);
8518        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8519                true /* requireFullPermission */, false /* checkShell */,
8520                "get packages holding permissions");
8521        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8522
8523        // writer
8524        synchronized (mPackages) {
8525            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8526            boolean[] tmpBools = new boolean[permissions.length];
8527            if (listUninstalled) {
8528                for (PackageSetting ps : mSettings.mPackages.values()) {
8529                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8530                            userId);
8531                }
8532            } else {
8533                for (PackageParser.Package pkg : mPackages.values()) {
8534                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8535                    if (ps != null) {
8536                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8537                                userId);
8538                    }
8539                }
8540            }
8541
8542            return new ParceledListSlice<PackageInfo>(list);
8543        }
8544    }
8545
8546    @Override
8547    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8548        final int callingUid = Binder.getCallingUid();
8549        if (getInstantAppPackageName(callingUid) != null) {
8550            return ParceledListSlice.emptyList();
8551        }
8552        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8553        flags = updateFlagsForApplication(flags, userId, null);
8554        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8555
8556        // writer
8557        synchronized (mPackages) {
8558            ArrayList<ApplicationInfo> list;
8559            if (listUninstalled) {
8560                list = new ArrayList<>(mSettings.mPackages.size());
8561                for (PackageSetting ps : mSettings.mPackages.values()) {
8562                    ApplicationInfo ai;
8563                    int effectiveFlags = flags;
8564                    if (ps.isSystem()) {
8565                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8566                    }
8567                    if (ps.pkg != null) {
8568                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8569                            continue;
8570                        }
8571                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8572                            return null;
8573                        }
8574                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8575                                ps.readUserState(userId), userId);
8576                        if (ai != null) {
8577                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8578                        }
8579                    } else {
8580                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8581                        // and already converts to externally visible package name
8582                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8583                                callingUid, effectiveFlags, userId);
8584                    }
8585                    if (ai != null) {
8586                        list.add(ai);
8587                    }
8588                }
8589            } else {
8590                list = new ArrayList<>(mPackages.size());
8591                for (PackageParser.Package p : mPackages.values()) {
8592                    if (p.mExtras != null) {
8593                        PackageSetting ps = (PackageSetting) p.mExtras;
8594                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8595                            continue;
8596                        }
8597                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8598                            return null;
8599                        }
8600                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8601                                ps.readUserState(userId), userId);
8602                        if (ai != null) {
8603                            ai.packageName = resolveExternalPackageNameLPr(p);
8604                            list.add(ai);
8605                        }
8606                    }
8607                }
8608            }
8609
8610            return new ParceledListSlice<>(list);
8611        }
8612    }
8613
8614    @Override
8615    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8616        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8617            return null;
8618        }
8619        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8620            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8621                    "getEphemeralApplications");
8622        }
8623        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8624                true /* requireFullPermission */, false /* checkShell */,
8625                "getEphemeralApplications");
8626        synchronized (mPackages) {
8627            List<InstantAppInfo> instantApps = mInstantAppRegistry
8628                    .getInstantAppsLPr(userId);
8629            if (instantApps != null) {
8630                return new ParceledListSlice<>(instantApps);
8631            }
8632        }
8633        return null;
8634    }
8635
8636    @Override
8637    public boolean isInstantApp(String packageName, int userId) {
8638        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8639                true /* requireFullPermission */, false /* checkShell */,
8640                "isInstantApp");
8641        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8642            return false;
8643        }
8644
8645        synchronized (mPackages) {
8646            int callingUid = Binder.getCallingUid();
8647            if (Process.isIsolated(callingUid)) {
8648                callingUid = mIsolatedOwners.get(callingUid);
8649            }
8650            final PackageSetting ps = mSettings.mPackages.get(packageName);
8651            PackageParser.Package pkg = mPackages.get(packageName);
8652            final boolean returnAllowed =
8653                    ps != null
8654                    && (isCallerSameApp(packageName, callingUid)
8655                            || canViewInstantApps(callingUid, userId)
8656                            || mInstantAppRegistry.isInstantAccessGranted(
8657                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8658            if (returnAllowed) {
8659                return ps.getInstantApp(userId);
8660            }
8661        }
8662        return false;
8663    }
8664
8665    @Override
8666    public byte[] getInstantAppCookie(String packageName, int userId) {
8667        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8668            return null;
8669        }
8670
8671        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8672                true /* requireFullPermission */, false /* checkShell */,
8673                "getInstantAppCookie");
8674        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8675            return null;
8676        }
8677        synchronized (mPackages) {
8678            return mInstantAppRegistry.getInstantAppCookieLPw(
8679                    packageName, userId);
8680        }
8681    }
8682
8683    @Override
8684    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8685        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8686            return true;
8687        }
8688
8689        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8690                true /* requireFullPermission */, true /* checkShell */,
8691                "setInstantAppCookie");
8692        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8693            return false;
8694        }
8695        synchronized (mPackages) {
8696            return mInstantAppRegistry.setInstantAppCookieLPw(
8697                    packageName, cookie, userId);
8698        }
8699    }
8700
8701    @Override
8702    public Bitmap getInstantAppIcon(String packageName, int userId) {
8703        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8704            return null;
8705        }
8706
8707        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8708            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8709                    "getInstantAppIcon");
8710        }
8711        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8712                true /* requireFullPermission */, false /* checkShell */,
8713                "getInstantAppIcon");
8714
8715        synchronized (mPackages) {
8716            return mInstantAppRegistry.getInstantAppIconLPw(
8717                    packageName, userId);
8718        }
8719    }
8720
8721    private boolean isCallerSameApp(String packageName, int uid) {
8722        PackageParser.Package pkg = mPackages.get(packageName);
8723        return pkg != null
8724                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8725    }
8726
8727    @Override
8728    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8729        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8730            return ParceledListSlice.emptyList();
8731        }
8732        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8733    }
8734
8735    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8736        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8737
8738        // reader
8739        synchronized (mPackages) {
8740            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8741            final int userId = UserHandle.getCallingUserId();
8742            while (i.hasNext()) {
8743                final PackageParser.Package p = i.next();
8744                if (p.applicationInfo == null) continue;
8745
8746                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8747                        && !p.applicationInfo.isDirectBootAware();
8748                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8749                        && p.applicationInfo.isDirectBootAware();
8750
8751                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8752                        && (!mSafeMode || isSystemApp(p))
8753                        && (matchesUnaware || matchesAware)) {
8754                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8755                    if (ps != null) {
8756                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8757                                ps.readUserState(userId), userId);
8758                        if (ai != null) {
8759                            finalList.add(ai);
8760                        }
8761                    }
8762                }
8763            }
8764        }
8765
8766        return finalList;
8767    }
8768
8769    @Override
8770    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8771        if (!sUserManager.exists(userId)) return null;
8772        flags = updateFlagsForComponent(flags, userId, name);
8773        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8774        // reader
8775        synchronized (mPackages) {
8776            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8777            PackageSetting ps = provider != null
8778                    ? mSettings.mPackages.get(provider.owner.packageName)
8779                    : null;
8780            if (ps != null) {
8781                final boolean isInstantApp = ps.getInstantApp(userId);
8782                // normal application; filter out instant application provider
8783                if (instantAppPkgName == null && isInstantApp) {
8784                    return null;
8785                }
8786                // instant application; filter out other instant applications
8787                if (instantAppPkgName != null
8788                        && isInstantApp
8789                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8790                    return null;
8791                }
8792                // instant application; filter out non-exposed provider
8793                if (instantAppPkgName != null
8794                        && !isInstantApp
8795                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8796                    return null;
8797                }
8798                // provider not enabled
8799                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8800                    return null;
8801                }
8802                return PackageParser.generateProviderInfo(
8803                        provider, flags, ps.readUserState(userId), userId);
8804            }
8805            return null;
8806        }
8807    }
8808
8809    /**
8810     * @deprecated
8811     */
8812    @Deprecated
8813    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8814        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8815            return;
8816        }
8817        // reader
8818        synchronized (mPackages) {
8819            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8820                    .entrySet().iterator();
8821            final int userId = UserHandle.getCallingUserId();
8822            while (i.hasNext()) {
8823                Map.Entry<String, PackageParser.Provider> entry = i.next();
8824                PackageParser.Provider p = entry.getValue();
8825                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8826
8827                if (ps != null && p.syncable
8828                        && (!mSafeMode || (p.info.applicationInfo.flags
8829                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8830                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8831                            ps.readUserState(userId), userId);
8832                    if (info != null) {
8833                        outNames.add(entry.getKey());
8834                        outInfo.add(info);
8835                    }
8836                }
8837            }
8838        }
8839    }
8840
8841    @Override
8842    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8843            int uid, int flags, String metaDataKey) {
8844        final int callingUid = Binder.getCallingUid();
8845        final int userId = processName != null ? UserHandle.getUserId(uid)
8846                : UserHandle.getCallingUserId();
8847        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8848        flags = updateFlagsForComponent(flags, userId, processName);
8849        ArrayList<ProviderInfo> finalList = null;
8850        // reader
8851        synchronized (mPackages) {
8852            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8853            while (i.hasNext()) {
8854                final PackageParser.Provider p = i.next();
8855                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8856                if (ps != null && p.info.authority != null
8857                        && (processName == null
8858                                || (p.info.processName.equals(processName)
8859                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8860                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8861
8862                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8863                    // parameter.
8864                    if (metaDataKey != null
8865                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8866                        continue;
8867                    }
8868                    final ComponentName component =
8869                            new ComponentName(p.info.packageName, p.info.name);
8870                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8871                        continue;
8872                    }
8873                    if (finalList == null) {
8874                        finalList = new ArrayList<ProviderInfo>(3);
8875                    }
8876                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8877                            ps.readUserState(userId), userId);
8878                    if (info != null) {
8879                        finalList.add(info);
8880                    }
8881                }
8882            }
8883        }
8884
8885        if (finalList != null) {
8886            Collections.sort(finalList, mProviderInitOrderSorter);
8887            return new ParceledListSlice<ProviderInfo>(finalList);
8888        }
8889
8890        return ParceledListSlice.emptyList();
8891    }
8892
8893    @Override
8894    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8895        // reader
8896        synchronized (mPackages) {
8897            final int callingUid = Binder.getCallingUid();
8898            final int callingUserId = UserHandle.getUserId(callingUid);
8899            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8900            if (ps == null) return null;
8901            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8902                return null;
8903            }
8904            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8905            return PackageParser.generateInstrumentationInfo(i, flags);
8906        }
8907    }
8908
8909    @Override
8910    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8911            String targetPackage, int flags) {
8912        final int callingUid = Binder.getCallingUid();
8913        final int callingUserId = UserHandle.getUserId(callingUid);
8914        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8915        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8916            return ParceledListSlice.emptyList();
8917        }
8918        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8919    }
8920
8921    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8922            int flags) {
8923        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8924
8925        // reader
8926        synchronized (mPackages) {
8927            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8928            while (i.hasNext()) {
8929                final PackageParser.Instrumentation p = i.next();
8930                if (targetPackage == null
8931                        || targetPackage.equals(p.info.targetPackage)) {
8932                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8933                            flags);
8934                    if (ii != null) {
8935                        finalList.add(ii);
8936                    }
8937                }
8938            }
8939        }
8940
8941        return finalList;
8942    }
8943
8944    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8945        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8946        try {
8947            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8948        } finally {
8949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8950        }
8951    }
8952
8953    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8954        final File[] files = dir.listFiles();
8955        if (ArrayUtils.isEmpty(files)) {
8956            Log.d(TAG, "No files in app dir " + dir);
8957            return;
8958        }
8959
8960        if (DEBUG_PACKAGE_SCANNING) {
8961            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8962                    + " flags=0x" + Integer.toHexString(parseFlags));
8963        }
8964        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8965                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8966                mParallelPackageParserCallback);
8967
8968        // Submit files for parsing in parallel
8969        int fileCount = 0;
8970        for (File file : files) {
8971            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8972                    && !PackageInstallerService.isStageName(file.getName());
8973            if (!isPackage) {
8974                // Ignore entries which are not packages
8975                continue;
8976            }
8977            parallelPackageParser.submit(file, parseFlags);
8978            fileCount++;
8979        }
8980
8981        // Process results one by one
8982        for (; fileCount > 0; fileCount--) {
8983            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8984            Throwable throwable = parseResult.throwable;
8985            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8986
8987            if (throwable == null) {
8988                // Static shared libraries have synthetic package names
8989                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8990                    renameStaticSharedLibraryPackage(parseResult.pkg);
8991                }
8992                try {
8993                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8994                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8995                                currentTime, null);
8996                    }
8997                } catch (PackageManagerException e) {
8998                    errorCode = e.error;
8999                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9000                }
9001            } else if (throwable instanceof PackageParser.PackageParserException) {
9002                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9003                        throwable;
9004                errorCode = e.error;
9005                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9006            } else {
9007                throw new IllegalStateException("Unexpected exception occurred while parsing "
9008                        + parseResult.scanFile, throwable);
9009            }
9010
9011            // Delete invalid userdata apps
9012            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9013                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9014                logCriticalInfo(Log.WARN,
9015                        "Deleting invalid package at " + parseResult.scanFile);
9016                removeCodePathLI(parseResult.scanFile);
9017            }
9018        }
9019        parallelPackageParser.close();
9020    }
9021
9022    private static File getSettingsProblemFile() {
9023        File dataDir = Environment.getDataDirectory();
9024        File systemDir = new File(dataDir, "system");
9025        File fname = new File(systemDir, "uiderrors.txt");
9026        return fname;
9027    }
9028
9029    static void reportSettingsProblem(int priority, String msg) {
9030        logCriticalInfo(priority, msg);
9031    }
9032
9033    public static void logCriticalInfo(int priority, String msg) {
9034        Slog.println(priority, TAG, msg);
9035        EventLogTags.writePmCriticalInfo(msg);
9036        try {
9037            File fname = getSettingsProblemFile();
9038            FileOutputStream out = new FileOutputStream(fname, true);
9039            PrintWriter pw = new FastPrintWriter(out);
9040            SimpleDateFormat formatter = new SimpleDateFormat();
9041            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9042            pw.println(dateString + ": " + msg);
9043            pw.close();
9044            FileUtils.setPermissions(
9045                    fname.toString(),
9046                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9047                    -1, -1);
9048        } catch (java.io.IOException e) {
9049        }
9050    }
9051
9052    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9053        if (srcFile.isDirectory()) {
9054            final File baseFile = new File(pkg.baseCodePath);
9055            long maxModifiedTime = baseFile.lastModified();
9056            if (pkg.splitCodePaths != null) {
9057                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9058                    final File splitFile = new File(pkg.splitCodePaths[i]);
9059                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9060                }
9061            }
9062            return maxModifiedTime;
9063        }
9064        return srcFile.lastModified();
9065    }
9066
9067    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9068            final int policyFlags) throws PackageManagerException {
9069        // When upgrading from pre-N MR1, verify the package time stamp using the package
9070        // directory and not the APK file.
9071        final long lastModifiedTime = mIsPreNMR1Upgrade
9072                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9073        if (ps != null
9074                && ps.codePath.equals(srcFile)
9075                && ps.timeStamp == lastModifiedTime
9076                && !isCompatSignatureUpdateNeeded(pkg)
9077                && !isRecoverSignatureUpdateNeeded(pkg)) {
9078            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9079            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9080            ArraySet<PublicKey> signingKs;
9081            synchronized (mPackages) {
9082                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9083            }
9084            if (ps.signatures.mSignatures != null
9085                    && ps.signatures.mSignatures.length != 0
9086                    && signingKs != null) {
9087                // Optimization: reuse the existing cached certificates
9088                // if the package appears to be unchanged.
9089                pkg.mSignatures = ps.signatures.mSignatures;
9090                pkg.mSigningKeys = signingKs;
9091                return;
9092            }
9093
9094            Slog.w(TAG, "PackageSetting for " + ps.name
9095                    + " is missing signatures.  Collecting certs again to recover them.");
9096        } else {
9097            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9098        }
9099
9100        try {
9101            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9102            PackageParser.collectCertificates(pkg, policyFlags);
9103        } catch (PackageParserException e) {
9104            throw PackageManagerException.from(e);
9105        } finally {
9106            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9107        }
9108    }
9109
9110    /**
9111     *  Traces a package scan.
9112     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9113     */
9114    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9115            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9116        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9117        try {
9118            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9119        } finally {
9120            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9121        }
9122    }
9123
9124    /**
9125     *  Scans a package and returns the newly parsed package.
9126     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9127     */
9128    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9129            long currentTime, UserHandle user) throws PackageManagerException {
9130        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9131        PackageParser pp = new PackageParser();
9132        pp.setSeparateProcesses(mSeparateProcesses);
9133        pp.setOnlyCoreApps(mOnlyCore);
9134        pp.setDisplayMetrics(mMetrics);
9135        pp.setCallback(mPackageParserCallback);
9136
9137        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9138            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9139        }
9140
9141        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9142        final PackageParser.Package pkg;
9143        try {
9144            pkg = pp.parsePackage(scanFile, parseFlags);
9145        } catch (PackageParserException e) {
9146            throw PackageManagerException.from(e);
9147        } finally {
9148            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9149        }
9150
9151        // Static shared libraries have synthetic package names
9152        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9153            renameStaticSharedLibraryPackage(pkg);
9154        }
9155
9156        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9157    }
9158
9159    /**
9160     *  Scans a package and returns the newly parsed package.
9161     *  @throws PackageManagerException on a parse error.
9162     */
9163    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9164            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9165            throws PackageManagerException {
9166        // If the package has children and this is the first dive in the function
9167        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9168        // packages (parent and children) would be successfully scanned before the
9169        // actual scan since scanning mutates internal state and we want to atomically
9170        // install the package and its children.
9171        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9172            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9173                scanFlags |= SCAN_CHECK_ONLY;
9174            }
9175        } else {
9176            scanFlags &= ~SCAN_CHECK_ONLY;
9177        }
9178
9179        // Scan the parent
9180        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9181                scanFlags, currentTime, user);
9182
9183        // Scan the children
9184        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9185        for (int i = 0; i < childCount; i++) {
9186            PackageParser.Package childPackage = pkg.childPackages.get(i);
9187            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9188                    currentTime, user);
9189        }
9190
9191
9192        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9193            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9194        }
9195
9196        return scannedPkg;
9197    }
9198
9199    /**
9200     *  Scans a package and returns the newly parsed package.
9201     *  @throws PackageManagerException on a parse error.
9202     */
9203    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9204            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9205            throws PackageManagerException {
9206        PackageSetting ps = null;
9207        PackageSetting updatedPkg;
9208        // reader
9209        synchronized (mPackages) {
9210            // Look to see if we already know about this package.
9211            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9212            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9213                // This package has been renamed to its original name.  Let's
9214                // use that.
9215                ps = mSettings.getPackageLPr(oldName);
9216            }
9217            // If there was no original package, see one for the real package name.
9218            if (ps == null) {
9219                ps = mSettings.getPackageLPr(pkg.packageName);
9220            }
9221            // Check to see if this package could be hiding/updating a system
9222            // package.  Must look for it either under the original or real
9223            // package name depending on our state.
9224            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9225            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9226
9227            // If this is a package we don't know about on the system partition, we
9228            // may need to remove disabled child packages on the system partition
9229            // or may need to not add child packages if the parent apk is updated
9230            // on the data partition and no longer defines this child package.
9231            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9232                // If this is a parent package for an updated system app and this system
9233                // app got an OTA update which no longer defines some of the child packages
9234                // we have to prune them from the disabled system packages.
9235                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9236                if (disabledPs != null) {
9237                    final int scannedChildCount = (pkg.childPackages != null)
9238                            ? pkg.childPackages.size() : 0;
9239                    final int disabledChildCount = disabledPs.childPackageNames != null
9240                            ? disabledPs.childPackageNames.size() : 0;
9241                    for (int i = 0; i < disabledChildCount; i++) {
9242                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9243                        boolean disabledPackageAvailable = false;
9244                        for (int j = 0; j < scannedChildCount; j++) {
9245                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9246                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9247                                disabledPackageAvailable = true;
9248                                break;
9249                            }
9250                         }
9251                         if (!disabledPackageAvailable) {
9252                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9253                         }
9254                    }
9255                }
9256            }
9257        }
9258
9259        final boolean isUpdatedPkg = updatedPkg != null;
9260        final boolean isUpdatedSystemPkg = isUpdatedPkg
9261                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9262        boolean isUpdatedPkgBetter = false;
9263        // First check if this is a system package that may involve an update
9264        if (isUpdatedSystemPkg) {
9265            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9266            // it needs to drop FLAG_PRIVILEGED.
9267            if (locationIsPrivileged(scanFile)) {
9268                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9269            } else {
9270                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9271            }
9272
9273            if (ps != null && !ps.codePath.equals(scanFile)) {
9274                // The path has changed from what was last scanned...  check the
9275                // version of the new path against what we have stored to determine
9276                // what to do.
9277                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9278                if (pkg.mVersionCode <= ps.versionCode) {
9279                    // The system package has been updated and the code path does not match
9280                    // Ignore entry. Skip it.
9281                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9282                            + " ignored: updated version " + ps.versionCode
9283                            + " better than this " + pkg.mVersionCode);
9284                    if (!updatedPkg.codePath.equals(scanFile)) {
9285                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9286                                + ps.name + " changing from " + updatedPkg.codePathString
9287                                + " to " + scanFile);
9288                        updatedPkg.codePath = scanFile;
9289                        updatedPkg.codePathString = scanFile.toString();
9290                        updatedPkg.resourcePath = scanFile;
9291                        updatedPkg.resourcePathString = scanFile.toString();
9292                    }
9293                    updatedPkg.pkg = pkg;
9294                    updatedPkg.versionCode = pkg.mVersionCode;
9295
9296                    // Update the disabled system child packages to point to the package too.
9297                    final int childCount = updatedPkg.childPackageNames != null
9298                            ? updatedPkg.childPackageNames.size() : 0;
9299                    for (int i = 0; i < childCount; i++) {
9300                        String childPackageName = updatedPkg.childPackageNames.get(i);
9301                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9302                                childPackageName);
9303                        if (updatedChildPkg != null) {
9304                            updatedChildPkg.pkg = pkg;
9305                            updatedChildPkg.versionCode = pkg.mVersionCode;
9306                        }
9307                    }
9308                } else {
9309                    // The current app on the system partition is better than
9310                    // what we have updated to on the data partition; switch
9311                    // back to the system partition version.
9312                    // At this point, its safely assumed that package installation for
9313                    // apps in system partition will go through. If not there won't be a working
9314                    // version of the app
9315                    // writer
9316                    synchronized (mPackages) {
9317                        // Just remove the loaded entries from package lists.
9318                        mPackages.remove(ps.name);
9319                    }
9320
9321                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9322                            + " reverting from " + ps.codePathString
9323                            + ": new version " + pkg.mVersionCode
9324                            + " better than installed " + ps.versionCode);
9325
9326                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9327                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9328                    synchronized (mInstallLock) {
9329                        args.cleanUpResourcesLI();
9330                    }
9331                    synchronized (mPackages) {
9332                        mSettings.enableSystemPackageLPw(ps.name);
9333                    }
9334                    isUpdatedPkgBetter = true;
9335                }
9336            }
9337        }
9338
9339        String resourcePath = null;
9340        String baseResourcePath = null;
9341        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9342            if (ps != null && ps.resourcePathString != null) {
9343                resourcePath = ps.resourcePathString;
9344                baseResourcePath = ps.resourcePathString;
9345            } else {
9346                // Should not happen at all. Just log an error.
9347                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9348            }
9349        } else {
9350            resourcePath = pkg.codePath;
9351            baseResourcePath = pkg.baseCodePath;
9352        }
9353
9354        // Set application objects path explicitly.
9355        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9356        pkg.setApplicationInfoCodePath(pkg.codePath);
9357        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9358        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9359        pkg.setApplicationInfoResourcePath(resourcePath);
9360        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9361        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9362
9363        // throw an exception if we have an update to a system application, but, it's not more
9364        // recent than the package we've already scanned
9365        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9366            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9367                    + scanFile + " ignored: updated version " + ps.versionCode
9368                    + " better than this " + pkg.mVersionCode);
9369        }
9370
9371        if (isUpdatedPkg) {
9372            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9373            // initially
9374            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9375
9376            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9377            // flag set initially
9378            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9379                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9380            }
9381        }
9382
9383        // Verify certificates against what was last scanned
9384        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9385
9386        /*
9387         * A new system app appeared, but we already had a non-system one of the
9388         * same name installed earlier.
9389         */
9390        boolean shouldHideSystemApp = false;
9391        if (!isUpdatedPkg && ps != null
9392                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9393            /*
9394             * Check to make sure the signatures match first. If they don't,
9395             * wipe the installed application and its data.
9396             */
9397            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9398                    != PackageManager.SIGNATURE_MATCH) {
9399                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9400                        + " signatures don't match existing userdata copy; removing");
9401                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9402                        "scanPackageInternalLI")) {
9403                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9404                }
9405                ps = null;
9406            } else {
9407                /*
9408                 * If the newly-added system app is an older version than the
9409                 * already installed version, hide it. It will be scanned later
9410                 * and re-added like an update.
9411                 */
9412                if (pkg.mVersionCode <= ps.versionCode) {
9413                    shouldHideSystemApp = true;
9414                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9415                            + " but new version " + pkg.mVersionCode + " better than installed "
9416                            + ps.versionCode + "; hiding system");
9417                } else {
9418                    /*
9419                     * The newly found system app is a newer version that the
9420                     * one previously installed. Simply remove the
9421                     * already-installed application and replace it with our own
9422                     * while keeping the application data.
9423                     */
9424                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9425                            + " reverting from " + ps.codePathString + ": new version "
9426                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9427                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9428                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9429                    synchronized (mInstallLock) {
9430                        args.cleanUpResourcesLI();
9431                    }
9432                }
9433            }
9434        }
9435
9436        // The apk is forward locked (not public) if its code and resources
9437        // are kept in different files. (except for app in either system or
9438        // vendor path).
9439        // TODO grab this value from PackageSettings
9440        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9441            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9442                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9443            }
9444        }
9445
9446        final int userId = ((user == null) ? 0 : user.getIdentifier());
9447        if (ps != null && ps.getInstantApp(userId)) {
9448            scanFlags |= SCAN_AS_INSTANT_APP;
9449        }
9450        if (ps != null && ps.getVirtulalPreload(userId)) {
9451            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9452        }
9453
9454        // Note that we invoke the following method only if we are about to unpack an application
9455        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9456                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9457
9458        /*
9459         * If the system app should be overridden by a previously installed
9460         * data, hide the system app now and let the /data/app scan pick it up
9461         * again.
9462         */
9463        if (shouldHideSystemApp) {
9464            synchronized (mPackages) {
9465                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9466            }
9467        }
9468
9469        return scannedPkg;
9470    }
9471
9472    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9473        // Derive the new package synthetic package name
9474        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9475                + pkg.staticSharedLibVersion);
9476    }
9477
9478    private static String fixProcessName(String defProcessName,
9479            String processName) {
9480        if (processName == null) {
9481            return defProcessName;
9482        }
9483        return processName;
9484    }
9485
9486    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9487            throws PackageManagerException {
9488        if (pkgSetting.signatures.mSignatures != null) {
9489            // Already existing package. Make sure signatures match
9490            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9491                    == PackageManager.SIGNATURE_MATCH;
9492            if (!match) {
9493                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9494                        == PackageManager.SIGNATURE_MATCH;
9495            }
9496            if (!match) {
9497                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9498                        == PackageManager.SIGNATURE_MATCH;
9499            }
9500            if (!match) {
9501                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9502                        + pkg.packageName + " signatures do not match the "
9503                        + "previously installed version; ignoring!");
9504            }
9505        }
9506
9507        // Check for shared user signatures
9508        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9509            // Already existing package. Make sure signatures match
9510            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9511                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9512            if (!match) {
9513                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9514                        == PackageManager.SIGNATURE_MATCH;
9515            }
9516            if (!match) {
9517                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9518                        == PackageManager.SIGNATURE_MATCH;
9519            }
9520            if (!match) {
9521                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9522                        "Package " + pkg.packageName
9523                        + " has no signatures that match those in shared user "
9524                        + pkgSetting.sharedUser.name + "; ignoring!");
9525            }
9526        }
9527    }
9528
9529    /**
9530     * Enforces that only the system UID or root's UID can call a method exposed
9531     * via Binder.
9532     *
9533     * @param message used as message if SecurityException is thrown
9534     * @throws SecurityException if the caller is not system or root
9535     */
9536    private static final void enforceSystemOrRoot(String message) {
9537        final int uid = Binder.getCallingUid();
9538        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9539            throw new SecurityException(message);
9540        }
9541    }
9542
9543    @Override
9544    public void performFstrimIfNeeded() {
9545        enforceSystemOrRoot("Only the system can request fstrim");
9546
9547        // Before everything else, see whether we need to fstrim.
9548        try {
9549            IStorageManager sm = PackageHelper.getStorageManager();
9550            if (sm != null) {
9551                boolean doTrim = false;
9552                final long interval = android.provider.Settings.Global.getLong(
9553                        mContext.getContentResolver(),
9554                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9555                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9556                if (interval > 0) {
9557                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9558                    if (timeSinceLast > interval) {
9559                        doTrim = true;
9560                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9561                                + "; running immediately");
9562                    }
9563                }
9564                if (doTrim) {
9565                    final boolean dexOptDialogShown;
9566                    synchronized (mPackages) {
9567                        dexOptDialogShown = mDexOptDialogShown;
9568                    }
9569                    if (!isFirstBoot() && dexOptDialogShown) {
9570                        try {
9571                            ActivityManager.getService().showBootMessage(
9572                                    mContext.getResources().getString(
9573                                            R.string.android_upgrading_fstrim), true);
9574                        } catch (RemoteException e) {
9575                        }
9576                    }
9577                    sm.runMaintenance();
9578                }
9579            } else {
9580                Slog.e(TAG, "storageManager service unavailable!");
9581            }
9582        } catch (RemoteException e) {
9583            // Can't happen; StorageManagerService is local
9584        }
9585    }
9586
9587    @Override
9588    public void updatePackagesIfNeeded() {
9589        enforceSystemOrRoot("Only the system can request package update");
9590
9591        // We need to re-extract after an OTA.
9592        boolean causeUpgrade = isUpgrade();
9593
9594        // First boot or factory reset.
9595        // Note: we also handle devices that are upgrading to N right now as if it is their
9596        //       first boot, as they do not have profile data.
9597        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9598
9599        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9600        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9601
9602        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9603            return;
9604        }
9605
9606        List<PackageParser.Package> pkgs;
9607        synchronized (mPackages) {
9608            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9609        }
9610
9611        final long startTime = System.nanoTime();
9612        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9613                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9614                    false /* bootComplete */);
9615
9616        final int elapsedTimeSeconds =
9617                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9618
9619        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9620        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9621        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9622        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9623        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9624    }
9625
9626    /*
9627     * Return the prebuilt profile path given a package base code path.
9628     */
9629    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9630        return pkg.baseCodePath + ".prof";
9631    }
9632
9633    /**
9634     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9635     * containing statistics about the invocation. The array consists of three elements,
9636     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9637     * and {@code numberOfPackagesFailed}.
9638     */
9639    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9640            String compilerFilter, boolean bootComplete) {
9641
9642        int numberOfPackagesVisited = 0;
9643        int numberOfPackagesOptimized = 0;
9644        int numberOfPackagesSkipped = 0;
9645        int numberOfPackagesFailed = 0;
9646        final int numberOfPackagesToDexopt = pkgs.size();
9647
9648        for (PackageParser.Package pkg : pkgs) {
9649            numberOfPackagesVisited++;
9650
9651            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9652                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9653                // that are already compiled.
9654                File profileFile = new File(getPrebuildProfilePath(pkg));
9655                // Copy profile if it exists.
9656                if (profileFile.exists()) {
9657                    try {
9658                        // We could also do this lazily before calling dexopt in
9659                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9660                        // is that we don't have a good way to say "do this only once".
9661                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9662                                pkg.applicationInfo.uid, pkg.packageName)) {
9663                            Log.e(TAG, "Installer failed to copy system profile!");
9664                        }
9665                    } catch (Exception e) {
9666                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9667                                e);
9668                    }
9669                }
9670            }
9671
9672            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9673                if (DEBUG_DEXOPT) {
9674                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9675                }
9676                numberOfPackagesSkipped++;
9677                continue;
9678            }
9679
9680            if (DEBUG_DEXOPT) {
9681                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9682                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9683            }
9684
9685            if (showDialog) {
9686                try {
9687                    ActivityManager.getService().showBootMessage(
9688                            mContext.getResources().getString(R.string.android_upgrading_apk,
9689                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9690                } catch (RemoteException e) {
9691                }
9692                synchronized (mPackages) {
9693                    mDexOptDialogShown = true;
9694                }
9695            }
9696
9697            // If the OTA updates a system app which was previously preopted to a non-preopted state
9698            // the app might end up being verified at runtime. That's because by default the apps
9699            // are verify-profile but for preopted apps there's no profile.
9700            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9701            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9702            // filter (by default 'quicken').
9703            // Note that at this stage unused apps are already filtered.
9704            if (isSystemApp(pkg) &&
9705                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9706                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9707                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9708            }
9709
9710            // checkProfiles is false to avoid merging profiles during boot which
9711            // might interfere with background compilation (b/28612421).
9712            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9713            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9714            // trade-off worth doing to save boot time work.
9715            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9716            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9717                    pkg.packageName,
9718                    compilerFilter,
9719                    dexoptFlags));
9720
9721            if (pkg.isSystemApp()) {
9722                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9723                // too much boot after an OTA.
9724                int secondaryDexoptFlags = dexoptFlags |
9725                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9726                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9727                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9728                        pkg.packageName,
9729                        compilerFilter,
9730                        secondaryDexoptFlags));
9731            }
9732
9733            // TODO(shubhamajmera): Record secondary dexopt stats.
9734            switch (primaryDexOptStaus) {
9735                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9736                    numberOfPackagesOptimized++;
9737                    break;
9738                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9739                    numberOfPackagesSkipped++;
9740                    break;
9741                case PackageDexOptimizer.DEX_OPT_FAILED:
9742                    numberOfPackagesFailed++;
9743                    break;
9744                default:
9745                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9746                    break;
9747            }
9748        }
9749
9750        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9751                numberOfPackagesFailed };
9752    }
9753
9754    @Override
9755    public void notifyPackageUse(String packageName, int reason) {
9756        synchronized (mPackages) {
9757            final int callingUid = Binder.getCallingUid();
9758            final int callingUserId = UserHandle.getUserId(callingUid);
9759            if (getInstantAppPackageName(callingUid) != null) {
9760                if (!isCallerSameApp(packageName, callingUid)) {
9761                    return;
9762                }
9763            } else {
9764                if (isInstantApp(packageName, callingUserId)) {
9765                    return;
9766                }
9767            }
9768            final PackageParser.Package p = mPackages.get(packageName);
9769            if (p == null) {
9770                return;
9771            }
9772            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9773        }
9774    }
9775
9776    @Override
9777    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9778            List<String> classPaths, String loaderIsa) {
9779        int userId = UserHandle.getCallingUserId();
9780        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9781        if (ai == null) {
9782            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9783                + loadingPackageName + ", user=" + userId);
9784            return;
9785        }
9786        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9787    }
9788
9789    @Override
9790    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9791            IDexModuleRegisterCallback callback) {
9792        int userId = UserHandle.getCallingUserId();
9793        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9794        DexManager.RegisterDexModuleResult result;
9795        if (ai == null) {
9796            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9797                     " calling user. package=" + packageName + ", user=" + userId);
9798            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9799        } else {
9800            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9801        }
9802
9803        if (callback != null) {
9804            mHandler.post(() -> {
9805                try {
9806                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9807                } catch (RemoteException e) {
9808                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9809                }
9810            });
9811        }
9812    }
9813
9814    /**
9815     * Ask the package manager to perform a dex-opt with the given compiler filter.
9816     *
9817     * Note: exposed only for the shell command to allow moving packages explicitly to a
9818     *       definite state.
9819     */
9820    @Override
9821    public boolean performDexOptMode(String packageName,
9822            boolean checkProfiles, String targetCompilerFilter, boolean force,
9823            boolean bootComplete, String splitName) {
9824        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9825                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9826                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9827        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9828                splitName, flags));
9829    }
9830
9831    /**
9832     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9833     * secondary dex files belonging to the given package.
9834     *
9835     * Note: exposed only for the shell command to allow moving packages explicitly to a
9836     *       definite state.
9837     */
9838    @Override
9839    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9840            boolean force) {
9841        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9842                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9843                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9844                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9845        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9846    }
9847
9848    /*package*/ boolean performDexOpt(DexoptOptions options) {
9849        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9850            return false;
9851        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9852            return false;
9853        }
9854
9855        if (options.isDexoptOnlySecondaryDex()) {
9856            return mDexManager.dexoptSecondaryDex(options);
9857        } else {
9858            int dexoptStatus = performDexOptWithStatus(options);
9859            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9860        }
9861    }
9862
9863    /**
9864     * Perform dexopt on the given package and return one of following result:
9865     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9866     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9867     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9868     */
9869    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9870        return performDexOptTraced(options);
9871    }
9872
9873    private int performDexOptTraced(DexoptOptions options) {
9874        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9875        try {
9876            return performDexOptInternal(options);
9877        } finally {
9878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9879        }
9880    }
9881
9882    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9883    // if the package can now be considered up to date for the given filter.
9884    private int performDexOptInternal(DexoptOptions options) {
9885        PackageParser.Package p;
9886        synchronized (mPackages) {
9887            p = mPackages.get(options.getPackageName());
9888            if (p == null) {
9889                // Package could not be found. Report failure.
9890                return PackageDexOptimizer.DEX_OPT_FAILED;
9891            }
9892            mPackageUsage.maybeWriteAsync(mPackages);
9893            mCompilerStats.maybeWriteAsync();
9894        }
9895        long callingId = Binder.clearCallingIdentity();
9896        try {
9897            synchronized (mInstallLock) {
9898                return performDexOptInternalWithDependenciesLI(p, options);
9899            }
9900        } finally {
9901            Binder.restoreCallingIdentity(callingId);
9902        }
9903    }
9904
9905    public ArraySet<String> getOptimizablePackages() {
9906        ArraySet<String> pkgs = new ArraySet<String>();
9907        synchronized (mPackages) {
9908            for (PackageParser.Package p : mPackages.values()) {
9909                if (PackageDexOptimizer.canOptimizePackage(p)) {
9910                    pkgs.add(p.packageName);
9911                }
9912            }
9913        }
9914        return pkgs;
9915    }
9916
9917    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9918            DexoptOptions options) {
9919        // Select the dex optimizer based on the force parameter.
9920        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9921        //       allocate an object here.
9922        PackageDexOptimizer pdo = options.isForce()
9923                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9924                : mPackageDexOptimizer;
9925
9926        // Dexopt all dependencies first. Note: we ignore the return value and march on
9927        // on errors.
9928        // Note that we are going to call performDexOpt on those libraries as many times as
9929        // they are referenced in packages. When we do a batch of performDexOpt (for example
9930        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9931        // and the first package that uses the library will dexopt it. The
9932        // others will see that the compiled code for the library is up to date.
9933        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9934        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9935        if (!deps.isEmpty()) {
9936            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9937                    options.getCompilerFilter(), options.getSplitName(),
9938                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9939            for (PackageParser.Package depPackage : deps) {
9940                // TODO: Analyze and investigate if we (should) profile libraries.
9941                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9942                        getOrCreateCompilerPackageStats(depPackage),
9943                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9944            }
9945        }
9946        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9947                getOrCreateCompilerPackageStats(p),
9948                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9949    }
9950
9951    /**
9952     * Reconcile the information we have about the secondary dex files belonging to
9953     * {@code packagName} and the actual dex files. For all dex files that were
9954     * deleted, update the internal records and delete the generated oat files.
9955     */
9956    @Override
9957    public void reconcileSecondaryDexFiles(String packageName) {
9958        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9959            return;
9960        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9961            return;
9962        }
9963        mDexManager.reconcileSecondaryDexFiles(packageName);
9964    }
9965
9966    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9967    // a reference there.
9968    /*package*/ DexManager getDexManager() {
9969        return mDexManager;
9970    }
9971
9972    /**
9973     * Execute the background dexopt job immediately.
9974     */
9975    @Override
9976    public boolean runBackgroundDexoptJob() {
9977        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9978            return false;
9979        }
9980        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9981    }
9982
9983    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9984        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9985                || p.usesStaticLibraries != null) {
9986            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9987            Set<String> collectedNames = new HashSet<>();
9988            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9989
9990            retValue.remove(p);
9991
9992            return retValue;
9993        } else {
9994            return Collections.emptyList();
9995        }
9996    }
9997
9998    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9999            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10000        if (!collectedNames.contains(p.packageName)) {
10001            collectedNames.add(p.packageName);
10002            collected.add(p);
10003
10004            if (p.usesLibraries != null) {
10005                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10006                        null, collected, collectedNames);
10007            }
10008            if (p.usesOptionalLibraries != null) {
10009                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10010                        null, collected, collectedNames);
10011            }
10012            if (p.usesStaticLibraries != null) {
10013                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10014                        p.usesStaticLibrariesVersions, collected, collectedNames);
10015            }
10016        }
10017    }
10018
10019    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10020            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10021        final int libNameCount = libs.size();
10022        for (int i = 0; i < libNameCount; i++) {
10023            String libName = libs.get(i);
10024            int version = (versions != null && versions.length == libNameCount)
10025                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10026            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10027            if (libPkg != null) {
10028                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10029            }
10030        }
10031    }
10032
10033    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10034        synchronized (mPackages) {
10035            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10036            if (libEntry != null) {
10037                return mPackages.get(libEntry.apk);
10038            }
10039            return null;
10040        }
10041    }
10042
10043    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10044        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10045        if (versionedLib == null) {
10046            return null;
10047        }
10048        return versionedLib.get(version);
10049    }
10050
10051    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10052        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10053                pkg.staticSharedLibName);
10054        if (versionedLib == null) {
10055            return null;
10056        }
10057        int previousLibVersion = -1;
10058        final int versionCount = versionedLib.size();
10059        for (int i = 0; i < versionCount; i++) {
10060            final int libVersion = versionedLib.keyAt(i);
10061            if (libVersion < pkg.staticSharedLibVersion) {
10062                previousLibVersion = Math.max(previousLibVersion, libVersion);
10063            }
10064        }
10065        if (previousLibVersion >= 0) {
10066            return versionedLib.get(previousLibVersion);
10067        }
10068        return null;
10069    }
10070
10071    public void shutdown() {
10072        mPackageUsage.writeNow(mPackages);
10073        mCompilerStats.writeNow();
10074        mDexManager.writePackageDexUsageNow();
10075    }
10076
10077    @Override
10078    public void dumpProfiles(String packageName) {
10079        PackageParser.Package pkg;
10080        synchronized (mPackages) {
10081            pkg = mPackages.get(packageName);
10082            if (pkg == null) {
10083                throw new IllegalArgumentException("Unknown package: " + packageName);
10084            }
10085        }
10086        /* Only the shell, root, or the app user should be able to dump profiles. */
10087        int callingUid = Binder.getCallingUid();
10088        if (callingUid != Process.SHELL_UID &&
10089            callingUid != Process.ROOT_UID &&
10090            callingUid != pkg.applicationInfo.uid) {
10091            throw new SecurityException("dumpProfiles");
10092        }
10093
10094        synchronized (mInstallLock) {
10095            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10096            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10097            try {
10098                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10099                String codePaths = TextUtils.join(";", allCodePaths);
10100                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10101            } catch (InstallerException e) {
10102                Slog.w(TAG, "Failed to dump profiles", e);
10103            }
10104            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10105        }
10106    }
10107
10108    @Override
10109    public void forceDexOpt(String packageName) {
10110        enforceSystemOrRoot("forceDexOpt");
10111
10112        PackageParser.Package pkg;
10113        synchronized (mPackages) {
10114            pkg = mPackages.get(packageName);
10115            if (pkg == null) {
10116                throw new IllegalArgumentException("Unknown package: " + packageName);
10117            }
10118        }
10119
10120        synchronized (mInstallLock) {
10121            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10122
10123            // Whoever is calling forceDexOpt wants a compiled package.
10124            // Don't use profiles since that may cause compilation to be skipped.
10125            final int res = performDexOptInternalWithDependenciesLI(
10126                    pkg,
10127                    new DexoptOptions(packageName,
10128                            getDefaultCompilerFilter(),
10129                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10130
10131            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10132            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10133                throw new IllegalStateException("Failed to dexopt: " + res);
10134            }
10135        }
10136    }
10137
10138    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10139        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10140            Slog.w(TAG, "Unable to update from " + oldPkg.name
10141                    + " to " + newPkg.packageName
10142                    + ": old package not in system partition");
10143            return false;
10144        } else if (mPackages.get(oldPkg.name) != null) {
10145            Slog.w(TAG, "Unable to update from " + oldPkg.name
10146                    + " to " + newPkg.packageName
10147                    + ": old package still exists");
10148            return false;
10149        }
10150        return true;
10151    }
10152
10153    void removeCodePathLI(File codePath) {
10154        if (codePath.isDirectory()) {
10155            try {
10156                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10157            } catch (InstallerException e) {
10158                Slog.w(TAG, "Failed to remove code path", e);
10159            }
10160        } else {
10161            codePath.delete();
10162        }
10163    }
10164
10165    private int[] resolveUserIds(int userId) {
10166        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10167    }
10168
10169    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10170        if (pkg == null) {
10171            Slog.wtf(TAG, "Package was null!", new Throwable());
10172            return;
10173        }
10174        clearAppDataLeafLIF(pkg, userId, flags);
10175        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10176        for (int i = 0; i < childCount; i++) {
10177            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10178        }
10179    }
10180
10181    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10182        final PackageSetting ps;
10183        synchronized (mPackages) {
10184            ps = mSettings.mPackages.get(pkg.packageName);
10185        }
10186        for (int realUserId : resolveUserIds(userId)) {
10187            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10188            try {
10189                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10190                        ceDataInode);
10191            } catch (InstallerException e) {
10192                Slog.w(TAG, String.valueOf(e));
10193            }
10194        }
10195    }
10196
10197    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10198        if (pkg == null) {
10199            Slog.wtf(TAG, "Package was null!", new Throwable());
10200            return;
10201        }
10202        destroyAppDataLeafLIF(pkg, userId, flags);
10203        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10204        for (int i = 0; i < childCount; i++) {
10205            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10206        }
10207    }
10208
10209    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10210        final PackageSetting ps;
10211        synchronized (mPackages) {
10212            ps = mSettings.mPackages.get(pkg.packageName);
10213        }
10214        for (int realUserId : resolveUserIds(userId)) {
10215            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10216            try {
10217                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10218                        ceDataInode);
10219            } catch (InstallerException e) {
10220                Slog.w(TAG, String.valueOf(e));
10221            }
10222            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10223        }
10224    }
10225
10226    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10227        if (pkg == null) {
10228            Slog.wtf(TAG, "Package was null!", new Throwable());
10229            return;
10230        }
10231        destroyAppProfilesLeafLIF(pkg);
10232        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10233        for (int i = 0; i < childCount; i++) {
10234            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10235        }
10236    }
10237
10238    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10239        try {
10240            mInstaller.destroyAppProfiles(pkg.packageName);
10241        } catch (InstallerException e) {
10242            Slog.w(TAG, String.valueOf(e));
10243        }
10244    }
10245
10246    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10247        if (pkg == null) {
10248            Slog.wtf(TAG, "Package was null!", new Throwable());
10249            return;
10250        }
10251        clearAppProfilesLeafLIF(pkg);
10252        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10253        for (int i = 0; i < childCount; i++) {
10254            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10255        }
10256    }
10257
10258    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10259        try {
10260            mInstaller.clearAppProfiles(pkg.packageName);
10261        } catch (InstallerException e) {
10262            Slog.w(TAG, String.valueOf(e));
10263        }
10264    }
10265
10266    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10267            long lastUpdateTime) {
10268        // Set parent install/update time
10269        PackageSetting ps = (PackageSetting) pkg.mExtras;
10270        if (ps != null) {
10271            ps.firstInstallTime = firstInstallTime;
10272            ps.lastUpdateTime = lastUpdateTime;
10273        }
10274        // Set children install/update time
10275        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10276        for (int i = 0; i < childCount; i++) {
10277            PackageParser.Package childPkg = pkg.childPackages.get(i);
10278            ps = (PackageSetting) childPkg.mExtras;
10279            if (ps != null) {
10280                ps.firstInstallTime = firstInstallTime;
10281                ps.lastUpdateTime = lastUpdateTime;
10282            }
10283        }
10284    }
10285
10286    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10287            PackageParser.Package changingLib) {
10288        if (file.path != null) {
10289            usesLibraryFiles.add(file.path);
10290            return;
10291        }
10292        PackageParser.Package p = mPackages.get(file.apk);
10293        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10294            // If we are doing this while in the middle of updating a library apk,
10295            // then we need to make sure to use that new apk for determining the
10296            // dependencies here.  (We haven't yet finished committing the new apk
10297            // to the package manager state.)
10298            if (p == null || p.packageName.equals(changingLib.packageName)) {
10299                p = changingLib;
10300            }
10301        }
10302        if (p != null) {
10303            usesLibraryFiles.addAll(p.getAllCodePaths());
10304            if (p.usesLibraryFiles != null) {
10305                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10306            }
10307        }
10308    }
10309
10310    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10311            PackageParser.Package changingLib) throws PackageManagerException {
10312        if (pkg == null) {
10313            return;
10314        }
10315        ArraySet<String> usesLibraryFiles = null;
10316        if (pkg.usesLibraries != null) {
10317            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10318                    null, null, pkg.packageName, changingLib, true, null);
10319        }
10320        if (pkg.usesStaticLibraries != null) {
10321            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10322                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10323                    pkg.packageName, changingLib, true, usesLibraryFiles);
10324        }
10325        if (pkg.usesOptionalLibraries != null) {
10326            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10327                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10328        }
10329        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10330            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10331        } else {
10332            pkg.usesLibraryFiles = null;
10333        }
10334    }
10335
10336    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10337            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10338            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10339            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10340            throws PackageManagerException {
10341        final int libCount = requestedLibraries.size();
10342        for (int i = 0; i < libCount; i++) {
10343            final String libName = requestedLibraries.get(i);
10344            final int libVersion = requiredVersions != null ? requiredVersions[i]
10345                    : SharedLibraryInfo.VERSION_UNDEFINED;
10346            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10347            if (libEntry == null) {
10348                if (required) {
10349                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10350                            "Package " + packageName + " requires unavailable shared library "
10351                                    + libName + "; failing!");
10352                } else if (DEBUG_SHARED_LIBRARIES) {
10353                    Slog.i(TAG, "Package " + packageName
10354                            + " desires unavailable shared library "
10355                            + libName + "; ignoring!");
10356                }
10357            } else {
10358                if (requiredVersions != null && requiredCertDigests != null) {
10359                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10360                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10361                            "Package " + packageName + " requires unavailable static shared"
10362                                    + " library " + libName + " version "
10363                                    + libEntry.info.getVersion() + "; failing!");
10364                    }
10365
10366                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10367                    if (libPkg == null) {
10368                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10369                                "Package " + packageName + " requires unavailable static shared"
10370                                        + " library; failing!");
10371                    }
10372
10373                    String expectedCertDigest = requiredCertDigests[i];
10374                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10375                                libPkg.mSignatures[0]);
10376                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10377                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10378                                "Package " + packageName + " requires differently signed" +
10379                                        " static shared library; failing!");
10380                    }
10381                }
10382
10383                if (outUsedLibraries == null) {
10384                    outUsedLibraries = new ArraySet<>();
10385                }
10386                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10387            }
10388        }
10389        return outUsedLibraries;
10390    }
10391
10392    private static boolean hasString(List<String> list, List<String> which) {
10393        if (list == null) {
10394            return false;
10395        }
10396        for (int i=list.size()-1; i>=0; i--) {
10397            for (int j=which.size()-1; j>=0; j--) {
10398                if (which.get(j).equals(list.get(i))) {
10399                    return true;
10400                }
10401            }
10402        }
10403        return false;
10404    }
10405
10406    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10407            PackageParser.Package changingPkg) {
10408        ArrayList<PackageParser.Package> res = null;
10409        for (PackageParser.Package pkg : mPackages.values()) {
10410            if (changingPkg != null
10411                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10412                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10413                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10414                            changingPkg.staticSharedLibName)) {
10415                return null;
10416            }
10417            if (res == null) {
10418                res = new ArrayList<>();
10419            }
10420            res.add(pkg);
10421            try {
10422                updateSharedLibrariesLPr(pkg, changingPkg);
10423            } catch (PackageManagerException e) {
10424                // If a system app update or an app and a required lib missing we
10425                // delete the package and for updated system apps keep the data as
10426                // it is better for the user to reinstall than to be in an limbo
10427                // state. Also libs disappearing under an app should never happen
10428                // - just in case.
10429                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10430                    final int flags = pkg.isUpdatedSystemApp()
10431                            ? PackageManager.DELETE_KEEP_DATA : 0;
10432                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10433                            flags , null, true, null);
10434                }
10435                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10436            }
10437        }
10438        return res;
10439    }
10440
10441    /**
10442     * Derive the value of the {@code cpuAbiOverride} based on the provided
10443     * value and an optional stored value from the package settings.
10444     */
10445    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10446        String cpuAbiOverride = null;
10447
10448        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10449            cpuAbiOverride = null;
10450        } else if (abiOverride != null) {
10451            cpuAbiOverride = abiOverride;
10452        } else if (settings != null) {
10453            cpuAbiOverride = settings.cpuAbiOverrideString;
10454        }
10455
10456        return cpuAbiOverride;
10457    }
10458
10459    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10460            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10461                    throws PackageManagerException {
10462        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10463        // If the package has children and this is the first dive in the function
10464        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10465        // whether all packages (parent and children) would be successfully scanned
10466        // before the actual scan since scanning mutates internal state and we want
10467        // to atomically install the package and its children.
10468        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10469            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10470                scanFlags |= SCAN_CHECK_ONLY;
10471            }
10472        } else {
10473            scanFlags &= ~SCAN_CHECK_ONLY;
10474        }
10475
10476        final PackageParser.Package scannedPkg;
10477        try {
10478            // Scan the parent
10479            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10480            // Scan the children
10481            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10482            for (int i = 0; i < childCount; i++) {
10483                PackageParser.Package childPkg = pkg.childPackages.get(i);
10484                scanPackageLI(childPkg, policyFlags,
10485                        scanFlags, currentTime, user);
10486            }
10487        } finally {
10488            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10489        }
10490
10491        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10492            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10493        }
10494
10495        return scannedPkg;
10496    }
10497
10498    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10499            int scanFlags, long currentTime, @Nullable UserHandle user)
10500                    throws PackageManagerException {
10501        boolean success = false;
10502        try {
10503            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10504                    currentTime, user);
10505            success = true;
10506            return res;
10507        } finally {
10508            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10509                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10510                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10511                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10512                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10513            }
10514        }
10515    }
10516
10517    /**
10518     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10519     */
10520    private static boolean apkHasCode(String fileName) {
10521        StrictJarFile jarFile = null;
10522        try {
10523            jarFile = new StrictJarFile(fileName,
10524                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10525            return jarFile.findEntry("classes.dex") != null;
10526        } catch (IOException ignore) {
10527        } finally {
10528            try {
10529                if (jarFile != null) {
10530                    jarFile.close();
10531                }
10532            } catch (IOException ignore) {}
10533        }
10534        return false;
10535    }
10536
10537    /**
10538     * Enforces code policy for the package. This ensures that if an APK has
10539     * declared hasCode="true" in its manifest that the APK actually contains
10540     * code.
10541     *
10542     * @throws PackageManagerException If bytecode could not be found when it should exist
10543     */
10544    private static void assertCodePolicy(PackageParser.Package pkg)
10545            throws PackageManagerException {
10546        final boolean shouldHaveCode =
10547                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10548        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10549            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10550                    "Package " + pkg.baseCodePath + " code is missing");
10551        }
10552
10553        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10554            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10555                final boolean splitShouldHaveCode =
10556                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10557                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10558                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10559                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10560                }
10561            }
10562        }
10563    }
10564
10565    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10566            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10567                    throws PackageManagerException {
10568        if (DEBUG_PACKAGE_SCANNING) {
10569            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10570                Log.d(TAG, "Scanning package " + pkg.packageName);
10571        }
10572
10573        applyPolicy(pkg, policyFlags);
10574
10575        assertPackageIsValid(pkg, policyFlags, scanFlags);
10576
10577        // Initialize package source and resource directories
10578        final File scanFile = new File(pkg.codePath);
10579        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10580        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10581
10582        SharedUserSetting suid = null;
10583        PackageSetting pkgSetting = null;
10584
10585        // Getting the package setting may have a side-effect, so if we
10586        // are only checking if scan would succeed, stash a copy of the
10587        // old setting to restore at the end.
10588        PackageSetting nonMutatedPs = null;
10589
10590        // We keep references to the derived CPU Abis from settings in oder to reuse
10591        // them in the case where we're not upgrading or booting for the first time.
10592        String primaryCpuAbiFromSettings = null;
10593        String secondaryCpuAbiFromSettings = null;
10594
10595        // writer
10596        synchronized (mPackages) {
10597            if (pkg.mSharedUserId != null) {
10598                // SIDE EFFECTS; may potentially allocate a new shared user
10599                suid = mSettings.getSharedUserLPw(
10600                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10601                if (DEBUG_PACKAGE_SCANNING) {
10602                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10603                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10604                                + "): packages=" + suid.packages);
10605                }
10606            }
10607
10608            // Check if we are renaming from an original package name.
10609            PackageSetting origPackage = null;
10610            String realName = null;
10611            if (pkg.mOriginalPackages != null) {
10612                // This package may need to be renamed to a previously
10613                // installed name.  Let's check on that...
10614                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10615                if (pkg.mOriginalPackages.contains(renamed)) {
10616                    // This package had originally been installed as the
10617                    // original name, and we have already taken care of
10618                    // transitioning to the new one.  Just update the new
10619                    // one to continue using the old name.
10620                    realName = pkg.mRealPackage;
10621                    if (!pkg.packageName.equals(renamed)) {
10622                        // Callers into this function may have already taken
10623                        // care of renaming the package; only do it here if
10624                        // it is not already done.
10625                        pkg.setPackageName(renamed);
10626                    }
10627                } else {
10628                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10629                        if ((origPackage = mSettings.getPackageLPr(
10630                                pkg.mOriginalPackages.get(i))) != null) {
10631                            // We do have the package already installed under its
10632                            // original name...  should we use it?
10633                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10634                                // New package is not compatible with original.
10635                                origPackage = null;
10636                                continue;
10637                            } else if (origPackage.sharedUser != null) {
10638                                // Make sure uid is compatible between packages.
10639                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10640                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10641                                            + " to " + pkg.packageName + ": old uid "
10642                                            + origPackage.sharedUser.name
10643                                            + " differs from " + pkg.mSharedUserId);
10644                                    origPackage = null;
10645                                    continue;
10646                                }
10647                                // TODO: Add case when shared user id is added [b/28144775]
10648                            } else {
10649                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10650                                        + pkg.packageName + " to old name " + origPackage.name);
10651                            }
10652                            break;
10653                        }
10654                    }
10655                }
10656            }
10657
10658            if (mTransferedPackages.contains(pkg.packageName)) {
10659                Slog.w(TAG, "Package " + pkg.packageName
10660                        + " was transferred to another, but its .apk remains");
10661            }
10662
10663            // See comments in nonMutatedPs declaration
10664            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10665                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10666                if (foundPs != null) {
10667                    nonMutatedPs = new PackageSetting(foundPs);
10668                }
10669            }
10670
10671            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10672                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10673                if (foundPs != null) {
10674                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10675                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10676                }
10677            }
10678
10679            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10680            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10681                PackageManagerService.reportSettingsProblem(Log.WARN,
10682                        "Package " + pkg.packageName + " shared user changed from "
10683                                + (pkgSetting.sharedUser != null
10684                                        ? pkgSetting.sharedUser.name : "<nothing>")
10685                                + " to "
10686                                + (suid != null ? suid.name : "<nothing>")
10687                                + "; replacing with new");
10688                pkgSetting = null;
10689            }
10690            final PackageSetting oldPkgSetting =
10691                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10692            final PackageSetting disabledPkgSetting =
10693                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10694
10695            String[] usesStaticLibraries = null;
10696            if (pkg.usesStaticLibraries != null) {
10697                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10698                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10699            }
10700
10701            if (pkgSetting == null) {
10702                final String parentPackageName = (pkg.parentPackage != null)
10703                        ? pkg.parentPackage.packageName : null;
10704                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10705                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10706                // REMOVE SharedUserSetting from method; update in a separate call
10707                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10708                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10709                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10710                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10711                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10712                        true /*allowInstall*/, instantApp, virtualPreload,
10713                        parentPackageName, pkg.getChildPackageNames(),
10714                        UserManagerService.getInstance(), usesStaticLibraries,
10715                        pkg.usesStaticLibrariesVersions);
10716                // SIDE EFFECTS; updates system state; move elsewhere
10717                if (origPackage != null) {
10718                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10719                }
10720                mSettings.addUserToSettingLPw(pkgSetting);
10721            } else {
10722                // REMOVE SharedUserSetting from method; update in a separate call.
10723                //
10724                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10725                // secondaryCpuAbi are not known at this point so we always update them
10726                // to null here, only to reset them at a later point.
10727                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10728                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10729                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10730                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10731                        UserManagerService.getInstance(), usesStaticLibraries,
10732                        pkg.usesStaticLibrariesVersions);
10733            }
10734            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10735            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10736
10737            // SIDE EFFECTS; modifies system state; move elsewhere
10738            if (pkgSetting.origPackage != null) {
10739                // If we are first transitioning from an original package,
10740                // fix up the new package's name now.  We need to do this after
10741                // looking up the package under its new name, so getPackageLP
10742                // can take care of fiddling things correctly.
10743                pkg.setPackageName(origPackage.name);
10744
10745                // File a report about this.
10746                String msg = "New package " + pkgSetting.realName
10747                        + " renamed to replace old package " + pkgSetting.name;
10748                reportSettingsProblem(Log.WARN, msg);
10749
10750                // Make a note of it.
10751                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10752                    mTransferedPackages.add(origPackage.name);
10753                }
10754
10755                // No longer need to retain this.
10756                pkgSetting.origPackage = null;
10757            }
10758
10759            // SIDE EFFECTS; modifies system state; move elsewhere
10760            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10761                // Make a note of it.
10762                mTransferedPackages.add(pkg.packageName);
10763            }
10764
10765            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10766                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10767            }
10768
10769            if ((scanFlags & SCAN_BOOTING) == 0
10770                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10771                // Check all shared libraries and map to their actual file path.
10772                // We only do this here for apps not on a system dir, because those
10773                // are the only ones that can fail an install due to this.  We
10774                // will take care of the system apps by updating all of their
10775                // library paths after the scan is done. Also during the initial
10776                // scan don't update any libs as we do this wholesale after all
10777                // apps are scanned to avoid dependency based scanning.
10778                updateSharedLibrariesLPr(pkg, null);
10779            }
10780
10781            if (mFoundPolicyFile) {
10782                SELinuxMMAC.assignSeInfoValue(pkg);
10783            }
10784            pkg.applicationInfo.uid = pkgSetting.appId;
10785            pkg.mExtras = pkgSetting;
10786
10787
10788            // Static shared libs have same package with different versions where
10789            // we internally use a synthetic package name to allow multiple versions
10790            // of the same package, therefore we need to compare signatures against
10791            // the package setting for the latest library version.
10792            PackageSetting signatureCheckPs = pkgSetting;
10793            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10794                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10795                if (libraryEntry != null) {
10796                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10797                }
10798            }
10799
10800            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10801                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10802                    // We just determined the app is signed correctly, so bring
10803                    // over the latest parsed certs.
10804                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10805                } else {
10806                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10807                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10808                                "Package " + pkg.packageName + " upgrade keys do not match the "
10809                                + "previously installed version");
10810                    } else {
10811                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10812                        String msg = "System package " + pkg.packageName
10813                                + " signature changed; retaining data.";
10814                        reportSettingsProblem(Log.WARN, msg);
10815                    }
10816                }
10817            } else {
10818                try {
10819                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10820                    verifySignaturesLP(signatureCheckPs, pkg);
10821                    // We just determined the app is signed correctly, so bring
10822                    // over the latest parsed certs.
10823                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10824                } catch (PackageManagerException e) {
10825                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10826                        throw e;
10827                    }
10828                    // The signature has changed, but this package is in the system
10829                    // image...  let's recover!
10830                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10831                    // However...  if this package is part of a shared user, but it
10832                    // doesn't match the signature of the shared user, let's fail.
10833                    // What this means is that you can't change the signatures
10834                    // associated with an overall shared user, which doesn't seem all
10835                    // that unreasonable.
10836                    if (signatureCheckPs.sharedUser != null) {
10837                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10838                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10839                            throw new PackageManagerException(
10840                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10841                                    "Signature mismatch for shared user: "
10842                                            + pkgSetting.sharedUser);
10843                        }
10844                    }
10845                    // File a report about this.
10846                    String msg = "System package " + pkg.packageName
10847                            + " signature changed; retaining data.";
10848                    reportSettingsProblem(Log.WARN, msg);
10849                }
10850            }
10851
10852            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10853                // This package wants to adopt ownership of permissions from
10854                // another package.
10855                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10856                    final String origName = pkg.mAdoptPermissions.get(i);
10857                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10858                    if (orig != null) {
10859                        if (verifyPackageUpdateLPr(orig, pkg)) {
10860                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10861                                    + pkg.packageName);
10862                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10863                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10864                        }
10865                    }
10866                }
10867            }
10868        }
10869
10870        pkg.applicationInfo.processName = fixProcessName(
10871                pkg.applicationInfo.packageName,
10872                pkg.applicationInfo.processName);
10873
10874        if (pkg != mPlatformPackage) {
10875            // Get all of our default paths setup
10876            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10877        }
10878
10879        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10880
10881        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10882            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10883                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10884                final boolean extractNativeLibs = !pkg.isLibrary();
10885                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10886                        mAppLib32InstallDir);
10887                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10888
10889                // Some system apps still use directory structure for native libraries
10890                // in which case we might end up not detecting abi solely based on apk
10891                // structure. Try to detect abi based on directory structure.
10892                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10893                        pkg.applicationInfo.primaryCpuAbi == null) {
10894                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10895                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10896                }
10897            } else {
10898                // This is not a first boot or an upgrade, don't bother deriving the
10899                // ABI during the scan. Instead, trust the value that was stored in the
10900                // package setting.
10901                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10902                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10903
10904                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10905
10906                if (DEBUG_ABI_SELECTION) {
10907                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10908                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10909                        pkg.applicationInfo.secondaryCpuAbi);
10910                }
10911            }
10912        } else {
10913            if ((scanFlags & SCAN_MOVE) != 0) {
10914                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10915                // but we already have this packages package info in the PackageSetting. We just
10916                // use that and derive the native library path based on the new codepath.
10917                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10918                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10919            }
10920
10921            // Set native library paths again. For moves, the path will be updated based on the
10922            // ABIs we've determined above. For non-moves, the path will be updated based on the
10923            // ABIs we determined during compilation, but the path will depend on the final
10924            // package path (after the rename away from the stage path).
10925            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10926        }
10927
10928        // This is a special case for the "system" package, where the ABI is
10929        // dictated by the zygote configuration (and init.rc). We should keep track
10930        // of this ABI so that we can deal with "normal" applications that run under
10931        // the same UID correctly.
10932        if (mPlatformPackage == pkg) {
10933            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10934                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10935        }
10936
10937        // If there's a mismatch between the abi-override in the package setting
10938        // and the abiOverride specified for the install. Warn about this because we
10939        // would've already compiled the app without taking the package setting into
10940        // account.
10941        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10942            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10943                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10944                        " for package " + pkg.packageName);
10945            }
10946        }
10947
10948        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10949        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10950        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10951
10952        // Copy the derived override back to the parsed package, so that we can
10953        // update the package settings accordingly.
10954        pkg.cpuAbiOverride = cpuAbiOverride;
10955
10956        if (DEBUG_ABI_SELECTION) {
10957            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10958                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10959                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10960        }
10961
10962        // Push the derived path down into PackageSettings so we know what to
10963        // clean up at uninstall time.
10964        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10965
10966        if (DEBUG_ABI_SELECTION) {
10967            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10968                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10969                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10970        }
10971
10972        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10973        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10974            // We don't do this here during boot because we can do it all
10975            // at once after scanning all existing packages.
10976            //
10977            // We also do this *before* we perform dexopt on this package, so that
10978            // we can avoid redundant dexopts, and also to make sure we've got the
10979            // code and package path correct.
10980            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10981        }
10982
10983        if (mFactoryTest && pkg.requestedPermissions.contains(
10984                android.Manifest.permission.FACTORY_TEST)) {
10985            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10986        }
10987
10988        if (isSystemApp(pkg)) {
10989            pkgSetting.isOrphaned = true;
10990        }
10991
10992        // Take care of first install / last update times.
10993        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10994        if (currentTime != 0) {
10995            if (pkgSetting.firstInstallTime == 0) {
10996                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10997            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10998                pkgSetting.lastUpdateTime = currentTime;
10999            }
11000        } else if (pkgSetting.firstInstallTime == 0) {
11001            // We need *something*.  Take time time stamp of the file.
11002            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11003        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11004            if (scanFileTime != pkgSetting.timeStamp) {
11005                // A package on the system image has changed; consider this
11006                // to be an update.
11007                pkgSetting.lastUpdateTime = scanFileTime;
11008            }
11009        }
11010        pkgSetting.setTimeStamp(scanFileTime);
11011
11012        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11013            if (nonMutatedPs != null) {
11014                synchronized (mPackages) {
11015                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11016                }
11017            }
11018        } else {
11019            final int userId = user == null ? 0 : user.getIdentifier();
11020            // Modify state for the given package setting
11021            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11022                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11023            if (pkgSetting.getInstantApp(userId)) {
11024                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11025            }
11026        }
11027        return pkg;
11028    }
11029
11030    /**
11031     * Applies policy to the parsed package based upon the given policy flags.
11032     * Ensures the package is in a good state.
11033     * <p>
11034     * Implementation detail: This method must NOT have any side effect. It would
11035     * ideally be static, but, it requires locks to read system state.
11036     */
11037    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11038        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11039            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11040            if (pkg.applicationInfo.isDirectBootAware()) {
11041                // we're direct boot aware; set for all components
11042                for (PackageParser.Service s : pkg.services) {
11043                    s.info.encryptionAware = s.info.directBootAware = true;
11044                }
11045                for (PackageParser.Provider p : pkg.providers) {
11046                    p.info.encryptionAware = p.info.directBootAware = true;
11047                }
11048                for (PackageParser.Activity a : pkg.activities) {
11049                    a.info.encryptionAware = a.info.directBootAware = true;
11050                }
11051                for (PackageParser.Activity r : pkg.receivers) {
11052                    r.info.encryptionAware = r.info.directBootAware = true;
11053                }
11054            }
11055            if (compressedFileExists(pkg.codePath)) {
11056                pkg.isStub = true;
11057            }
11058        } else {
11059            // Only allow system apps to be flagged as core apps.
11060            pkg.coreApp = false;
11061            // clear flags not applicable to regular apps
11062            pkg.applicationInfo.privateFlags &=
11063                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11064            pkg.applicationInfo.privateFlags &=
11065                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11066        }
11067        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11068
11069        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11070            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11071        }
11072
11073        if (!isSystemApp(pkg)) {
11074            // Only system apps can use these features.
11075            pkg.mOriginalPackages = null;
11076            pkg.mRealPackage = null;
11077            pkg.mAdoptPermissions = null;
11078        }
11079    }
11080
11081    /**
11082     * Asserts the parsed package is valid according to the given policy. If the
11083     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11084     * <p>
11085     * Implementation detail: This method must NOT have any side effects. It would
11086     * ideally be static, but, it requires locks to read system state.
11087     *
11088     * @throws PackageManagerException If the package fails any of the validation checks
11089     */
11090    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11091            throws PackageManagerException {
11092        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11093            assertCodePolicy(pkg);
11094        }
11095
11096        if (pkg.applicationInfo.getCodePath() == null ||
11097                pkg.applicationInfo.getResourcePath() == null) {
11098            // Bail out. The resource and code paths haven't been set.
11099            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11100                    "Code and resource paths haven't been set correctly");
11101        }
11102
11103        // Make sure we're not adding any bogus keyset info
11104        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11105        ksms.assertScannedPackageValid(pkg);
11106
11107        synchronized (mPackages) {
11108            // The special "android" package can only be defined once
11109            if (pkg.packageName.equals("android")) {
11110                if (mAndroidApplication != null) {
11111                    Slog.w(TAG, "*************************************************");
11112                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11113                    Slog.w(TAG, " codePath=" + pkg.codePath);
11114                    Slog.w(TAG, "*************************************************");
11115                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11116                            "Core android package being redefined.  Skipping.");
11117                }
11118            }
11119
11120            // A package name must be unique; don't allow duplicates
11121            if (mPackages.containsKey(pkg.packageName)) {
11122                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11123                        "Application package " + pkg.packageName
11124                        + " already installed.  Skipping duplicate.");
11125            }
11126
11127            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11128                // Static libs have a synthetic package name containing the version
11129                // but we still want the base name to be unique.
11130                if (mPackages.containsKey(pkg.manifestPackageName)) {
11131                    throw new PackageManagerException(
11132                            "Duplicate static shared lib provider package");
11133                }
11134
11135                // Static shared libraries should have at least O target SDK
11136                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11137                    throw new PackageManagerException(
11138                            "Packages declaring static-shared libs must target O SDK or higher");
11139                }
11140
11141                // Package declaring static a shared lib cannot be instant apps
11142                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11143                    throw new PackageManagerException(
11144                            "Packages declaring static-shared libs cannot be instant apps");
11145                }
11146
11147                // Package declaring static a shared lib cannot be renamed since the package
11148                // name is synthetic and apps can't code around package manager internals.
11149                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11150                    throw new PackageManagerException(
11151                            "Packages declaring static-shared libs cannot be renamed");
11152                }
11153
11154                // Package declaring static a shared lib cannot declare child packages
11155                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11156                    throw new PackageManagerException(
11157                            "Packages declaring static-shared libs cannot have child packages");
11158                }
11159
11160                // Package declaring static a shared lib cannot declare dynamic libs
11161                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11162                    throw new PackageManagerException(
11163                            "Packages declaring static-shared libs cannot declare dynamic libs");
11164                }
11165
11166                // Package declaring static a shared lib cannot declare shared users
11167                if (pkg.mSharedUserId != null) {
11168                    throw new PackageManagerException(
11169                            "Packages declaring static-shared libs cannot declare shared users");
11170                }
11171
11172                // Static shared libs cannot declare activities
11173                if (!pkg.activities.isEmpty()) {
11174                    throw new PackageManagerException(
11175                            "Static shared libs cannot declare activities");
11176                }
11177
11178                // Static shared libs cannot declare services
11179                if (!pkg.services.isEmpty()) {
11180                    throw new PackageManagerException(
11181                            "Static shared libs cannot declare services");
11182                }
11183
11184                // Static shared libs cannot declare providers
11185                if (!pkg.providers.isEmpty()) {
11186                    throw new PackageManagerException(
11187                            "Static shared libs cannot declare content providers");
11188                }
11189
11190                // Static shared libs cannot declare receivers
11191                if (!pkg.receivers.isEmpty()) {
11192                    throw new PackageManagerException(
11193                            "Static shared libs cannot declare broadcast receivers");
11194                }
11195
11196                // Static shared libs cannot declare permission groups
11197                if (!pkg.permissionGroups.isEmpty()) {
11198                    throw new PackageManagerException(
11199                            "Static shared libs cannot declare permission groups");
11200                }
11201
11202                // Static shared libs cannot declare permissions
11203                if (!pkg.permissions.isEmpty()) {
11204                    throw new PackageManagerException(
11205                            "Static shared libs cannot declare permissions");
11206                }
11207
11208                // Static shared libs cannot declare protected broadcasts
11209                if (pkg.protectedBroadcasts != null) {
11210                    throw new PackageManagerException(
11211                            "Static shared libs cannot declare protected broadcasts");
11212                }
11213
11214                // Static shared libs cannot be overlay targets
11215                if (pkg.mOverlayTarget != null) {
11216                    throw new PackageManagerException(
11217                            "Static shared libs cannot be overlay targets");
11218                }
11219
11220                // The version codes must be ordered as lib versions
11221                int minVersionCode = Integer.MIN_VALUE;
11222                int maxVersionCode = Integer.MAX_VALUE;
11223
11224                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11225                        pkg.staticSharedLibName);
11226                if (versionedLib != null) {
11227                    final int versionCount = versionedLib.size();
11228                    for (int i = 0; i < versionCount; i++) {
11229                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11230                        final int libVersionCode = libInfo.getDeclaringPackage()
11231                                .getVersionCode();
11232                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11233                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11234                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11235                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11236                        } else {
11237                            minVersionCode = maxVersionCode = libVersionCode;
11238                            break;
11239                        }
11240                    }
11241                }
11242                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11243                    throw new PackageManagerException("Static shared"
11244                            + " lib version codes must be ordered as lib versions");
11245                }
11246            }
11247
11248            // Only privileged apps and updated privileged apps can add child packages.
11249            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11250                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11251                    throw new PackageManagerException("Only privileged apps can add child "
11252                            + "packages. Ignoring package " + pkg.packageName);
11253                }
11254                final int childCount = pkg.childPackages.size();
11255                for (int i = 0; i < childCount; i++) {
11256                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11257                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11258                            childPkg.packageName)) {
11259                        throw new PackageManagerException("Can't override child of "
11260                                + "another disabled app. Ignoring package " + pkg.packageName);
11261                    }
11262                }
11263            }
11264
11265            // If we're only installing presumed-existing packages, require that the
11266            // scanned APK is both already known and at the path previously established
11267            // for it.  Previously unknown packages we pick up normally, but if we have an
11268            // a priori expectation about this package's install presence, enforce it.
11269            // With a singular exception for new system packages. When an OTA contains
11270            // a new system package, we allow the codepath to change from a system location
11271            // to the user-installed location. If we don't allow this change, any newer,
11272            // user-installed version of the application will be ignored.
11273            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11274                if (mExpectingBetter.containsKey(pkg.packageName)) {
11275                    logCriticalInfo(Log.WARN,
11276                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11277                } else {
11278                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11279                    if (known != null) {
11280                        if (DEBUG_PACKAGE_SCANNING) {
11281                            Log.d(TAG, "Examining " + pkg.codePath
11282                                    + " and requiring known paths " + known.codePathString
11283                                    + " & " + known.resourcePathString);
11284                        }
11285                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11286                                || !pkg.applicationInfo.getResourcePath().equals(
11287                                        known.resourcePathString)) {
11288                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11289                                    "Application package " + pkg.packageName
11290                                    + " found at " + pkg.applicationInfo.getCodePath()
11291                                    + " but expected at " + known.codePathString
11292                                    + "; ignoring.");
11293                        }
11294                    }
11295                }
11296            }
11297
11298            // Verify that this new package doesn't have any content providers
11299            // that conflict with existing packages.  Only do this if the
11300            // package isn't already installed, since we don't want to break
11301            // things that are installed.
11302            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11303                final int N = pkg.providers.size();
11304                int i;
11305                for (i=0; i<N; i++) {
11306                    PackageParser.Provider p = pkg.providers.get(i);
11307                    if (p.info.authority != null) {
11308                        String names[] = p.info.authority.split(";");
11309                        for (int j = 0; j < names.length; j++) {
11310                            if (mProvidersByAuthority.containsKey(names[j])) {
11311                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11312                                final String otherPackageName =
11313                                        ((other != null && other.getComponentName() != null) ?
11314                                                other.getComponentName().getPackageName() : "?");
11315                                throw new PackageManagerException(
11316                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11317                                        "Can't install because provider name " + names[j]
11318                                                + " (in package " + pkg.applicationInfo.packageName
11319                                                + ") is already used by " + otherPackageName);
11320                            }
11321                        }
11322                    }
11323                }
11324            }
11325        }
11326    }
11327
11328    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11329            int type, String declaringPackageName, int declaringVersionCode) {
11330        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11331        if (versionedLib == null) {
11332            versionedLib = new SparseArray<>();
11333            mSharedLibraries.put(name, versionedLib);
11334            if (type == SharedLibraryInfo.TYPE_STATIC) {
11335                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11336            }
11337        } else if (versionedLib.indexOfKey(version) >= 0) {
11338            return false;
11339        }
11340        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11341                version, type, declaringPackageName, declaringVersionCode);
11342        versionedLib.put(version, libEntry);
11343        return true;
11344    }
11345
11346    private boolean removeSharedLibraryLPw(String name, int version) {
11347        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11348        if (versionedLib == null) {
11349            return false;
11350        }
11351        final int libIdx = versionedLib.indexOfKey(version);
11352        if (libIdx < 0) {
11353            return false;
11354        }
11355        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11356        versionedLib.remove(version);
11357        if (versionedLib.size() <= 0) {
11358            mSharedLibraries.remove(name);
11359            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11360                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11361                        .getPackageName());
11362            }
11363        }
11364        return true;
11365    }
11366
11367    /**
11368     * Adds a scanned package to the system. When this method is finished, the package will
11369     * be available for query, resolution, etc...
11370     */
11371    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11372            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11373        final String pkgName = pkg.packageName;
11374        if (mCustomResolverComponentName != null &&
11375                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11376            setUpCustomResolverActivity(pkg);
11377        }
11378
11379        if (pkg.packageName.equals("android")) {
11380            synchronized (mPackages) {
11381                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11382                    // Set up information for our fall-back user intent resolution activity.
11383                    mPlatformPackage = pkg;
11384                    pkg.mVersionCode = mSdkVersion;
11385                    mAndroidApplication = pkg.applicationInfo;
11386                    if (!mResolverReplaced) {
11387                        mResolveActivity.applicationInfo = mAndroidApplication;
11388                        mResolveActivity.name = ResolverActivity.class.getName();
11389                        mResolveActivity.packageName = mAndroidApplication.packageName;
11390                        mResolveActivity.processName = "system:ui";
11391                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11392                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11393                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11394                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11395                        mResolveActivity.exported = true;
11396                        mResolveActivity.enabled = true;
11397                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11398                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11399                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11400                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11401                                | ActivityInfo.CONFIG_ORIENTATION
11402                                | ActivityInfo.CONFIG_KEYBOARD
11403                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11404                        mResolveInfo.activityInfo = mResolveActivity;
11405                        mResolveInfo.priority = 0;
11406                        mResolveInfo.preferredOrder = 0;
11407                        mResolveInfo.match = 0;
11408                        mResolveComponentName = new ComponentName(
11409                                mAndroidApplication.packageName, mResolveActivity.name);
11410                    }
11411                }
11412            }
11413        }
11414
11415        ArrayList<PackageParser.Package> clientLibPkgs = null;
11416        // writer
11417        synchronized (mPackages) {
11418            boolean hasStaticSharedLibs = false;
11419
11420            // Any app can add new static shared libraries
11421            if (pkg.staticSharedLibName != null) {
11422                // Static shared libs don't allow renaming as they have synthetic package
11423                // names to allow install of multiple versions, so use name from manifest.
11424                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11425                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11426                        pkg.manifestPackageName, pkg.mVersionCode)) {
11427                    hasStaticSharedLibs = true;
11428                } else {
11429                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11430                                + pkg.staticSharedLibName + " already exists; skipping");
11431                }
11432                // Static shared libs cannot be updated once installed since they
11433                // use synthetic package name which includes the version code, so
11434                // not need to update other packages's shared lib dependencies.
11435            }
11436
11437            if (!hasStaticSharedLibs
11438                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11439                // Only system apps can add new dynamic shared libraries.
11440                if (pkg.libraryNames != null) {
11441                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11442                        String name = pkg.libraryNames.get(i);
11443                        boolean allowed = false;
11444                        if (pkg.isUpdatedSystemApp()) {
11445                            // New library entries can only be added through the
11446                            // system image.  This is important to get rid of a lot
11447                            // of nasty edge cases: for example if we allowed a non-
11448                            // system update of the app to add a library, then uninstalling
11449                            // the update would make the library go away, and assumptions
11450                            // we made such as through app install filtering would now
11451                            // have allowed apps on the device which aren't compatible
11452                            // with it.  Better to just have the restriction here, be
11453                            // conservative, and create many fewer cases that can negatively
11454                            // impact the user experience.
11455                            final PackageSetting sysPs = mSettings
11456                                    .getDisabledSystemPkgLPr(pkg.packageName);
11457                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11458                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11459                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11460                                        allowed = true;
11461                                        break;
11462                                    }
11463                                }
11464                            }
11465                        } else {
11466                            allowed = true;
11467                        }
11468                        if (allowed) {
11469                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11470                                    SharedLibraryInfo.VERSION_UNDEFINED,
11471                                    SharedLibraryInfo.TYPE_DYNAMIC,
11472                                    pkg.packageName, pkg.mVersionCode)) {
11473                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11474                                        + name + " already exists; skipping");
11475                            }
11476                        } else {
11477                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11478                                    + name + " that is not declared on system image; skipping");
11479                        }
11480                    }
11481
11482                    if ((scanFlags & SCAN_BOOTING) == 0) {
11483                        // If we are not booting, we need to update any applications
11484                        // that are clients of our shared library.  If we are booting,
11485                        // this will all be done once the scan is complete.
11486                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11487                    }
11488                }
11489            }
11490        }
11491
11492        if ((scanFlags & SCAN_BOOTING) != 0) {
11493            // No apps can run during boot scan, so they don't need to be frozen
11494        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11495            // Caller asked to not kill app, so it's probably not frozen
11496        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11497            // Caller asked us to ignore frozen check for some reason; they
11498            // probably didn't know the package name
11499        } else {
11500            // We're doing major surgery on this package, so it better be frozen
11501            // right now to keep it from launching
11502            checkPackageFrozen(pkgName);
11503        }
11504
11505        // Also need to kill any apps that are dependent on the library.
11506        if (clientLibPkgs != null) {
11507            for (int i=0; i<clientLibPkgs.size(); i++) {
11508                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11509                killApplication(clientPkg.applicationInfo.packageName,
11510                        clientPkg.applicationInfo.uid, "update lib");
11511            }
11512        }
11513
11514        // writer
11515        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11516
11517        synchronized (mPackages) {
11518            // We don't expect installation to fail beyond this point
11519
11520            // Add the new setting to mSettings
11521            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11522            // Add the new setting to mPackages
11523            mPackages.put(pkg.applicationInfo.packageName, pkg);
11524            // Make sure we don't accidentally delete its data.
11525            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11526            while (iter.hasNext()) {
11527                PackageCleanItem item = iter.next();
11528                if (pkgName.equals(item.packageName)) {
11529                    iter.remove();
11530                }
11531            }
11532
11533            // Add the package's KeySets to the global KeySetManagerService
11534            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11535            ksms.addScannedPackageLPw(pkg);
11536
11537            int N = pkg.providers.size();
11538            StringBuilder r = null;
11539            int i;
11540            for (i=0; i<N; i++) {
11541                PackageParser.Provider p = pkg.providers.get(i);
11542                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11543                        p.info.processName);
11544                mProviders.addProvider(p);
11545                p.syncable = p.info.isSyncable;
11546                if (p.info.authority != null) {
11547                    String names[] = p.info.authority.split(";");
11548                    p.info.authority = null;
11549                    for (int j = 0; j < names.length; j++) {
11550                        if (j == 1 && p.syncable) {
11551                            // We only want the first authority for a provider to possibly be
11552                            // syncable, so if we already added this provider using a different
11553                            // authority clear the syncable flag. We copy the provider before
11554                            // changing it because the mProviders object contains a reference
11555                            // to a provider that we don't want to change.
11556                            // Only do this for the second authority since the resulting provider
11557                            // object can be the same for all future authorities for this provider.
11558                            p = new PackageParser.Provider(p);
11559                            p.syncable = false;
11560                        }
11561                        if (!mProvidersByAuthority.containsKey(names[j])) {
11562                            mProvidersByAuthority.put(names[j], p);
11563                            if (p.info.authority == null) {
11564                                p.info.authority = names[j];
11565                            } else {
11566                                p.info.authority = p.info.authority + ";" + names[j];
11567                            }
11568                            if (DEBUG_PACKAGE_SCANNING) {
11569                                if (chatty)
11570                                    Log.d(TAG, "Registered content provider: " + names[j]
11571                                            + ", className = " + p.info.name + ", isSyncable = "
11572                                            + p.info.isSyncable);
11573                            }
11574                        } else {
11575                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11576                            Slog.w(TAG, "Skipping provider name " + names[j] +
11577                                    " (in package " + pkg.applicationInfo.packageName +
11578                                    "): name already used by "
11579                                    + ((other != null && other.getComponentName() != null)
11580                                            ? other.getComponentName().getPackageName() : "?"));
11581                        }
11582                    }
11583                }
11584                if (chatty) {
11585                    if (r == null) {
11586                        r = new StringBuilder(256);
11587                    } else {
11588                        r.append(' ');
11589                    }
11590                    r.append(p.info.name);
11591                }
11592            }
11593            if (r != null) {
11594                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11595            }
11596
11597            N = pkg.services.size();
11598            r = null;
11599            for (i=0; i<N; i++) {
11600                PackageParser.Service s = pkg.services.get(i);
11601                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11602                        s.info.processName);
11603                mServices.addService(s);
11604                if (chatty) {
11605                    if (r == null) {
11606                        r = new StringBuilder(256);
11607                    } else {
11608                        r.append(' ');
11609                    }
11610                    r.append(s.info.name);
11611                }
11612            }
11613            if (r != null) {
11614                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11615            }
11616
11617            N = pkg.receivers.size();
11618            r = null;
11619            for (i=0; i<N; i++) {
11620                PackageParser.Activity a = pkg.receivers.get(i);
11621                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11622                        a.info.processName);
11623                mReceivers.addActivity(a, "receiver");
11624                if (chatty) {
11625                    if (r == null) {
11626                        r = new StringBuilder(256);
11627                    } else {
11628                        r.append(' ');
11629                    }
11630                    r.append(a.info.name);
11631                }
11632            }
11633            if (r != null) {
11634                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11635            }
11636
11637            N = pkg.activities.size();
11638            r = null;
11639            for (i=0; i<N; i++) {
11640                PackageParser.Activity a = pkg.activities.get(i);
11641                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11642                        a.info.processName);
11643                mActivities.addActivity(a, "activity");
11644                if (chatty) {
11645                    if (r == null) {
11646                        r = new StringBuilder(256);
11647                    } else {
11648                        r.append(' ');
11649                    }
11650                    r.append(a.info.name);
11651                }
11652            }
11653            if (r != null) {
11654                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11655            }
11656
11657            N = pkg.permissionGroups.size();
11658            r = null;
11659            for (i=0; i<N; i++) {
11660                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11661                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11662                final String curPackageName = cur == null ? null : cur.info.packageName;
11663                // Dont allow ephemeral apps to define new permission groups.
11664                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11665                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11666                            + pg.info.packageName
11667                            + " ignored: instant apps cannot define new permission groups.");
11668                    continue;
11669                }
11670                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11671                if (cur == null || isPackageUpdate) {
11672                    mPermissionGroups.put(pg.info.name, pg);
11673                    if (chatty) {
11674                        if (r == null) {
11675                            r = new StringBuilder(256);
11676                        } else {
11677                            r.append(' ');
11678                        }
11679                        if (isPackageUpdate) {
11680                            r.append("UPD:");
11681                        }
11682                        r.append(pg.info.name);
11683                    }
11684                } else {
11685                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11686                            + pg.info.packageName + " ignored: original from "
11687                            + cur.info.packageName);
11688                    if (chatty) {
11689                        if (r == null) {
11690                            r = new StringBuilder(256);
11691                        } else {
11692                            r.append(' ');
11693                        }
11694                        r.append("DUP:");
11695                        r.append(pg.info.name);
11696                    }
11697                }
11698            }
11699            if (r != null) {
11700                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11701            }
11702
11703            N = pkg.permissions.size();
11704            r = null;
11705            for (i=0; i<N; i++) {
11706                PackageParser.Permission p = pkg.permissions.get(i);
11707
11708                // Dont allow ephemeral apps to define new permissions.
11709                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11710                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11711                            + p.info.packageName
11712                            + " ignored: instant apps cannot define new permissions.");
11713                    continue;
11714                }
11715
11716                // Assume by default that we did not install this permission into the system.
11717                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11718
11719                // Now that permission groups have a special meaning, we ignore permission
11720                // groups for legacy apps to prevent unexpected behavior. In particular,
11721                // permissions for one app being granted to someone just because they happen
11722                // to be in a group defined by another app (before this had no implications).
11723                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11724                    p.group = mPermissionGroups.get(p.info.group);
11725                    // Warn for a permission in an unknown group.
11726                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11727                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11728                                + p.info.packageName + " in an unknown group " + p.info.group);
11729                    }
11730                }
11731
11732                ArrayMap<String, BasePermission> permissionMap =
11733                        p.tree ? mSettings.mPermissionTrees
11734                                : mSettings.mPermissions;
11735                BasePermission bp = permissionMap.get(p.info.name);
11736
11737                // Allow system apps to redefine non-system permissions
11738                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11739                    final boolean currentOwnerIsSystem = (bp.perm != null
11740                            && isSystemApp(bp.perm.owner));
11741                    if (isSystemApp(p.owner)) {
11742                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11743                            // It's a built-in permission and no owner, take ownership now
11744                            bp.packageSetting = pkgSetting;
11745                            bp.perm = p;
11746                            bp.uid = pkg.applicationInfo.uid;
11747                            bp.sourcePackage = p.info.packageName;
11748                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11749                        } else if (!currentOwnerIsSystem) {
11750                            String msg = "New decl " + p.owner + " of permission  "
11751                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11752                            reportSettingsProblem(Log.WARN, msg);
11753                            bp = null;
11754                        }
11755                    }
11756                }
11757
11758                if (bp == null) {
11759                    bp = new BasePermission(p.info.name, p.info.packageName,
11760                            BasePermission.TYPE_NORMAL);
11761                    permissionMap.put(p.info.name, bp);
11762                }
11763
11764                if (bp.perm == null) {
11765                    if (bp.sourcePackage == null
11766                            || bp.sourcePackage.equals(p.info.packageName)) {
11767                        BasePermission tree = findPermissionTreeLP(p.info.name);
11768                        if (tree == null
11769                                || tree.sourcePackage.equals(p.info.packageName)) {
11770                            bp.packageSetting = pkgSetting;
11771                            bp.perm = p;
11772                            bp.uid = pkg.applicationInfo.uid;
11773                            bp.sourcePackage = p.info.packageName;
11774                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11775                            if (chatty) {
11776                                if (r == null) {
11777                                    r = new StringBuilder(256);
11778                                } else {
11779                                    r.append(' ');
11780                                }
11781                                r.append(p.info.name);
11782                            }
11783                        } else {
11784                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11785                                    + p.info.packageName + " ignored: base tree "
11786                                    + tree.name + " is from package "
11787                                    + tree.sourcePackage);
11788                        }
11789                    } else {
11790                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11791                                + p.info.packageName + " ignored: original from "
11792                                + bp.sourcePackage);
11793                    }
11794                } else if (chatty) {
11795                    if (r == null) {
11796                        r = new StringBuilder(256);
11797                    } else {
11798                        r.append(' ');
11799                    }
11800                    r.append("DUP:");
11801                    r.append(p.info.name);
11802                }
11803                if (bp.perm == p) {
11804                    bp.protectionLevel = p.info.protectionLevel;
11805                }
11806            }
11807
11808            if (r != null) {
11809                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11810            }
11811
11812            N = pkg.instrumentation.size();
11813            r = null;
11814            for (i=0; i<N; i++) {
11815                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11816                a.info.packageName = pkg.applicationInfo.packageName;
11817                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11818                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11819                a.info.splitNames = pkg.splitNames;
11820                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11821                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11822                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11823                a.info.dataDir = pkg.applicationInfo.dataDir;
11824                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11825                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11826                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11827                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11828                mInstrumentation.put(a.getComponentName(), a);
11829                if (chatty) {
11830                    if (r == null) {
11831                        r = new StringBuilder(256);
11832                    } else {
11833                        r.append(' ');
11834                    }
11835                    r.append(a.info.name);
11836                }
11837            }
11838            if (r != null) {
11839                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11840            }
11841
11842            if (pkg.protectedBroadcasts != null) {
11843                N = pkg.protectedBroadcasts.size();
11844                synchronized (mProtectedBroadcasts) {
11845                    for (i = 0; i < N; i++) {
11846                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11847                    }
11848                }
11849            }
11850        }
11851
11852        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11853    }
11854
11855    /**
11856     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11857     * is derived purely on the basis of the contents of {@code scanFile} and
11858     * {@code cpuAbiOverride}.
11859     *
11860     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11861     */
11862    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11863                                 String cpuAbiOverride, boolean extractLibs,
11864                                 File appLib32InstallDir)
11865            throws PackageManagerException {
11866        // Give ourselves some initial paths; we'll come back for another
11867        // pass once we've determined ABI below.
11868        setNativeLibraryPaths(pkg, appLib32InstallDir);
11869
11870        // We would never need to extract libs for forward-locked and external packages,
11871        // since the container service will do it for us. We shouldn't attempt to
11872        // extract libs from system app when it was not updated.
11873        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11874                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11875            extractLibs = false;
11876        }
11877
11878        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11879        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11880
11881        NativeLibraryHelper.Handle handle = null;
11882        try {
11883            handle = NativeLibraryHelper.Handle.create(pkg);
11884            // TODO(multiArch): This can be null for apps that didn't go through the
11885            // usual installation process. We can calculate it again, like we
11886            // do during install time.
11887            //
11888            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11889            // unnecessary.
11890            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11891
11892            // Null out the abis so that they can be recalculated.
11893            pkg.applicationInfo.primaryCpuAbi = null;
11894            pkg.applicationInfo.secondaryCpuAbi = null;
11895            if (isMultiArch(pkg.applicationInfo)) {
11896                // Warn if we've set an abiOverride for multi-lib packages..
11897                // By definition, we need to copy both 32 and 64 bit libraries for
11898                // such packages.
11899                if (pkg.cpuAbiOverride != null
11900                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11901                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11902                }
11903
11904                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11905                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11906                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11907                    if (extractLibs) {
11908                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11909                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11910                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11911                                useIsaSpecificSubdirs);
11912                    } else {
11913                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11914                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11915                    }
11916                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11917                }
11918
11919                // Shared library native code should be in the APK zip aligned
11920                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11921                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11922                            "Shared library native lib extraction not supported");
11923                }
11924
11925                maybeThrowExceptionForMultiArchCopy(
11926                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11927
11928                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11929                    if (extractLibs) {
11930                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11931                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11932                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11933                                useIsaSpecificSubdirs);
11934                    } else {
11935                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11936                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11937                    }
11938                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11939                }
11940
11941                maybeThrowExceptionForMultiArchCopy(
11942                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11943
11944                if (abi64 >= 0) {
11945                    // Shared library native libs should be in the APK zip aligned
11946                    if (extractLibs && pkg.isLibrary()) {
11947                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11948                                "Shared library native lib extraction not supported");
11949                    }
11950                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11951                }
11952
11953                if (abi32 >= 0) {
11954                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11955                    if (abi64 >= 0) {
11956                        if (pkg.use32bitAbi) {
11957                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11958                            pkg.applicationInfo.primaryCpuAbi = abi;
11959                        } else {
11960                            pkg.applicationInfo.secondaryCpuAbi = abi;
11961                        }
11962                    } else {
11963                        pkg.applicationInfo.primaryCpuAbi = abi;
11964                    }
11965                }
11966            } else {
11967                String[] abiList = (cpuAbiOverride != null) ?
11968                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11969
11970                // Enable gross and lame hacks for apps that are built with old
11971                // SDK tools. We must scan their APKs for renderscript bitcode and
11972                // not launch them if it's present. Don't bother checking on devices
11973                // that don't have 64 bit support.
11974                boolean needsRenderScriptOverride = false;
11975                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11976                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11977                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11978                    needsRenderScriptOverride = true;
11979                }
11980
11981                final int copyRet;
11982                if (extractLibs) {
11983                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11984                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11985                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11986                } else {
11987                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11988                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11989                }
11990                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11991
11992                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11993                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11994                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11995                }
11996
11997                if (copyRet >= 0) {
11998                    // Shared libraries that have native libs must be multi-architecture
11999                    if (pkg.isLibrary()) {
12000                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12001                                "Shared library with native libs must be multiarch");
12002                    }
12003                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12004                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12005                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12006                } else if (needsRenderScriptOverride) {
12007                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12008                }
12009            }
12010        } catch (IOException ioe) {
12011            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12012        } finally {
12013            IoUtils.closeQuietly(handle);
12014        }
12015
12016        // Now that we've calculated the ABIs and determined if it's an internal app,
12017        // we will go ahead and populate the nativeLibraryPath.
12018        setNativeLibraryPaths(pkg, appLib32InstallDir);
12019    }
12020
12021    /**
12022     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12023     * i.e, so that all packages can be run inside a single process if required.
12024     *
12025     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12026     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12027     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12028     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12029     * updating a package that belongs to a shared user.
12030     *
12031     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12032     * adds unnecessary complexity.
12033     */
12034    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12035            PackageParser.Package scannedPackage) {
12036        String requiredInstructionSet = null;
12037        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12038            requiredInstructionSet = VMRuntime.getInstructionSet(
12039                     scannedPackage.applicationInfo.primaryCpuAbi);
12040        }
12041
12042        PackageSetting requirer = null;
12043        for (PackageSetting ps : packagesForUser) {
12044            // If packagesForUser contains scannedPackage, we skip it. This will happen
12045            // when scannedPackage is an update of an existing package. Without this check,
12046            // we will never be able to change the ABI of any package belonging to a shared
12047            // user, even if it's compatible with other packages.
12048            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12049                if (ps.primaryCpuAbiString == null) {
12050                    continue;
12051                }
12052
12053                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12054                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12055                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12056                    // this but there's not much we can do.
12057                    String errorMessage = "Instruction set mismatch, "
12058                            + ((requirer == null) ? "[caller]" : requirer)
12059                            + " requires " + requiredInstructionSet + " whereas " + ps
12060                            + " requires " + instructionSet;
12061                    Slog.w(TAG, errorMessage);
12062                }
12063
12064                if (requiredInstructionSet == null) {
12065                    requiredInstructionSet = instructionSet;
12066                    requirer = ps;
12067                }
12068            }
12069        }
12070
12071        if (requiredInstructionSet != null) {
12072            String adjustedAbi;
12073            if (requirer != null) {
12074                // requirer != null implies that either scannedPackage was null or that scannedPackage
12075                // did not require an ABI, in which case we have to adjust scannedPackage to match
12076                // the ABI of the set (which is the same as requirer's ABI)
12077                adjustedAbi = requirer.primaryCpuAbiString;
12078                if (scannedPackage != null) {
12079                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12080                }
12081            } else {
12082                // requirer == null implies that we're updating all ABIs in the set to
12083                // match scannedPackage.
12084                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12085            }
12086
12087            for (PackageSetting ps : packagesForUser) {
12088                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12089                    if (ps.primaryCpuAbiString != null) {
12090                        continue;
12091                    }
12092
12093                    ps.primaryCpuAbiString = adjustedAbi;
12094                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12095                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12096                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12097                        if (DEBUG_ABI_SELECTION) {
12098                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12099                                    + " (requirer="
12100                                    + (requirer != null ? requirer.pkg : "null")
12101                                    + ", scannedPackage="
12102                                    + (scannedPackage != null ? scannedPackage : "null")
12103                                    + ")");
12104                        }
12105                        try {
12106                            mInstaller.rmdex(ps.codePathString,
12107                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12108                        } catch (InstallerException ignored) {
12109                        }
12110                    }
12111                }
12112            }
12113        }
12114    }
12115
12116    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12117        synchronized (mPackages) {
12118            mResolverReplaced = true;
12119            // Set up information for custom user intent resolution activity.
12120            mResolveActivity.applicationInfo = pkg.applicationInfo;
12121            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12122            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12123            mResolveActivity.processName = pkg.applicationInfo.packageName;
12124            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12125            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12126                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12127            mResolveActivity.theme = 0;
12128            mResolveActivity.exported = true;
12129            mResolveActivity.enabled = true;
12130            mResolveInfo.activityInfo = mResolveActivity;
12131            mResolveInfo.priority = 0;
12132            mResolveInfo.preferredOrder = 0;
12133            mResolveInfo.match = 0;
12134            mResolveComponentName = mCustomResolverComponentName;
12135            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12136                    mResolveComponentName);
12137        }
12138    }
12139
12140    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12141        if (installerActivity == null) {
12142            if (DEBUG_EPHEMERAL) {
12143                Slog.d(TAG, "Clear ephemeral installer activity");
12144            }
12145            mInstantAppInstallerActivity = null;
12146            return;
12147        }
12148
12149        if (DEBUG_EPHEMERAL) {
12150            Slog.d(TAG, "Set ephemeral installer activity: "
12151                    + installerActivity.getComponentName());
12152        }
12153        // Set up information for ephemeral installer activity
12154        mInstantAppInstallerActivity = installerActivity;
12155        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12156                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12157        mInstantAppInstallerActivity.exported = true;
12158        mInstantAppInstallerActivity.enabled = true;
12159        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12160        mInstantAppInstallerInfo.priority = 0;
12161        mInstantAppInstallerInfo.preferredOrder = 1;
12162        mInstantAppInstallerInfo.isDefault = true;
12163        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12164                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12165    }
12166
12167    private static String calculateBundledApkRoot(final String codePathString) {
12168        final File codePath = new File(codePathString);
12169        final File codeRoot;
12170        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12171            codeRoot = Environment.getRootDirectory();
12172        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12173            codeRoot = Environment.getOemDirectory();
12174        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12175            codeRoot = Environment.getVendorDirectory();
12176        } else {
12177            // Unrecognized code path; take its top real segment as the apk root:
12178            // e.g. /something/app/blah.apk => /something
12179            try {
12180                File f = codePath.getCanonicalFile();
12181                File parent = f.getParentFile();    // non-null because codePath is a file
12182                File tmp;
12183                while ((tmp = parent.getParentFile()) != null) {
12184                    f = parent;
12185                    parent = tmp;
12186                }
12187                codeRoot = f;
12188                Slog.w(TAG, "Unrecognized code path "
12189                        + codePath + " - using " + codeRoot);
12190            } catch (IOException e) {
12191                // Can't canonicalize the code path -- shenanigans?
12192                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12193                return Environment.getRootDirectory().getPath();
12194            }
12195        }
12196        return codeRoot.getPath();
12197    }
12198
12199    /**
12200     * Derive and set the location of native libraries for the given package,
12201     * which varies depending on where and how the package was installed.
12202     */
12203    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12204        final ApplicationInfo info = pkg.applicationInfo;
12205        final String codePath = pkg.codePath;
12206        final File codeFile = new File(codePath);
12207        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12208        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12209
12210        info.nativeLibraryRootDir = null;
12211        info.nativeLibraryRootRequiresIsa = false;
12212        info.nativeLibraryDir = null;
12213        info.secondaryNativeLibraryDir = null;
12214
12215        if (isApkFile(codeFile)) {
12216            // Monolithic install
12217            if (bundledApp) {
12218                // If "/system/lib64/apkname" exists, assume that is the per-package
12219                // native library directory to use; otherwise use "/system/lib/apkname".
12220                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12221                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12222                        getPrimaryInstructionSet(info));
12223
12224                // This is a bundled system app so choose the path based on the ABI.
12225                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12226                // is just the default path.
12227                final String apkName = deriveCodePathName(codePath);
12228                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12229                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12230                        apkName).getAbsolutePath();
12231
12232                if (info.secondaryCpuAbi != null) {
12233                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12234                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12235                            secondaryLibDir, apkName).getAbsolutePath();
12236                }
12237            } else if (asecApp) {
12238                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12239                        .getAbsolutePath();
12240            } else {
12241                final String apkName = deriveCodePathName(codePath);
12242                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12243                        .getAbsolutePath();
12244            }
12245
12246            info.nativeLibraryRootRequiresIsa = false;
12247            info.nativeLibraryDir = info.nativeLibraryRootDir;
12248        } else {
12249            // Cluster install
12250            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12251            info.nativeLibraryRootRequiresIsa = true;
12252
12253            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12254                    getPrimaryInstructionSet(info)).getAbsolutePath();
12255
12256            if (info.secondaryCpuAbi != null) {
12257                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12258                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12259            }
12260        }
12261    }
12262
12263    /**
12264     * Calculate the abis and roots for a bundled app. These can uniquely
12265     * be determined from the contents of the system partition, i.e whether
12266     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12267     * of this information, and instead assume that the system was built
12268     * sensibly.
12269     */
12270    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12271                                           PackageSetting pkgSetting) {
12272        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12273
12274        // If "/system/lib64/apkname" exists, assume that is the per-package
12275        // native library directory to use; otherwise use "/system/lib/apkname".
12276        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12277        setBundledAppAbi(pkg, apkRoot, apkName);
12278        // pkgSetting might be null during rescan following uninstall of updates
12279        // to a bundled app, so accommodate that possibility.  The settings in
12280        // that case will be established later from the parsed package.
12281        //
12282        // If the settings aren't null, sync them up with what we've just derived.
12283        // note that apkRoot isn't stored in the package settings.
12284        if (pkgSetting != null) {
12285            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12286            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12287        }
12288    }
12289
12290    /**
12291     * Deduces the ABI of a bundled app and sets the relevant fields on the
12292     * parsed pkg object.
12293     *
12294     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12295     *        under which system libraries are installed.
12296     * @param apkName the name of the installed package.
12297     */
12298    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12299        final File codeFile = new File(pkg.codePath);
12300
12301        final boolean has64BitLibs;
12302        final boolean has32BitLibs;
12303        if (isApkFile(codeFile)) {
12304            // Monolithic install
12305            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12306            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12307        } else {
12308            // Cluster install
12309            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12310            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12311                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12312                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12313                has64BitLibs = (new File(rootDir, isa)).exists();
12314            } else {
12315                has64BitLibs = false;
12316            }
12317            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12318                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12319                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12320                has32BitLibs = (new File(rootDir, isa)).exists();
12321            } else {
12322                has32BitLibs = false;
12323            }
12324        }
12325
12326        if (has64BitLibs && !has32BitLibs) {
12327            // The package has 64 bit libs, but not 32 bit libs. Its primary
12328            // ABI should be 64 bit. We can safely assume here that the bundled
12329            // native libraries correspond to the most preferred ABI in the list.
12330
12331            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12332            pkg.applicationInfo.secondaryCpuAbi = null;
12333        } else if (has32BitLibs && !has64BitLibs) {
12334            // The package has 32 bit libs but not 64 bit libs. Its primary
12335            // ABI should be 32 bit.
12336
12337            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12338            pkg.applicationInfo.secondaryCpuAbi = null;
12339        } else if (has32BitLibs && has64BitLibs) {
12340            // The application has both 64 and 32 bit bundled libraries. We check
12341            // here that the app declares multiArch support, and warn if it doesn't.
12342            //
12343            // We will be lenient here and record both ABIs. The primary will be the
12344            // ABI that's higher on the list, i.e, a device that's configured to prefer
12345            // 64 bit apps will see a 64 bit primary ABI,
12346
12347            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12348                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12349            }
12350
12351            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12352                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12353                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12354            } else {
12355                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12356                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12357            }
12358        } else {
12359            pkg.applicationInfo.primaryCpuAbi = null;
12360            pkg.applicationInfo.secondaryCpuAbi = null;
12361        }
12362    }
12363
12364    private void killApplication(String pkgName, int appId, String reason) {
12365        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12366    }
12367
12368    private void killApplication(String pkgName, int appId, int userId, String reason) {
12369        // Request the ActivityManager to kill the process(only for existing packages)
12370        // so that we do not end up in a confused state while the user is still using the older
12371        // version of the application while the new one gets installed.
12372        final long token = Binder.clearCallingIdentity();
12373        try {
12374            IActivityManager am = ActivityManager.getService();
12375            if (am != null) {
12376                try {
12377                    am.killApplication(pkgName, appId, userId, reason);
12378                } catch (RemoteException e) {
12379                }
12380            }
12381        } finally {
12382            Binder.restoreCallingIdentity(token);
12383        }
12384    }
12385
12386    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12387        // Remove the parent package setting
12388        PackageSetting ps = (PackageSetting) pkg.mExtras;
12389        if (ps != null) {
12390            removePackageLI(ps, chatty);
12391        }
12392        // Remove the child package setting
12393        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12394        for (int i = 0; i < childCount; i++) {
12395            PackageParser.Package childPkg = pkg.childPackages.get(i);
12396            ps = (PackageSetting) childPkg.mExtras;
12397            if (ps != null) {
12398                removePackageLI(ps, chatty);
12399            }
12400        }
12401    }
12402
12403    void removePackageLI(PackageSetting ps, boolean chatty) {
12404        if (DEBUG_INSTALL) {
12405            if (chatty)
12406                Log.d(TAG, "Removing package " + ps.name);
12407        }
12408
12409        // writer
12410        synchronized (mPackages) {
12411            mPackages.remove(ps.name);
12412            final PackageParser.Package pkg = ps.pkg;
12413            if (pkg != null) {
12414                cleanPackageDataStructuresLILPw(pkg, chatty);
12415            }
12416        }
12417    }
12418
12419    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12420        if (DEBUG_INSTALL) {
12421            if (chatty)
12422                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12423        }
12424
12425        // writer
12426        synchronized (mPackages) {
12427            // Remove the parent package
12428            mPackages.remove(pkg.applicationInfo.packageName);
12429            cleanPackageDataStructuresLILPw(pkg, chatty);
12430
12431            // Remove the child packages
12432            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12433            for (int i = 0; i < childCount; i++) {
12434                PackageParser.Package childPkg = pkg.childPackages.get(i);
12435                mPackages.remove(childPkg.applicationInfo.packageName);
12436                cleanPackageDataStructuresLILPw(childPkg, chatty);
12437            }
12438        }
12439    }
12440
12441    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12442        int N = pkg.providers.size();
12443        StringBuilder r = null;
12444        int i;
12445        for (i=0; i<N; i++) {
12446            PackageParser.Provider p = pkg.providers.get(i);
12447            mProviders.removeProvider(p);
12448            if (p.info.authority == null) {
12449
12450                /* There was another ContentProvider with this authority when
12451                 * this app was installed so this authority is null,
12452                 * Ignore it as we don't have to unregister the provider.
12453                 */
12454                continue;
12455            }
12456            String names[] = p.info.authority.split(";");
12457            for (int j = 0; j < names.length; j++) {
12458                if (mProvidersByAuthority.get(names[j]) == p) {
12459                    mProvidersByAuthority.remove(names[j]);
12460                    if (DEBUG_REMOVE) {
12461                        if (chatty)
12462                            Log.d(TAG, "Unregistered content provider: " + names[j]
12463                                    + ", className = " + p.info.name + ", isSyncable = "
12464                                    + p.info.isSyncable);
12465                    }
12466                }
12467            }
12468            if (DEBUG_REMOVE && chatty) {
12469                if (r == null) {
12470                    r = new StringBuilder(256);
12471                } else {
12472                    r.append(' ');
12473                }
12474                r.append(p.info.name);
12475            }
12476        }
12477        if (r != null) {
12478            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12479        }
12480
12481        N = pkg.services.size();
12482        r = null;
12483        for (i=0; i<N; i++) {
12484            PackageParser.Service s = pkg.services.get(i);
12485            mServices.removeService(s);
12486            if (chatty) {
12487                if (r == null) {
12488                    r = new StringBuilder(256);
12489                } else {
12490                    r.append(' ');
12491                }
12492                r.append(s.info.name);
12493            }
12494        }
12495        if (r != null) {
12496            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12497        }
12498
12499        N = pkg.receivers.size();
12500        r = null;
12501        for (i=0; i<N; i++) {
12502            PackageParser.Activity a = pkg.receivers.get(i);
12503            mReceivers.removeActivity(a, "receiver");
12504            if (DEBUG_REMOVE && chatty) {
12505                if (r == null) {
12506                    r = new StringBuilder(256);
12507                } else {
12508                    r.append(' ');
12509                }
12510                r.append(a.info.name);
12511            }
12512        }
12513        if (r != null) {
12514            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12515        }
12516
12517        N = pkg.activities.size();
12518        r = null;
12519        for (i=0; i<N; i++) {
12520            PackageParser.Activity a = pkg.activities.get(i);
12521            mActivities.removeActivity(a, "activity");
12522            if (DEBUG_REMOVE && chatty) {
12523                if (r == null) {
12524                    r = new StringBuilder(256);
12525                } else {
12526                    r.append(' ');
12527                }
12528                r.append(a.info.name);
12529            }
12530        }
12531        if (r != null) {
12532            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12533        }
12534
12535        N = pkg.permissions.size();
12536        r = null;
12537        for (i=0; i<N; i++) {
12538            PackageParser.Permission p = pkg.permissions.get(i);
12539            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12540            if (bp == null) {
12541                bp = mSettings.mPermissionTrees.get(p.info.name);
12542            }
12543            if (bp != null && bp.perm == p) {
12544                bp.perm = null;
12545                if (DEBUG_REMOVE && chatty) {
12546                    if (r == null) {
12547                        r = new StringBuilder(256);
12548                    } else {
12549                        r.append(' ');
12550                    }
12551                    r.append(p.info.name);
12552                }
12553            }
12554            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12555                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12556                if (appOpPkgs != null) {
12557                    appOpPkgs.remove(pkg.packageName);
12558                }
12559            }
12560        }
12561        if (r != null) {
12562            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12563        }
12564
12565        N = pkg.requestedPermissions.size();
12566        r = null;
12567        for (i=0; i<N; i++) {
12568            String perm = pkg.requestedPermissions.get(i);
12569            BasePermission bp = mSettings.mPermissions.get(perm);
12570            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12571                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12572                if (appOpPkgs != null) {
12573                    appOpPkgs.remove(pkg.packageName);
12574                    if (appOpPkgs.isEmpty()) {
12575                        mAppOpPermissionPackages.remove(perm);
12576                    }
12577                }
12578            }
12579        }
12580        if (r != null) {
12581            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12582        }
12583
12584        N = pkg.instrumentation.size();
12585        r = null;
12586        for (i=0; i<N; i++) {
12587            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12588            mInstrumentation.remove(a.getComponentName());
12589            if (DEBUG_REMOVE && chatty) {
12590                if (r == null) {
12591                    r = new StringBuilder(256);
12592                } else {
12593                    r.append(' ');
12594                }
12595                r.append(a.info.name);
12596            }
12597        }
12598        if (r != null) {
12599            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12600        }
12601
12602        r = null;
12603        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12604            // Only system apps can hold shared libraries.
12605            if (pkg.libraryNames != null) {
12606                for (i = 0; i < pkg.libraryNames.size(); i++) {
12607                    String name = pkg.libraryNames.get(i);
12608                    if (removeSharedLibraryLPw(name, 0)) {
12609                        if (DEBUG_REMOVE && chatty) {
12610                            if (r == null) {
12611                                r = new StringBuilder(256);
12612                            } else {
12613                                r.append(' ');
12614                            }
12615                            r.append(name);
12616                        }
12617                    }
12618                }
12619            }
12620        }
12621
12622        r = null;
12623
12624        // Any package can hold static shared libraries.
12625        if (pkg.staticSharedLibName != null) {
12626            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12627                if (DEBUG_REMOVE && chatty) {
12628                    if (r == null) {
12629                        r = new StringBuilder(256);
12630                    } else {
12631                        r.append(' ');
12632                    }
12633                    r.append(pkg.staticSharedLibName);
12634                }
12635            }
12636        }
12637
12638        if (r != null) {
12639            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12640        }
12641    }
12642
12643    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12644        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12645            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12646                return true;
12647            }
12648        }
12649        return false;
12650    }
12651
12652    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12653    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12654    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12655
12656    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12657        // Update the parent permissions
12658        updatePermissionsLPw(pkg.packageName, pkg, flags);
12659        // Update the child permissions
12660        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12661        for (int i = 0; i < childCount; i++) {
12662            PackageParser.Package childPkg = pkg.childPackages.get(i);
12663            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12664        }
12665    }
12666
12667    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12668            int flags) {
12669        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12670        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12671    }
12672
12673    private void updatePermissionsLPw(String changingPkg,
12674            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12675        // Make sure there are no dangling permission trees.
12676        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12677        while (it.hasNext()) {
12678            final BasePermission bp = it.next();
12679            if (bp.packageSetting == null) {
12680                // We may not yet have parsed the package, so just see if
12681                // we still know about its settings.
12682                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12683            }
12684            if (bp.packageSetting == null) {
12685                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12686                        + " from package " + bp.sourcePackage);
12687                it.remove();
12688            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12689                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12690                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12691                            + " from package " + bp.sourcePackage);
12692                    flags |= UPDATE_PERMISSIONS_ALL;
12693                    it.remove();
12694                }
12695            }
12696        }
12697
12698        // Make sure all dynamic permissions have been assigned to a package,
12699        // and make sure there are no dangling permissions.
12700        it = mSettings.mPermissions.values().iterator();
12701        while (it.hasNext()) {
12702            final BasePermission bp = it.next();
12703            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12704                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12705                        + bp.name + " pkg=" + bp.sourcePackage
12706                        + " info=" + bp.pendingInfo);
12707                if (bp.packageSetting == null && bp.pendingInfo != null) {
12708                    final BasePermission tree = findPermissionTreeLP(bp.name);
12709                    if (tree != null && tree.perm != null) {
12710                        bp.packageSetting = tree.packageSetting;
12711                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12712                                new PermissionInfo(bp.pendingInfo));
12713                        bp.perm.info.packageName = tree.perm.info.packageName;
12714                        bp.perm.info.name = bp.name;
12715                        bp.uid = tree.uid;
12716                    }
12717                }
12718            }
12719            if (bp.packageSetting == null) {
12720                // We may not yet have parsed the package, so just see if
12721                // we still know about its settings.
12722                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12723            }
12724            if (bp.packageSetting == null) {
12725                Slog.w(TAG, "Removing dangling permission: " + bp.name
12726                        + " from package " + bp.sourcePackage);
12727                it.remove();
12728            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12729                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12730                    Slog.i(TAG, "Removing old permission: " + bp.name
12731                            + " from package " + bp.sourcePackage);
12732                    flags |= UPDATE_PERMISSIONS_ALL;
12733                    it.remove();
12734                }
12735            }
12736        }
12737
12738        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12739        // Now update the permissions for all packages, in particular
12740        // replace the granted permissions of the system packages.
12741        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12742            for (PackageParser.Package pkg : mPackages.values()) {
12743                if (pkg != pkgInfo) {
12744                    // Only replace for packages on requested volume
12745                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12746                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12747                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12748                    grantPermissionsLPw(pkg, replace, changingPkg);
12749                }
12750            }
12751        }
12752
12753        if (pkgInfo != null) {
12754            // Only replace for packages on requested volume
12755            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12756            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12757                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12758            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12759        }
12760        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12761    }
12762
12763    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12764            String packageOfInterest) {
12765        // IMPORTANT: There are two types of permissions: install and runtime.
12766        // Install time permissions are granted when the app is installed to
12767        // all device users and users added in the future. Runtime permissions
12768        // are granted at runtime explicitly to specific users. Normal and signature
12769        // protected permissions are install time permissions. Dangerous permissions
12770        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12771        // otherwise they are runtime permissions. This function does not manage
12772        // runtime permissions except for the case an app targeting Lollipop MR1
12773        // being upgraded to target a newer SDK, in which case dangerous permissions
12774        // are transformed from install time to runtime ones.
12775
12776        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12777        if (ps == null) {
12778            return;
12779        }
12780
12781        PermissionsState permissionsState = ps.getPermissionsState();
12782        PermissionsState origPermissions = permissionsState;
12783
12784        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12785
12786        boolean runtimePermissionsRevoked = false;
12787        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12788
12789        boolean changedInstallPermission = false;
12790
12791        if (replace) {
12792            ps.installPermissionsFixed = false;
12793            if (!ps.isSharedUser()) {
12794                origPermissions = new PermissionsState(permissionsState);
12795                permissionsState.reset();
12796            } else {
12797                // We need to know only about runtime permission changes since the
12798                // calling code always writes the install permissions state but
12799                // the runtime ones are written only if changed. The only cases of
12800                // changed runtime permissions here are promotion of an install to
12801                // runtime and revocation of a runtime from a shared user.
12802                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12803                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12804                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12805                    runtimePermissionsRevoked = true;
12806                }
12807            }
12808        }
12809
12810        permissionsState.setGlobalGids(mGlobalGids);
12811
12812        final int N = pkg.requestedPermissions.size();
12813        for (int i=0; i<N; i++) {
12814            final String name = pkg.requestedPermissions.get(i);
12815            final BasePermission bp = mSettings.mPermissions.get(name);
12816            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12817                    >= Build.VERSION_CODES.M;
12818
12819            if (DEBUG_INSTALL) {
12820                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12821            }
12822
12823            if (bp == null || bp.packageSetting == null) {
12824                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12825                    if (DEBUG_PERMISSIONS) {
12826                        Slog.i(TAG, "Unknown permission " + name
12827                                + " in package " + pkg.packageName);
12828                    }
12829                }
12830                continue;
12831            }
12832
12833
12834            // Limit ephemeral apps to ephemeral allowed permissions.
12835            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12836                if (DEBUG_PERMISSIONS) {
12837                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12838                            + pkg.packageName);
12839                }
12840                continue;
12841            }
12842
12843            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12844                if (DEBUG_PERMISSIONS) {
12845                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12846                            + pkg.packageName);
12847                }
12848                continue;
12849            }
12850
12851            final String perm = bp.name;
12852            boolean allowedSig = false;
12853            int grant = GRANT_DENIED;
12854
12855            // Keep track of app op permissions.
12856            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12857                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12858                if (pkgs == null) {
12859                    pkgs = new ArraySet<>();
12860                    mAppOpPermissionPackages.put(bp.name, pkgs);
12861                }
12862                pkgs.add(pkg.packageName);
12863            }
12864
12865            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12866            switch (level) {
12867                case PermissionInfo.PROTECTION_NORMAL: {
12868                    // For all apps normal permissions are install time ones.
12869                    grant = GRANT_INSTALL;
12870                } break;
12871
12872                case PermissionInfo.PROTECTION_DANGEROUS: {
12873                    // If a permission review is required for legacy apps we represent
12874                    // their permissions as always granted runtime ones since we need
12875                    // to keep the review required permission flag per user while an
12876                    // install permission's state is shared across all users.
12877                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12878                        // For legacy apps dangerous permissions are install time ones.
12879                        grant = GRANT_INSTALL;
12880                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12881                        // For legacy apps that became modern, install becomes runtime.
12882                        grant = GRANT_UPGRADE;
12883                    } else if (mPromoteSystemApps
12884                            && isSystemApp(ps)
12885                            && mExistingSystemPackages.contains(ps.name)) {
12886                        // For legacy system apps, install becomes runtime.
12887                        // We cannot check hasInstallPermission() for system apps since those
12888                        // permissions were granted implicitly and not persisted pre-M.
12889                        grant = GRANT_UPGRADE;
12890                    } else {
12891                        // For modern apps keep runtime permissions unchanged.
12892                        grant = GRANT_RUNTIME;
12893                    }
12894                } break;
12895
12896                case PermissionInfo.PROTECTION_SIGNATURE: {
12897                    // For all apps signature permissions are install time ones.
12898                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12899                    if (allowedSig) {
12900                        grant = GRANT_INSTALL;
12901                    }
12902                } break;
12903            }
12904
12905            if (DEBUG_PERMISSIONS) {
12906                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12907            }
12908
12909            if (grant != GRANT_DENIED) {
12910                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12911                    // If this is an existing, non-system package, then
12912                    // we can't add any new permissions to it.
12913                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12914                        // Except...  if this is a permission that was added
12915                        // to the platform (note: need to only do this when
12916                        // updating the platform).
12917                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12918                            grant = GRANT_DENIED;
12919                        }
12920                    }
12921                }
12922
12923                switch (grant) {
12924                    case GRANT_INSTALL: {
12925                        // Revoke this as runtime permission to handle the case of
12926                        // a runtime permission being downgraded to an install one.
12927                        // Also in permission review mode we keep dangerous permissions
12928                        // for legacy apps
12929                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12930                            if (origPermissions.getRuntimePermissionState(
12931                                    bp.name, userId) != null) {
12932                                // Revoke the runtime permission and clear the flags.
12933                                origPermissions.revokeRuntimePermission(bp, userId);
12934                                origPermissions.updatePermissionFlags(bp, userId,
12935                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12936                                // If we revoked a permission permission, we have to write.
12937                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12938                                        changedRuntimePermissionUserIds, userId);
12939                            }
12940                        }
12941                        // Grant an install permission.
12942                        if (permissionsState.grantInstallPermission(bp) !=
12943                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12944                            changedInstallPermission = true;
12945                        }
12946                    } break;
12947
12948                    case GRANT_RUNTIME: {
12949                        // Grant previously granted runtime permissions.
12950                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12951                            PermissionState permissionState = origPermissions
12952                                    .getRuntimePermissionState(bp.name, userId);
12953                            int flags = permissionState != null
12954                                    ? permissionState.getFlags() : 0;
12955                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12956                                // Don't propagate the permission in a permission review mode if
12957                                // the former was revoked, i.e. marked to not propagate on upgrade.
12958                                // Note that in a permission review mode install permissions are
12959                                // represented as constantly granted runtime ones since we need to
12960                                // keep a per user state associated with the permission. Also the
12961                                // revoke on upgrade flag is no longer applicable and is reset.
12962                                final boolean revokeOnUpgrade = (flags & PackageManager
12963                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12964                                if (revokeOnUpgrade) {
12965                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12966                                    // Since we changed the flags, we have to write.
12967                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12968                                            changedRuntimePermissionUserIds, userId);
12969                                }
12970                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12971                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12972                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12973                                        // If we cannot put the permission as it was,
12974                                        // we have to write.
12975                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12976                                                changedRuntimePermissionUserIds, userId);
12977                                    }
12978                                }
12979
12980                                // If the app supports runtime permissions no need for a review.
12981                                if (mPermissionReviewRequired
12982                                        && appSupportsRuntimePermissions
12983                                        && (flags & PackageManager
12984                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12985                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12986                                    // Since we changed the flags, we have to write.
12987                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12988                                            changedRuntimePermissionUserIds, userId);
12989                                }
12990                            } else if (mPermissionReviewRequired
12991                                    && !appSupportsRuntimePermissions) {
12992                                // For legacy apps that need a permission review, every new
12993                                // runtime permission is granted but it is pending a review.
12994                                // We also need to review only platform defined runtime
12995                                // permissions as these are the only ones the platform knows
12996                                // how to disable the API to simulate revocation as legacy
12997                                // apps don't expect to run with revoked permissions.
12998                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12999                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13000                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13001                                        // We changed the flags, hence have to write.
13002                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13003                                                changedRuntimePermissionUserIds, userId);
13004                                    }
13005                                }
13006                                if (permissionsState.grantRuntimePermission(bp, userId)
13007                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13008                                    // We changed the permission, hence have to write.
13009                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13010                                            changedRuntimePermissionUserIds, userId);
13011                                }
13012                            }
13013                            // Propagate the permission flags.
13014                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13015                        }
13016                    } break;
13017
13018                    case GRANT_UPGRADE: {
13019                        // Grant runtime permissions for a previously held install permission.
13020                        PermissionState permissionState = origPermissions
13021                                .getInstallPermissionState(bp.name);
13022                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13023
13024                        if (origPermissions.revokeInstallPermission(bp)
13025                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13026                            // We will be transferring the permission flags, so clear them.
13027                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13028                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13029                            changedInstallPermission = true;
13030                        }
13031
13032                        // If the permission is not to be promoted to runtime we ignore it and
13033                        // also its other flags as they are not applicable to install permissions.
13034                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13035                            for (int userId : currentUserIds) {
13036                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13037                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13038                                    // Transfer the permission flags.
13039                                    permissionsState.updatePermissionFlags(bp, userId,
13040                                            flags, flags);
13041                                    // If we granted the permission, we have to write.
13042                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13043                                            changedRuntimePermissionUserIds, userId);
13044                                }
13045                            }
13046                        }
13047                    } break;
13048
13049                    default: {
13050                        if (packageOfInterest == null
13051                                || packageOfInterest.equals(pkg.packageName)) {
13052                            if (DEBUG_PERMISSIONS) {
13053                                Slog.i(TAG, "Not granting permission " + perm
13054                                        + " to package " + pkg.packageName
13055                                        + " because it was previously installed without");
13056                            }
13057                        }
13058                    } break;
13059                }
13060            } else {
13061                if (permissionsState.revokeInstallPermission(bp) !=
13062                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13063                    // Also drop the permission flags.
13064                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13065                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13066                    changedInstallPermission = true;
13067                    Slog.i(TAG, "Un-granting permission " + perm
13068                            + " from package " + pkg.packageName
13069                            + " (protectionLevel=" + bp.protectionLevel
13070                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13071                            + ")");
13072                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13073                    // Don't print warning for app op permissions, since it is fine for them
13074                    // not to be granted, there is a UI for the user to decide.
13075                    if (DEBUG_PERMISSIONS
13076                            && (packageOfInterest == null
13077                                    || packageOfInterest.equals(pkg.packageName))) {
13078                        Slog.i(TAG, "Not granting permission " + perm
13079                                + " to package " + pkg.packageName
13080                                + " (protectionLevel=" + bp.protectionLevel
13081                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13082                                + ")");
13083                    }
13084                }
13085            }
13086        }
13087
13088        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13089                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13090            // This is the first that we have heard about this package, so the
13091            // permissions we have now selected are fixed until explicitly
13092            // changed.
13093            ps.installPermissionsFixed = true;
13094        }
13095
13096        // Persist the runtime permissions state for users with changes. If permissions
13097        // were revoked because no app in the shared user declares them we have to
13098        // write synchronously to avoid losing runtime permissions state.
13099        for (int userId : changedRuntimePermissionUserIds) {
13100            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13101        }
13102    }
13103
13104    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13105        boolean allowed = false;
13106        final int NP = PackageParser.NEW_PERMISSIONS.length;
13107        for (int ip=0; ip<NP; ip++) {
13108            final PackageParser.NewPermissionInfo npi
13109                    = PackageParser.NEW_PERMISSIONS[ip];
13110            if (npi.name.equals(perm)
13111                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13112                allowed = true;
13113                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13114                        + pkg.packageName);
13115                break;
13116            }
13117        }
13118        return allowed;
13119    }
13120
13121    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13122            BasePermission bp, PermissionsState origPermissions) {
13123        boolean privilegedPermission = (bp.protectionLevel
13124                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13125        boolean privappPermissionsDisable =
13126                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13127        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13128        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13129        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13130                && !platformPackage && platformPermission) {
13131            ArraySet<String> wlPermissions = SystemConfig.getInstance()
13132                    .getPrivAppPermissions(pkg.packageName);
13133            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13134            if (!whitelisted) {
13135                Slog.w(TAG, "Privileged permission " + perm + " for package "
13136                        + pkg.packageName + " - not in privapp-permissions whitelist");
13137                // Only report violations for apps on system image
13138                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13139                    if (mPrivappPermissionsViolations == null) {
13140                        mPrivappPermissionsViolations = new ArraySet<>();
13141                    }
13142                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13143                }
13144                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13145                    return false;
13146                }
13147            }
13148        }
13149        boolean allowed = (compareSignatures(
13150                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13151                        == PackageManager.SIGNATURE_MATCH)
13152                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13153                        == PackageManager.SIGNATURE_MATCH);
13154        if (!allowed && privilegedPermission) {
13155            if (isSystemApp(pkg)) {
13156                // For updated system applications, a system permission
13157                // is granted only if it had been defined by the original application.
13158                if (pkg.isUpdatedSystemApp()) {
13159                    final PackageSetting sysPs = mSettings
13160                            .getDisabledSystemPkgLPr(pkg.packageName);
13161                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13162                        // If the original was granted this permission, we take
13163                        // that grant decision as read and propagate it to the
13164                        // update.
13165                        if (sysPs.isPrivileged()) {
13166                            allowed = true;
13167                        }
13168                    } else {
13169                        // The system apk may have been updated with an older
13170                        // version of the one on the data partition, but which
13171                        // granted a new system permission that it didn't have
13172                        // before.  In this case we do want to allow the app to
13173                        // now get the new permission if the ancestral apk is
13174                        // privileged to get it.
13175                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13176                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13177                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13178                                    allowed = true;
13179                                    break;
13180                                }
13181                            }
13182                        }
13183                        // Also if a privileged parent package on the system image or any of
13184                        // its children requested a privileged permission, the updated child
13185                        // packages can also get the permission.
13186                        if (pkg.parentPackage != null) {
13187                            final PackageSetting disabledSysParentPs = mSettings
13188                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13189                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13190                                    && disabledSysParentPs.isPrivileged()) {
13191                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13192                                    allowed = true;
13193                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13194                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13195                                    for (int i = 0; i < count; i++) {
13196                                        PackageParser.Package disabledSysChildPkg =
13197                                                disabledSysParentPs.pkg.childPackages.get(i);
13198                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13199                                                perm)) {
13200                                            allowed = true;
13201                                            break;
13202                                        }
13203                                    }
13204                                }
13205                            }
13206                        }
13207                    }
13208                } else {
13209                    allowed = isPrivilegedApp(pkg);
13210                }
13211            }
13212        }
13213        if (!allowed) {
13214            if (!allowed && (bp.protectionLevel
13215                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13216                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13217                // If this was a previously normal/dangerous permission that got moved
13218                // to a system permission as part of the runtime permission redesign, then
13219                // we still want to blindly grant it to old apps.
13220                allowed = true;
13221            }
13222            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13223                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13224                // If this permission is to be granted to the system installer and
13225                // this app is an installer, then it gets the permission.
13226                allowed = true;
13227            }
13228            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13229                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13230                // If this permission is to be granted to the system verifier and
13231                // this app is a verifier, then it gets the permission.
13232                allowed = true;
13233            }
13234            if (!allowed && (bp.protectionLevel
13235                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13236                    && isSystemApp(pkg)) {
13237                // Any pre-installed system app is allowed to get this permission.
13238                allowed = true;
13239            }
13240            if (!allowed && (bp.protectionLevel
13241                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13242                // For development permissions, a development permission
13243                // is granted only if it was already granted.
13244                allowed = origPermissions.hasInstallPermission(perm);
13245            }
13246            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13247                    && pkg.packageName.equals(mSetupWizardPackage)) {
13248                // If this permission is to be granted to the system setup wizard and
13249                // this app is a setup wizard, then it gets the permission.
13250                allowed = true;
13251            }
13252        }
13253        return allowed;
13254    }
13255
13256    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13257        final int permCount = pkg.requestedPermissions.size();
13258        for (int j = 0; j < permCount; j++) {
13259            String requestedPermission = pkg.requestedPermissions.get(j);
13260            if (permission.equals(requestedPermission)) {
13261                return true;
13262            }
13263        }
13264        return false;
13265    }
13266
13267    final class ActivityIntentResolver
13268            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13269        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13270                boolean defaultOnly, int userId) {
13271            if (!sUserManager.exists(userId)) return null;
13272            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13273            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13274        }
13275
13276        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13277                int userId) {
13278            if (!sUserManager.exists(userId)) return null;
13279            mFlags = flags;
13280            return super.queryIntent(intent, resolvedType,
13281                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13282                    userId);
13283        }
13284
13285        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13286                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13287            if (!sUserManager.exists(userId)) return null;
13288            if (packageActivities == null) {
13289                return null;
13290            }
13291            mFlags = flags;
13292            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13293            final int N = packageActivities.size();
13294            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13295                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13296
13297            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13298            for (int i = 0; i < N; ++i) {
13299                intentFilters = packageActivities.get(i).intents;
13300                if (intentFilters != null && intentFilters.size() > 0) {
13301                    PackageParser.ActivityIntentInfo[] array =
13302                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13303                    intentFilters.toArray(array);
13304                    listCut.add(array);
13305                }
13306            }
13307            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13308        }
13309
13310        /**
13311         * Finds a privileged activity that matches the specified activity names.
13312         */
13313        private PackageParser.Activity findMatchingActivity(
13314                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13315            for (PackageParser.Activity sysActivity : activityList) {
13316                if (sysActivity.info.name.equals(activityInfo.name)) {
13317                    return sysActivity;
13318                }
13319                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13320                    return sysActivity;
13321                }
13322                if (sysActivity.info.targetActivity != null) {
13323                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13324                        return sysActivity;
13325                    }
13326                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13327                        return sysActivity;
13328                    }
13329                }
13330            }
13331            return null;
13332        }
13333
13334        public class IterGenerator<E> {
13335            public Iterator<E> generate(ActivityIntentInfo info) {
13336                return null;
13337            }
13338        }
13339
13340        public class ActionIterGenerator extends IterGenerator<String> {
13341            @Override
13342            public Iterator<String> generate(ActivityIntentInfo info) {
13343                return info.actionsIterator();
13344            }
13345        }
13346
13347        public class CategoriesIterGenerator extends IterGenerator<String> {
13348            @Override
13349            public Iterator<String> generate(ActivityIntentInfo info) {
13350                return info.categoriesIterator();
13351            }
13352        }
13353
13354        public class SchemesIterGenerator extends IterGenerator<String> {
13355            @Override
13356            public Iterator<String> generate(ActivityIntentInfo info) {
13357                return info.schemesIterator();
13358            }
13359        }
13360
13361        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13362            @Override
13363            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13364                return info.authoritiesIterator();
13365            }
13366        }
13367
13368        /**
13369         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13370         * MODIFIED. Do not pass in a list that should not be changed.
13371         */
13372        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13373                IterGenerator<T> generator, Iterator<T> searchIterator) {
13374            // loop through the set of actions; every one must be found in the intent filter
13375            while (searchIterator.hasNext()) {
13376                // we must have at least one filter in the list to consider a match
13377                if (intentList.size() == 0) {
13378                    break;
13379                }
13380
13381                final T searchAction = searchIterator.next();
13382
13383                // loop through the set of intent filters
13384                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13385                while (intentIter.hasNext()) {
13386                    final ActivityIntentInfo intentInfo = intentIter.next();
13387                    boolean selectionFound = false;
13388
13389                    // loop through the intent filter's selection criteria; at least one
13390                    // of them must match the searched criteria
13391                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13392                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13393                        final T intentSelection = intentSelectionIter.next();
13394                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13395                            selectionFound = true;
13396                            break;
13397                        }
13398                    }
13399
13400                    // the selection criteria wasn't found in this filter's set; this filter
13401                    // is not a potential match
13402                    if (!selectionFound) {
13403                        intentIter.remove();
13404                    }
13405                }
13406            }
13407        }
13408
13409        private boolean isProtectedAction(ActivityIntentInfo filter) {
13410            final Iterator<String> actionsIter = filter.actionsIterator();
13411            while (actionsIter != null && actionsIter.hasNext()) {
13412                final String filterAction = actionsIter.next();
13413                if (PROTECTED_ACTIONS.contains(filterAction)) {
13414                    return true;
13415                }
13416            }
13417            return false;
13418        }
13419
13420        /**
13421         * Adjusts the priority of the given intent filter according to policy.
13422         * <p>
13423         * <ul>
13424         * <li>The priority for non privileged applications is capped to '0'</li>
13425         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13426         * <li>The priority for unbundled updates to privileged applications is capped to the
13427         *      priority defined on the system partition</li>
13428         * </ul>
13429         * <p>
13430         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13431         * allowed to obtain any priority on any action.
13432         */
13433        private void adjustPriority(
13434                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13435            // nothing to do; priority is fine as-is
13436            if (intent.getPriority() <= 0) {
13437                return;
13438            }
13439
13440            final ActivityInfo activityInfo = intent.activity.info;
13441            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13442
13443            final boolean privilegedApp =
13444                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13445            if (!privilegedApp) {
13446                // non-privileged applications can never define a priority >0
13447                if (DEBUG_FILTERS) {
13448                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13449                            + " package: " + applicationInfo.packageName
13450                            + " activity: " + intent.activity.className
13451                            + " origPrio: " + intent.getPriority());
13452                }
13453                intent.setPriority(0);
13454                return;
13455            }
13456
13457            if (systemActivities == null) {
13458                // the system package is not disabled; we're parsing the system partition
13459                if (isProtectedAction(intent)) {
13460                    if (mDeferProtectedFilters) {
13461                        // We can't deal with these just yet. No component should ever obtain a
13462                        // >0 priority for a protected actions, with ONE exception -- the setup
13463                        // wizard. The setup wizard, however, cannot be known until we're able to
13464                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13465                        // until all intent filters have been processed. Chicken, meet egg.
13466                        // Let the filter temporarily have a high priority and rectify the
13467                        // priorities after all system packages have been scanned.
13468                        mProtectedFilters.add(intent);
13469                        if (DEBUG_FILTERS) {
13470                            Slog.i(TAG, "Protected action; save for later;"
13471                                    + " package: " + applicationInfo.packageName
13472                                    + " activity: " + intent.activity.className
13473                                    + " origPrio: " + intent.getPriority());
13474                        }
13475                        return;
13476                    } else {
13477                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13478                            Slog.i(TAG, "No setup wizard;"
13479                                + " All protected intents capped to priority 0");
13480                        }
13481                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13482                            if (DEBUG_FILTERS) {
13483                                Slog.i(TAG, "Found setup wizard;"
13484                                    + " allow priority " + intent.getPriority() + ";"
13485                                    + " package: " + intent.activity.info.packageName
13486                                    + " activity: " + intent.activity.className
13487                                    + " priority: " + intent.getPriority());
13488                            }
13489                            // setup wizard gets whatever it wants
13490                            return;
13491                        }
13492                        if (DEBUG_FILTERS) {
13493                            Slog.i(TAG, "Protected action; cap priority to 0;"
13494                                    + " package: " + intent.activity.info.packageName
13495                                    + " activity: " + intent.activity.className
13496                                    + " origPrio: " + intent.getPriority());
13497                        }
13498                        intent.setPriority(0);
13499                        return;
13500                    }
13501                }
13502                // privileged apps on the system image get whatever priority they request
13503                return;
13504            }
13505
13506            // privileged app unbundled update ... try to find the same activity
13507            final PackageParser.Activity foundActivity =
13508                    findMatchingActivity(systemActivities, activityInfo);
13509            if (foundActivity == null) {
13510                // this is a new activity; it cannot obtain >0 priority
13511                if (DEBUG_FILTERS) {
13512                    Slog.i(TAG, "New activity; cap priority to 0;"
13513                            + " package: " + applicationInfo.packageName
13514                            + " activity: " + intent.activity.className
13515                            + " origPrio: " + intent.getPriority());
13516                }
13517                intent.setPriority(0);
13518                return;
13519            }
13520
13521            // found activity, now check for filter equivalence
13522
13523            // a shallow copy is enough; we modify the list, not its contents
13524            final List<ActivityIntentInfo> intentListCopy =
13525                    new ArrayList<>(foundActivity.intents);
13526            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13527
13528            // find matching action subsets
13529            final Iterator<String> actionsIterator = intent.actionsIterator();
13530            if (actionsIterator != null) {
13531                getIntentListSubset(
13532                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13533                if (intentListCopy.size() == 0) {
13534                    // no more intents to match; we're not equivalent
13535                    if (DEBUG_FILTERS) {
13536                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13537                                + " package: " + applicationInfo.packageName
13538                                + " activity: " + intent.activity.className
13539                                + " origPrio: " + intent.getPriority());
13540                    }
13541                    intent.setPriority(0);
13542                    return;
13543                }
13544            }
13545
13546            // find matching category subsets
13547            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13548            if (categoriesIterator != null) {
13549                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13550                        categoriesIterator);
13551                if (intentListCopy.size() == 0) {
13552                    // no more intents to match; we're not equivalent
13553                    if (DEBUG_FILTERS) {
13554                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13555                                + " package: " + applicationInfo.packageName
13556                                + " activity: " + intent.activity.className
13557                                + " origPrio: " + intent.getPriority());
13558                    }
13559                    intent.setPriority(0);
13560                    return;
13561                }
13562            }
13563
13564            // find matching schemes subsets
13565            final Iterator<String> schemesIterator = intent.schemesIterator();
13566            if (schemesIterator != null) {
13567                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13568                        schemesIterator);
13569                if (intentListCopy.size() == 0) {
13570                    // no more intents to match; we're not equivalent
13571                    if (DEBUG_FILTERS) {
13572                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13573                                + " package: " + applicationInfo.packageName
13574                                + " activity: " + intent.activity.className
13575                                + " origPrio: " + intent.getPriority());
13576                    }
13577                    intent.setPriority(0);
13578                    return;
13579                }
13580            }
13581
13582            // find matching authorities subsets
13583            final Iterator<IntentFilter.AuthorityEntry>
13584                    authoritiesIterator = intent.authoritiesIterator();
13585            if (authoritiesIterator != null) {
13586                getIntentListSubset(intentListCopy,
13587                        new AuthoritiesIterGenerator(),
13588                        authoritiesIterator);
13589                if (intentListCopy.size() == 0) {
13590                    // no more intents to match; we're not equivalent
13591                    if (DEBUG_FILTERS) {
13592                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13593                                + " package: " + applicationInfo.packageName
13594                                + " activity: " + intent.activity.className
13595                                + " origPrio: " + intent.getPriority());
13596                    }
13597                    intent.setPriority(0);
13598                    return;
13599                }
13600            }
13601
13602            // we found matching filter(s); app gets the max priority of all intents
13603            int cappedPriority = 0;
13604            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13605                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13606            }
13607            if (intent.getPriority() > cappedPriority) {
13608                if (DEBUG_FILTERS) {
13609                    Slog.i(TAG, "Found matching filter(s);"
13610                            + " cap priority to " + cappedPriority + ";"
13611                            + " package: " + applicationInfo.packageName
13612                            + " activity: " + intent.activity.className
13613                            + " origPrio: " + intent.getPriority());
13614                }
13615                intent.setPriority(cappedPriority);
13616                return;
13617            }
13618            // all this for nothing; the requested priority was <= what was on the system
13619        }
13620
13621        public final void addActivity(PackageParser.Activity a, String type) {
13622            mActivities.put(a.getComponentName(), a);
13623            if (DEBUG_SHOW_INFO)
13624                Log.v(
13625                TAG, "  " + type + " " +
13626                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13627            if (DEBUG_SHOW_INFO)
13628                Log.v(TAG, "    Class=" + a.info.name);
13629            final int NI = a.intents.size();
13630            for (int j=0; j<NI; j++) {
13631                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13632                if ("activity".equals(type)) {
13633                    final PackageSetting ps =
13634                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13635                    final List<PackageParser.Activity> systemActivities =
13636                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13637                    adjustPriority(systemActivities, intent);
13638                }
13639                if (DEBUG_SHOW_INFO) {
13640                    Log.v(TAG, "    IntentFilter:");
13641                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13642                }
13643                if (!intent.debugCheck()) {
13644                    Log.w(TAG, "==> For Activity " + a.info.name);
13645                }
13646                addFilter(intent);
13647            }
13648        }
13649
13650        public final void removeActivity(PackageParser.Activity a, String type) {
13651            mActivities.remove(a.getComponentName());
13652            if (DEBUG_SHOW_INFO) {
13653                Log.v(TAG, "  " + type + " "
13654                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13655                                : a.info.name) + ":");
13656                Log.v(TAG, "    Class=" + a.info.name);
13657            }
13658            final int NI = a.intents.size();
13659            for (int j=0; j<NI; j++) {
13660                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13661                if (DEBUG_SHOW_INFO) {
13662                    Log.v(TAG, "    IntentFilter:");
13663                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13664                }
13665                removeFilter(intent);
13666            }
13667        }
13668
13669        @Override
13670        protected boolean allowFilterResult(
13671                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13672            ActivityInfo filterAi = filter.activity.info;
13673            for (int i=dest.size()-1; i>=0; i--) {
13674                ActivityInfo destAi = dest.get(i).activityInfo;
13675                if (destAi.name == filterAi.name
13676                        && destAi.packageName == filterAi.packageName) {
13677                    return false;
13678                }
13679            }
13680            return true;
13681        }
13682
13683        @Override
13684        protected ActivityIntentInfo[] newArray(int size) {
13685            return new ActivityIntentInfo[size];
13686        }
13687
13688        @Override
13689        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13690            if (!sUserManager.exists(userId)) return true;
13691            PackageParser.Package p = filter.activity.owner;
13692            if (p != null) {
13693                PackageSetting ps = (PackageSetting)p.mExtras;
13694                if (ps != null) {
13695                    // System apps are never considered stopped for purposes of
13696                    // filtering, because there may be no way for the user to
13697                    // actually re-launch them.
13698                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13699                            && ps.getStopped(userId);
13700                }
13701            }
13702            return false;
13703        }
13704
13705        @Override
13706        protected boolean isPackageForFilter(String packageName,
13707                PackageParser.ActivityIntentInfo info) {
13708            return packageName.equals(info.activity.owner.packageName);
13709        }
13710
13711        @Override
13712        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13713                int match, int userId) {
13714            if (!sUserManager.exists(userId)) return null;
13715            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13716                return null;
13717            }
13718            final PackageParser.Activity activity = info.activity;
13719            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13720            if (ps == null) {
13721                return null;
13722            }
13723            final PackageUserState userState = ps.readUserState(userId);
13724            ActivityInfo ai =
13725                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13726            if (ai == null) {
13727                return null;
13728            }
13729            final boolean matchExplicitlyVisibleOnly =
13730                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13731            final boolean matchVisibleToInstantApp =
13732                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13733            final boolean componentVisible =
13734                    matchVisibleToInstantApp
13735                    && info.isVisibleToInstantApp()
13736                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13737            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13738            // throw out filters that aren't visible to ephemeral apps
13739            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13740                return null;
13741            }
13742            // throw out instant app filters if we're not explicitly requesting them
13743            if (!matchInstantApp && userState.instantApp) {
13744                return null;
13745            }
13746            // throw out instant app filters if updates are available; will trigger
13747            // instant app resolution
13748            if (userState.instantApp && ps.isUpdateAvailable()) {
13749                return null;
13750            }
13751            final ResolveInfo res = new ResolveInfo();
13752            res.activityInfo = ai;
13753            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13754                res.filter = info;
13755            }
13756            if (info != null) {
13757                res.handleAllWebDataURI = info.handleAllWebDataURI();
13758            }
13759            res.priority = info.getPriority();
13760            res.preferredOrder = activity.owner.mPreferredOrder;
13761            //System.out.println("Result: " + res.activityInfo.className +
13762            //                   " = " + res.priority);
13763            res.match = match;
13764            res.isDefault = info.hasDefault;
13765            res.labelRes = info.labelRes;
13766            res.nonLocalizedLabel = info.nonLocalizedLabel;
13767            if (userNeedsBadging(userId)) {
13768                res.noResourceId = true;
13769            } else {
13770                res.icon = info.icon;
13771            }
13772            res.iconResourceId = info.icon;
13773            res.system = res.activityInfo.applicationInfo.isSystemApp();
13774            res.isInstantAppAvailable = userState.instantApp;
13775            return res;
13776        }
13777
13778        @Override
13779        protected void sortResults(List<ResolveInfo> results) {
13780            Collections.sort(results, mResolvePrioritySorter);
13781        }
13782
13783        @Override
13784        protected void dumpFilter(PrintWriter out, String prefix,
13785                PackageParser.ActivityIntentInfo filter) {
13786            out.print(prefix); out.print(
13787                    Integer.toHexString(System.identityHashCode(filter.activity)));
13788                    out.print(' ');
13789                    filter.activity.printComponentShortName(out);
13790                    out.print(" filter ");
13791                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13792        }
13793
13794        @Override
13795        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13796            return filter.activity;
13797        }
13798
13799        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13800            PackageParser.Activity activity = (PackageParser.Activity)label;
13801            out.print(prefix); out.print(
13802                    Integer.toHexString(System.identityHashCode(activity)));
13803                    out.print(' ');
13804                    activity.printComponentShortName(out);
13805            if (count > 1) {
13806                out.print(" ("); out.print(count); out.print(" filters)");
13807            }
13808            out.println();
13809        }
13810
13811        // Keys are String (activity class name), values are Activity.
13812        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13813                = new ArrayMap<ComponentName, PackageParser.Activity>();
13814        private int mFlags;
13815    }
13816
13817    private final class ServiceIntentResolver
13818            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13819        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13820                boolean defaultOnly, int userId) {
13821            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13822            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13823        }
13824
13825        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13826                int userId) {
13827            if (!sUserManager.exists(userId)) return null;
13828            mFlags = flags;
13829            return super.queryIntent(intent, resolvedType,
13830                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13831                    userId);
13832        }
13833
13834        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13835                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13836            if (!sUserManager.exists(userId)) return null;
13837            if (packageServices == null) {
13838                return null;
13839            }
13840            mFlags = flags;
13841            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13842            final int N = packageServices.size();
13843            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13844                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13845
13846            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13847            for (int i = 0; i < N; ++i) {
13848                intentFilters = packageServices.get(i).intents;
13849                if (intentFilters != null && intentFilters.size() > 0) {
13850                    PackageParser.ServiceIntentInfo[] array =
13851                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13852                    intentFilters.toArray(array);
13853                    listCut.add(array);
13854                }
13855            }
13856            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13857        }
13858
13859        public final void addService(PackageParser.Service s) {
13860            mServices.put(s.getComponentName(), s);
13861            if (DEBUG_SHOW_INFO) {
13862                Log.v(TAG, "  "
13863                        + (s.info.nonLocalizedLabel != null
13864                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13865                Log.v(TAG, "    Class=" + s.info.name);
13866            }
13867            final int NI = s.intents.size();
13868            int j;
13869            for (j=0; j<NI; j++) {
13870                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13871                if (DEBUG_SHOW_INFO) {
13872                    Log.v(TAG, "    IntentFilter:");
13873                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13874                }
13875                if (!intent.debugCheck()) {
13876                    Log.w(TAG, "==> For Service " + s.info.name);
13877                }
13878                addFilter(intent);
13879            }
13880        }
13881
13882        public final void removeService(PackageParser.Service s) {
13883            mServices.remove(s.getComponentName());
13884            if (DEBUG_SHOW_INFO) {
13885                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13886                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13887                Log.v(TAG, "    Class=" + s.info.name);
13888            }
13889            final int NI = s.intents.size();
13890            int j;
13891            for (j=0; j<NI; j++) {
13892                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13893                if (DEBUG_SHOW_INFO) {
13894                    Log.v(TAG, "    IntentFilter:");
13895                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13896                }
13897                removeFilter(intent);
13898            }
13899        }
13900
13901        @Override
13902        protected boolean allowFilterResult(
13903                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13904            ServiceInfo filterSi = filter.service.info;
13905            for (int i=dest.size()-1; i>=0; i--) {
13906                ServiceInfo destAi = dest.get(i).serviceInfo;
13907                if (destAi.name == filterSi.name
13908                        && destAi.packageName == filterSi.packageName) {
13909                    return false;
13910                }
13911            }
13912            return true;
13913        }
13914
13915        @Override
13916        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13917            return new PackageParser.ServiceIntentInfo[size];
13918        }
13919
13920        @Override
13921        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13922            if (!sUserManager.exists(userId)) return true;
13923            PackageParser.Package p = filter.service.owner;
13924            if (p != null) {
13925                PackageSetting ps = (PackageSetting)p.mExtras;
13926                if (ps != null) {
13927                    // System apps are never considered stopped for purposes of
13928                    // filtering, because there may be no way for the user to
13929                    // actually re-launch them.
13930                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13931                            && ps.getStopped(userId);
13932                }
13933            }
13934            return false;
13935        }
13936
13937        @Override
13938        protected boolean isPackageForFilter(String packageName,
13939                PackageParser.ServiceIntentInfo info) {
13940            return packageName.equals(info.service.owner.packageName);
13941        }
13942
13943        @Override
13944        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13945                int match, int userId) {
13946            if (!sUserManager.exists(userId)) return null;
13947            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13948            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13949                return null;
13950            }
13951            final PackageParser.Service service = info.service;
13952            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13953            if (ps == null) {
13954                return null;
13955            }
13956            final PackageUserState userState = ps.readUserState(userId);
13957            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13958                    userState, userId);
13959            if (si == null) {
13960                return null;
13961            }
13962            final boolean matchVisibleToInstantApp =
13963                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13964            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13965            // throw out filters that aren't visible to ephemeral apps
13966            if (matchVisibleToInstantApp
13967                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13968                return null;
13969            }
13970            // throw out ephemeral filters if we're not explicitly requesting them
13971            if (!isInstantApp && userState.instantApp) {
13972                return null;
13973            }
13974            // throw out instant app filters if updates are available; will trigger
13975            // instant app resolution
13976            if (userState.instantApp && ps.isUpdateAvailable()) {
13977                return null;
13978            }
13979            final ResolveInfo res = new ResolveInfo();
13980            res.serviceInfo = si;
13981            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13982                res.filter = filter;
13983            }
13984            res.priority = info.getPriority();
13985            res.preferredOrder = service.owner.mPreferredOrder;
13986            res.match = match;
13987            res.isDefault = info.hasDefault;
13988            res.labelRes = info.labelRes;
13989            res.nonLocalizedLabel = info.nonLocalizedLabel;
13990            res.icon = info.icon;
13991            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13992            return res;
13993        }
13994
13995        @Override
13996        protected void sortResults(List<ResolveInfo> results) {
13997            Collections.sort(results, mResolvePrioritySorter);
13998        }
13999
14000        @Override
14001        protected void dumpFilter(PrintWriter out, String prefix,
14002                PackageParser.ServiceIntentInfo filter) {
14003            out.print(prefix); out.print(
14004                    Integer.toHexString(System.identityHashCode(filter.service)));
14005                    out.print(' ');
14006                    filter.service.printComponentShortName(out);
14007                    out.print(" filter ");
14008                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14009        }
14010
14011        @Override
14012        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14013            return filter.service;
14014        }
14015
14016        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14017            PackageParser.Service service = (PackageParser.Service)label;
14018            out.print(prefix); out.print(
14019                    Integer.toHexString(System.identityHashCode(service)));
14020                    out.print(' ');
14021                    service.printComponentShortName(out);
14022            if (count > 1) {
14023                out.print(" ("); out.print(count); out.print(" filters)");
14024            }
14025            out.println();
14026        }
14027
14028//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14029//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14030//            final List<ResolveInfo> retList = Lists.newArrayList();
14031//            while (i.hasNext()) {
14032//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14033//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14034//                    retList.add(resolveInfo);
14035//                }
14036//            }
14037//            return retList;
14038//        }
14039
14040        // Keys are String (activity class name), values are Activity.
14041        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14042                = new ArrayMap<ComponentName, PackageParser.Service>();
14043        private int mFlags;
14044    }
14045
14046    private final class ProviderIntentResolver
14047            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14048        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14049                boolean defaultOnly, int userId) {
14050            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14051            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14052        }
14053
14054        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14055                int userId) {
14056            if (!sUserManager.exists(userId))
14057                return null;
14058            mFlags = flags;
14059            return super.queryIntent(intent, resolvedType,
14060                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14061                    userId);
14062        }
14063
14064        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14065                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14066            if (!sUserManager.exists(userId))
14067                return null;
14068            if (packageProviders == null) {
14069                return null;
14070            }
14071            mFlags = flags;
14072            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14073            final int N = packageProviders.size();
14074            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14075                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14076
14077            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14078            for (int i = 0; i < N; ++i) {
14079                intentFilters = packageProviders.get(i).intents;
14080                if (intentFilters != null && intentFilters.size() > 0) {
14081                    PackageParser.ProviderIntentInfo[] array =
14082                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14083                    intentFilters.toArray(array);
14084                    listCut.add(array);
14085                }
14086            }
14087            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14088        }
14089
14090        public final void addProvider(PackageParser.Provider p) {
14091            if (mProviders.containsKey(p.getComponentName())) {
14092                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14093                return;
14094            }
14095
14096            mProviders.put(p.getComponentName(), p);
14097            if (DEBUG_SHOW_INFO) {
14098                Log.v(TAG, "  "
14099                        + (p.info.nonLocalizedLabel != null
14100                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14101                Log.v(TAG, "    Class=" + p.info.name);
14102            }
14103            final int NI = p.intents.size();
14104            int j;
14105            for (j = 0; j < NI; j++) {
14106                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14107                if (DEBUG_SHOW_INFO) {
14108                    Log.v(TAG, "    IntentFilter:");
14109                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14110                }
14111                if (!intent.debugCheck()) {
14112                    Log.w(TAG, "==> For Provider " + p.info.name);
14113                }
14114                addFilter(intent);
14115            }
14116        }
14117
14118        public final void removeProvider(PackageParser.Provider p) {
14119            mProviders.remove(p.getComponentName());
14120            if (DEBUG_SHOW_INFO) {
14121                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14122                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14123                Log.v(TAG, "    Class=" + p.info.name);
14124            }
14125            final int NI = p.intents.size();
14126            int j;
14127            for (j = 0; j < NI; j++) {
14128                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14129                if (DEBUG_SHOW_INFO) {
14130                    Log.v(TAG, "    IntentFilter:");
14131                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14132                }
14133                removeFilter(intent);
14134            }
14135        }
14136
14137        @Override
14138        protected boolean allowFilterResult(
14139                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14140            ProviderInfo filterPi = filter.provider.info;
14141            for (int i = dest.size() - 1; i >= 0; i--) {
14142                ProviderInfo destPi = dest.get(i).providerInfo;
14143                if (destPi.name == filterPi.name
14144                        && destPi.packageName == filterPi.packageName) {
14145                    return false;
14146                }
14147            }
14148            return true;
14149        }
14150
14151        @Override
14152        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14153            return new PackageParser.ProviderIntentInfo[size];
14154        }
14155
14156        @Override
14157        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14158            if (!sUserManager.exists(userId))
14159                return true;
14160            PackageParser.Package p = filter.provider.owner;
14161            if (p != null) {
14162                PackageSetting ps = (PackageSetting) p.mExtras;
14163                if (ps != null) {
14164                    // System apps are never considered stopped for purposes of
14165                    // filtering, because there may be no way for the user to
14166                    // actually re-launch them.
14167                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14168                            && ps.getStopped(userId);
14169                }
14170            }
14171            return false;
14172        }
14173
14174        @Override
14175        protected boolean isPackageForFilter(String packageName,
14176                PackageParser.ProviderIntentInfo info) {
14177            return packageName.equals(info.provider.owner.packageName);
14178        }
14179
14180        @Override
14181        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14182                int match, int userId) {
14183            if (!sUserManager.exists(userId))
14184                return null;
14185            final PackageParser.ProviderIntentInfo info = filter;
14186            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14187                return null;
14188            }
14189            final PackageParser.Provider provider = info.provider;
14190            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14191            if (ps == null) {
14192                return null;
14193            }
14194            final PackageUserState userState = ps.readUserState(userId);
14195            final boolean matchVisibleToInstantApp =
14196                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14197            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14198            // throw out filters that aren't visible to instant applications
14199            if (matchVisibleToInstantApp
14200                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14201                return null;
14202            }
14203            // throw out instant application filters if we're not explicitly requesting them
14204            if (!isInstantApp && userState.instantApp) {
14205                return null;
14206            }
14207            // throw out instant application filters if updates are available; will trigger
14208            // instant application resolution
14209            if (userState.instantApp && ps.isUpdateAvailable()) {
14210                return null;
14211            }
14212            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14213                    userState, userId);
14214            if (pi == null) {
14215                return null;
14216            }
14217            final ResolveInfo res = new ResolveInfo();
14218            res.providerInfo = pi;
14219            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14220                res.filter = filter;
14221            }
14222            res.priority = info.getPriority();
14223            res.preferredOrder = provider.owner.mPreferredOrder;
14224            res.match = match;
14225            res.isDefault = info.hasDefault;
14226            res.labelRes = info.labelRes;
14227            res.nonLocalizedLabel = info.nonLocalizedLabel;
14228            res.icon = info.icon;
14229            res.system = res.providerInfo.applicationInfo.isSystemApp();
14230            return res;
14231        }
14232
14233        @Override
14234        protected void sortResults(List<ResolveInfo> results) {
14235            Collections.sort(results, mResolvePrioritySorter);
14236        }
14237
14238        @Override
14239        protected void dumpFilter(PrintWriter out, String prefix,
14240                PackageParser.ProviderIntentInfo filter) {
14241            out.print(prefix);
14242            out.print(
14243                    Integer.toHexString(System.identityHashCode(filter.provider)));
14244            out.print(' ');
14245            filter.provider.printComponentShortName(out);
14246            out.print(" filter ");
14247            out.println(Integer.toHexString(System.identityHashCode(filter)));
14248        }
14249
14250        @Override
14251        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14252            return filter.provider;
14253        }
14254
14255        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14256            PackageParser.Provider provider = (PackageParser.Provider)label;
14257            out.print(prefix); out.print(
14258                    Integer.toHexString(System.identityHashCode(provider)));
14259                    out.print(' ');
14260                    provider.printComponentShortName(out);
14261            if (count > 1) {
14262                out.print(" ("); out.print(count); out.print(" filters)");
14263            }
14264            out.println();
14265        }
14266
14267        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14268                = new ArrayMap<ComponentName, PackageParser.Provider>();
14269        private int mFlags;
14270    }
14271
14272    static final class EphemeralIntentResolver
14273            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14274        /**
14275         * The result that has the highest defined order. Ordering applies on a
14276         * per-package basis. Mapping is from package name to Pair of order and
14277         * EphemeralResolveInfo.
14278         * <p>
14279         * NOTE: This is implemented as a field variable for convenience and efficiency.
14280         * By having a field variable, we're able to track filter ordering as soon as
14281         * a non-zero order is defined. Otherwise, multiple loops across the result set
14282         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14283         * this needs to be contained entirely within {@link #filterResults}.
14284         */
14285        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14286
14287        @Override
14288        protected AuxiliaryResolveInfo[] newArray(int size) {
14289            return new AuxiliaryResolveInfo[size];
14290        }
14291
14292        @Override
14293        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14294            return true;
14295        }
14296
14297        @Override
14298        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14299                int userId) {
14300            if (!sUserManager.exists(userId)) {
14301                return null;
14302            }
14303            final String packageName = responseObj.resolveInfo.getPackageName();
14304            final Integer order = responseObj.getOrder();
14305            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14306                    mOrderResult.get(packageName);
14307            // ordering is enabled and this item's order isn't high enough
14308            if (lastOrderResult != null && lastOrderResult.first >= order) {
14309                return null;
14310            }
14311            final InstantAppResolveInfo res = responseObj.resolveInfo;
14312            if (order > 0) {
14313                // non-zero order, enable ordering
14314                mOrderResult.put(packageName, new Pair<>(order, res));
14315            }
14316            return responseObj;
14317        }
14318
14319        @Override
14320        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14321            // only do work if ordering is enabled [most of the time it won't be]
14322            if (mOrderResult.size() == 0) {
14323                return;
14324            }
14325            int resultSize = results.size();
14326            for (int i = 0; i < resultSize; i++) {
14327                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14328                final String packageName = info.getPackageName();
14329                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14330                if (savedInfo == null) {
14331                    // package doesn't having ordering
14332                    continue;
14333                }
14334                if (savedInfo.second == info) {
14335                    // circled back to the highest ordered item; remove from order list
14336                    mOrderResult.remove(savedInfo);
14337                    if (mOrderResult.size() == 0) {
14338                        // no more ordered items
14339                        break;
14340                    }
14341                    continue;
14342                }
14343                // item has a worse order, remove it from the result list
14344                results.remove(i);
14345                resultSize--;
14346                i--;
14347            }
14348        }
14349    }
14350
14351    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14352            new Comparator<ResolveInfo>() {
14353        public int compare(ResolveInfo r1, ResolveInfo r2) {
14354            int v1 = r1.priority;
14355            int v2 = r2.priority;
14356            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14357            if (v1 != v2) {
14358                return (v1 > v2) ? -1 : 1;
14359            }
14360            v1 = r1.preferredOrder;
14361            v2 = r2.preferredOrder;
14362            if (v1 != v2) {
14363                return (v1 > v2) ? -1 : 1;
14364            }
14365            if (r1.isDefault != r2.isDefault) {
14366                return r1.isDefault ? -1 : 1;
14367            }
14368            v1 = r1.match;
14369            v2 = r2.match;
14370            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14371            if (v1 != v2) {
14372                return (v1 > v2) ? -1 : 1;
14373            }
14374            if (r1.system != r2.system) {
14375                return r1.system ? -1 : 1;
14376            }
14377            if (r1.activityInfo != null) {
14378                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14379            }
14380            if (r1.serviceInfo != null) {
14381                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14382            }
14383            if (r1.providerInfo != null) {
14384                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14385            }
14386            return 0;
14387        }
14388    };
14389
14390    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14391            new Comparator<ProviderInfo>() {
14392        public int compare(ProviderInfo p1, ProviderInfo p2) {
14393            final int v1 = p1.initOrder;
14394            final int v2 = p2.initOrder;
14395            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14396        }
14397    };
14398
14399    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14400            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14401            final int[] userIds) {
14402        mHandler.post(new Runnable() {
14403            @Override
14404            public void run() {
14405                try {
14406                    final IActivityManager am = ActivityManager.getService();
14407                    if (am == null) return;
14408                    final int[] resolvedUserIds;
14409                    if (userIds == null) {
14410                        resolvedUserIds = am.getRunningUserIds();
14411                    } else {
14412                        resolvedUserIds = userIds;
14413                    }
14414                    for (int id : resolvedUserIds) {
14415                        final Intent intent = new Intent(action,
14416                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14417                        if (extras != null) {
14418                            intent.putExtras(extras);
14419                        }
14420                        if (targetPkg != null) {
14421                            intent.setPackage(targetPkg);
14422                        }
14423                        // Modify the UID when posting to other users
14424                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14425                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14426                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14427                            intent.putExtra(Intent.EXTRA_UID, uid);
14428                        }
14429                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14430                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14431                        if (DEBUG_BROADCASTS) {
14432                            RuntimeException here = new RuntimeException("here");
14433                            here.fillInStackTrace();
14434                            Slog.d(TAG, "Sending to user " + id + ": "
14435                                    + intent.toShortString(false, true, false, false)
14436                                    + " " + intent.getExtras(), here);
14437                        }
14438                        am.broadcastIntent(null, intent, null, finishedReceiver,
14439                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14440                                null, finishedReceiver != null, false, id);
14441                    }
14442                } catch (RemoteException ex) {
14443                }
14444            }
14445        });
14446    }
14447
14448    /**
14449     * Check if the external storage media is available. This is true if there
14450     * is a mounted external storage medium or if the external storage is
14451     * emulated.
14452     */
14453    private boolean isExternalMediaAvailable() {
14454        return mMediaMounted || Environment.isExternalStorageEmulated();
14455    }
14456
14457    @Override
14458    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14459        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14460            return null;
14461        }
14462        // writer
14463        synchronized (mPackages) {
14464            if (!isExternalMediaAvailable()) {
14465                // If the external storage is no longer mounted at this point,
14466                // the caller may not have been able to delete all of this
14467                // packages files and can not delete any more.  Bail.
14468                return null;
14469            }
14470            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14471            if (lastPackage != null) {
14472                pkgs.remove(lastPackage);
14473            }
14474            if (pkgs.size() > 0) {
14475                return pkgs.get(0);
14476            }
14477        }
14478        return null;
14479    }
14480
14481    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14482        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14483                userId, andCode ? 1 : 0, packageName);
14484        if (mSystemReady) {
14485            msg.sendToTarget();
14486        } else {
14487            if (mPostSystemReadyMessages == null) {
14488                mPostSystemReadyMessages = new ArrayList<>();
14489            }
14490            mPostSystemReadyMessages.add(msg);
14491        }
14492    }
14493
14494    void startCleaningPackages() {
14495        // reader
14496        if (!isExternalMediaAvailable()) {
14497            return;
14498        }
14499        synchronized (mPackages) {
14500            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14501                return;
14502            }
14503        }
14504        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14505        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14506        IActivityManager am = ActivityManager.getService();
14507        if (am != null) {
14508            int dcsUid = -1;
14509            synchronized (mPackages) {
14510                if (!mDefaultContainerWhitelisted) {
14511                    mDefaultContainerWhitelisted = true;
14512                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14513                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14514                }
14515            }
14516            try {
14517                if (dcsUid > 0) {
14518                    am.backgroundWhitelistUid(dcsUid);
14519                }
14520                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14521                        UserHandle.USER_SYSTEM);
14522            } catch (RemoteException e) {
14523            }
14524        }
14525    }
14526
14527    @Override
14528    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14529            int installFlags, String installerPackageName, int userId) {
14530        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14531
14532        final int callingUid = Binder.getCallingUid();
14533        enforceCrossUserPermission(callingUid, userId,
14534                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14535
14536        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14537            try {
14538                if (observer != null) {
14539                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14540                }
14541            } catch (RemoteException re) {
14542            }
14543            return;
14544        }
14545
14546        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14547            installFlags |= PackageManager.INSTALL_FROM_ADB;
14548
14549        } else {
14550            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14551            // about installerPackageName.
14552
14553            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14554            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14555        }
14556
14557        UserHandle user;
14558        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14559            user = UserHandle.ALL;
14560        } else {
14561            user = new UserHandle(userId);
14562        }
14563
14564        // Only system components can circumvent runtime permissions when installing.
14565        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14566                && mContext.checkCallingOrSelfPermission(Manifest.permission
14567                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14568            throw new SecurityException("You need the "
14569                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14570                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14571        }
14572
14573        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14574                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14575            throw new IllegalArgumentException(
14576                    "New installs into ASEC containers no longer supported");
14577        }
14578
14579        final File originFile = new File(originPath);
14580        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14581
14582        final Message msg = mHandler.obtainMessage(INIT_COPY);
14583        final VerificationInfo verificationInfo = new VerificationInfo(
14584                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14585        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14586                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14587                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14588                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14589        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14590        msg.obj = params;
14591
14592        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14593                System.identityHashCode(msg.obj));
14594        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14595                System.identityHashCode(msg.obj));
14596
14597        mHandler.sendMessage(msg);
14598    }
14599
14600
14601    /**
14602     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14603     * it is acting on behalf on an enterprise or the user).
14604     *
14605     * Note that the ordering of the conditionals in this method is important. The checks we perform
14606     * are as follows, in this order:
14607     *
14608     * 1) If the install is being performed by a system app, we can trust the app to have set the
14609     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14610     *    what it is.
14611     * 2) If the install is being performed by a device or profile owner app, the install reason
14612     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14613     *    set the install reason correctly. If the app targets an older SDK version where install
14614     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14615     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14616     * 3) In all other cases, the install is being performed by a regular app that is neither part
14617     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14618     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14619     *    set to enterprise policy and if so, change it to unknown instead.
14620     */
14621    private int fixUpInstallReason(String installerPackageName, int installerUid,
14622            int installReason) {
14623        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14624                == PERMISSION_GRANTED) {
14625            // If the install is being performed by a system app, we trust that app to have set the
14626            // install reason correctly.
14627            return installReason;
14628        }
14629
14630        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14631            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14632        if (dpm != null) {
14633            ComponentName owner = null;
14634            try {
14635                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14636                if (owner == null) {
14637                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14638                }
14639            } catch (RemoteException e) {
14640            }
14641            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14642                // If the install is being performed by a device or profile owner, the install
14643                // reason should be enterprise policy.
14644                return PackageManager.INSTALL_REASON_POLICY;
14645            }
14646        }
14647
14648        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14649            // If the install is being performed by a regular app (i.e. neither system app nor
14650            // device or profile owner), we have no reason to believe that the app is acting on
14651            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14652            // change it to unknown instead.
14653            return PackageManager.INSTALL_REASON_UNKNOWN;
14654        }
14655
14656        // If the install is being performed by a regular app and the install reason was set to any
14657        // value but enterprise policy, leave the install reason unchanged.
14658        return installReason;
14659    }
14660
14661    void installStage(String packageName, File stagedDir, String stagedCid,
14662            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14663            String installerPackageName, int installerUid, UserHandle user,
14664            Certificate[][] certificates) {
14665        if (DEBUG_EPHEMERAL) {
14666            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14667                Slog.d(TAG, "Ephemeral install of " + packageName);
14668            }
14669        }
14670        final VerificationInfo verificationInfo = new VerificationInfo(
14671                sessionParams.originatingUri, sessionParams.referrerUri,
14672                sessionParams.originatingUid, installerUid);
14673
14674        final OriginInfo origin;
14675        if (stagedDir != null) {
14676            origin = OriginInfo.fromStagedFile(stagedDir);
14677        } else {
14678            origin = OriginInfo.fromStagedContainer(stagedCid);
14679        }
14680
14681        final Message msg = mHandler.obtainMessage(INIT_COPY);
14682        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14683                sessionParams.installReason);
14684        final InstallParams params = new InstallParams(origin, null, observer,
14685                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14686                verificationInfo, user, sessionParams.abiOverride,
14687                sessionParams.grantedRuntimePermissions, certificates, installReason);
14688        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14689        msg.obj = params;
14690
14691        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14692                System.identityHashCode(msg.obj));
14693        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14694                System.identityHashCode(msg.obj));
14695
14696        mHandler.sendMessage(msg);
14697    }
14698
14699    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14700            int userId) {
14701        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14702        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14703                false /*startReceiver*/, pkgSetting.appId, userId);
14704
14705        // Send a session commit broadcast
14706        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14707        info.installReason = pkgSetting.getInstallReason(userId);
14708        info.appPackageName = packageName;
14709        sendSessionCommitBroadcast(info, userId);
14710    }
14711
14712    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14713            boolean includeStopped, int appId, int... userIds) {
14714        if (ArrayUtils.isEmpty(userIds)) {
14715            return;
14716        }
14717        Bundle extras = new Bundle(1);
14718        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14719        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14720
14721        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14722                packageName, extras, 0, null, null, userIds);
14723        if (sendBootCompleted) {
14724            mHandler.post(() -> {
14725                        for (int userId : userIds) {
14726                            sendBootCompletedBroadcastToSystemApp(
14727                                    packageName, includeStopped, userId);
14728                        }
14729                    }
14730            );
14731        }
14732    }
14733
14734    /**
14735     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14736     * automatically without needing an explicit launch.
14737     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14738     */
14739    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14740            int userId) {
14741        // If user is not running, the app didn't miss any broadcast
14742        if (!mUserManagerInternal.isUserRunning(userId)) {
14743            return;
14744        }
14745        final IActivityManager am = ActivityManager.getService();
14746        try {
14747            // Deliver LOCKED_BOOT_COMPLETED first
14748            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14749                    .setPackage(packageName);
14750            if (includeStopped) {
14751                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14752            }
14753            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14754            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14755                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14756
14757            // Deliver BOOT_COMPLETED only if user is unlocked
14758            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14759                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14760                if (includeStopped) {
14761                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14762                }
14763                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14764                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14765            }
14766        } catch (RemoteException e) {
14767            throw e.rethrowFromSystemServer();
14768        }
14769    }
14770
14771    @Override
14772    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14773            int userId) {
14774        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14775        PackageSetting pkgSetting;
14776        final int callingUid = Binder.getCallingUid();
14777        enforceCrossUserPermission(callingUid, userId,
14778                true /* requireFullPermission */, true /* checkShell */,
14779                "setApplicationHiddenSetting for user " + userId);
14780
14781        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14782            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14783            return false;
14784        }
14785
14786        long callingId = Binder.clearCallingIdentity();
14787        try {
14788            boolean sendAdded = false;
14789            boolean sendRemoved = false;
14790            // writer
14791            synchronized (mPackages) {
14792                pkgSetting = mSettings.mPackages.get(packageName);
14793                if (pkgSetting == null) {
14794                    return false;
14795                }
14796                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14797                    return false;
14798                }
14799                // Do not allow "android" is being disabled
14800                if ("android".equals(packageName)) {
14801                    Slog.w(TAG, "Cannot hide package: android");
14802                    return false;
14803                }
14804                // Cannot hide static shared libs as they are considered
14805                // a part of the using app (emulating static linking). Also
14806                // static libs are installed always on internal storage.
14807                PackageParser.Package pkg = mPackages.get(packageName);
14808                if (pkg != null && pkg.staticSharedLibName != null) {
14809                    Slog.w(TAG, "Cannot hide package: " + packageName
14810                            + " providing static shared library: "
14811                            + pkg.staticSharedLibName);
14812                    return false;
14813                }
14814                // Only allow protected packages to hide themselves.
14815                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14816                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14817                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14818                    return false;
14819                }
14820
14821                if (pkgSetting.getHidden(userId) != hidden) {
14822                    pkgSetting.setHidden(hidden, userId);
14823                    mSettings.writePackageRestrictionsLPr(userId);
14824                    if (hidden) {
14825                        sendRemoved = true;
14826                    } else {
14827                        sendAdded = true;
14828                    }
14829                }
14830            }
14831            if (sendAdded) {
14832                sendPackageAddedForUser(packageName, pkgSetting, userId);
14833                return true;
14834            }
14835            if (sendRemoved) {
14836                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14837                        "hiding pkg");
14838                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14839                return true;
14840            }
14841        } finally {
14842            Binder.restoreCallingIdentity(callingId);
14843        }
14844        return false;
14845    }
14846
14847    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14848            int userId) {
14849        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14850        info.removedPackage = packageName;
14851        info.installerPackageName = pkgSetting.installerPackageName;
14852        info.removedUsers = new int[] {userId};
14853        info.broadcastUsers = new int[] {userId};
14854        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14855        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14856    }
14857
14858    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14859        if (pkgList.length > 0) {
14860            Bundle extras = new Bundle(1);
14861            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14862
14863            sendPackageBroadcast(
14864                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14865                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14866                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14867                    new int[] {userId});
14868        }
14869    }
14870
14871    /**
14872     * Returns true if application is not found or there was an error. Otherwise it returns
14873     * the hidden state of the package for the given user.
14874     */
14875    @Override
14876    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14877        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14878        final int callingUid = Binder.getCallingUid();
14879        enforceCrossUserPermission(callingUid, userId,
14880                true /* requireFullPermission */, false /* checkShell */,
14881                "getApplicationHidden for user " + userId);
14882        PackageSetting ps;
14883        long callingId = Binder.clearCallingIdentity();
14884        try {
14885            // writer
14886            synchronized (mPackages) {
14887                ps = mSettings.mPackages.get(packageName);
14888                if (ps == null) {
14889                    return true;
14890                }
14891                if (filterAppAccessLPr(ps, callingUid, userId)) {
14892                    return true;
14893                }
14894                return ps.getHidden(userId);
14895            }
14896        } finally {
14897            Binder.restoreCallingIdentity(callingId);
14898        }
14899    }
14900
14901    /**
14902     * @hide
14903     */
14904    @Override
14905    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14906            int installReason) {
14907        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14908                null);
14909        PackageSetting pkgSetting;
14910        final int callingUid = Binder.getCallingUid();
14911        enforceCrossUserPermission(callingUid, userId,
14912                true /* requireFullPermission */, true /* checkShell */,
14913                "installExistingPackage for user " + userId);
14914        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14915            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14916        }
14917
14918        long callingId = Binder.clearCallingIdentity();
14919        try {
14920            boolean installed = false;
14921            final boolean instantApp =
14922                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14923            final boolean fullApp =
14924                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14925
14926            // writer
14927            synchronized (mPackages) {
14928                pkgSetting = mSettings.mPackages.get(packageName);
14929                if (pkgSetting == null) {
14930                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14931                }
14932                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14933                    // only allow the existing package to be used if it's installed as a full
14934                    // application for at least one user
14935                    boolean installAllowed = false;
14936                    for (int checkUserId : sUserManager.getUserIds()) {
14937                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14938                        if (installAllowed) {
14939                            break;
14940                        }
14941                    }
14942                    if (!installAllowed) {
14943                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14944                    }
14945                }
14946                if (!pkgSetting.getInstalled(userId)) {
14947                    pkgSetting.setInstalled(true, userId);
14948                    pkgSetting.setHidden(false, userId);
14949                    pkgSetting.setInstallReason(installReason, userId);
14950                    mSettings.writePackageRestrictionsLPr(userId);
14951                    mSettings.writeKernelMappingLPr(pkgSetting);
14952                    installed = true;
14953                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14954                    // upgrade app from instant to full; we don't allow app downgrade
14955                    installed = true;
14956                }
14957                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14958            }
14959
14960            if (installed) {
14961                if (pkgSetting.pkg != null) {
14962                    synchronized (mInstallLock) {
14963                        // We don't need to freeze for a brand new install
14964                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14965                    }
14966                }
14967                sendPackageAddedForUser(packageName, pkgSetting, userId);
14968                synchronized (mPackages) {
14969                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14970                }
14971            }
14972        } finally {
14973            Binder.restoreCallingIdentity(callingId);
14974        }
14975
14976        return PackageManager.INSTALL_SUCCEEDED;
14977    }
14978
14979    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14980            boolean instantApp, boolean fullApp) {
14981        // no state specified; do nothing
14982        if (!instantApp && !fullApp) {
14983            return;
14984        }
14985        if (userId != UserHandle.USER_ALL) {
14986            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14987                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14988            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14989                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14990            }
14991        } else {
14992            for (int currentUserId : sUserManager.getUserIds()) {
14993                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14994                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14995                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14996                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14997                }
14998            }
14999        }
15000    }
15001
15002    boolean isUserRestricted(int userId, String restrictionKey) {
15003        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15004        if (restrictions.getBoolean(restrictionKey, false)) {
15005            Log.w(TAG, "User is restricted: " + restrictionKey);
15006            return true;
15007        }
15008        return false;
15009    }
15010
15011    @Override
15012    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15013            int userId) {
15014        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15015        final int callingUid = Binder.getCallingUid();
15016        enforceCrossUserPermission(callingUid, userId,
15017                true /* requireFullPermission */, true /* checkShell */,
15018                "setPackagesSuspended for user " + userId);
15019
15020        if (ArrayUtils.isEmpty(packageNames)) {
15021            return packageNames;
15022        }
15023
15024        // List of package names for whom the suspended state has changed.
15025        List<String> changedPackages = new ArrayList<>(packageNames.length);
15026        // List of package names for whom the suspended state is not set as requested in this
15027        // method.
15028        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15029        long callingId = Binder.clearCallingIdentity();
15030        try {
15031            for (int i = 0; i < packageNames.length; i++) {
15032                String packageName = packageNames[i];
15033                boolean changed = false;
15034                final int appId;
15035                synchronized (mPackages) {
15036                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15037                    if (pkgSetting == null
15038                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15039                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15040                                + "\". Skipping suspending/un-suspending.");
15041                        unactionedPackages.add(packageName);
15042                        continue;
15043                    }
15044                    appId = pkgSetting.appId;
15045                    if (pkgSetting.getSuspended(userId) != suspended) {
15046                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15047                            unactionedPackages.add(packageName);
15048                            continue;
15049                        }
15050                        pkgSetting.setSuspended(suspended, userId);
15051                        mSettings.writePackageRestrictionsLPr(userId);
15052                        changed = true;
15053                        changedPackages.add(packageName);
15054                    }
15055                }
15056
15057                if (changed && suspended) {
15058                    killApplication(packageName, UserHandle.getUid(userId, appId),
15059                            "suspending package");
15060                }
15061            }
15062        } finally {
15063            Binder.restoreCallingIdentity(callingId);
15064        }
15065
15066        if (!changedPackages.isEmpty()) {
15067            sendPackagesSuspendedForUser(changedPackages.toArray(
15068                    new String[changedPackages.size()]), userId, suspended);
15069        }
15070
15071        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15072    }
15073
15074    @Override
15075    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15076        final int callingUid = Binder.getCallingUid();
15077        enforceCrossUserPermission(callingUid, userId,
15078                true /* requireFullPermission */, false /* checkShell */,
15079                "isPackageSuspendedForUser for user " + userId);
15080        synchronized (mPackages) {
15081            final PackageSetting ps = mSettings.mPackages.get(packageName);
15082            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15083                throw new IllegalArgumentException("Unknown target package: " + packageName);
15084            }
15085            return ps.getSuspended(userId);
15086        }
15087    }
15088
15089    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15090        if (isPackageDeviceAdmin(packageName, userId)) {
15091            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15092                    + "\": has an active device admin");
15093            return false;
15094        }
15095
15096        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15097        if (packageName.equals(activeLauncherPackageName)) {
15098            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15099                    + "\": contains the active launcher");
15100            return false;
15101        }
15102
15103        if (packageName.equals(mRequiredInstallerPackage)) {
15104            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15105                    + "\": required for package installation");
15106            return false;
15107        }
15108
15109        if (packageName.equals(mRequiredUninstallerPackage)) {
15110            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15111                    + "\": required for package uninstallation");
15112            return false;
15113        }
15114
15115        if (packageName.equals(mRequiredVerifierPackage)) {
15116            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15117                    + "\": required for package verification");
15118            return false;
15119        }
15120
15121        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15122            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15123                    + "\": is the default dialer");
15124            return false;
15125        }
15126
15127        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15128            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15129                    + "\": protected package");
15130            return false;
15131        }
15132
15133        // Cannot suspend static shared libs as they are considered
15134        // a part of the using app (emulating static linking). Also
15135        // static libs are installed always on internal storage.
15136        PackageParser.Package pkg = mPackages.get(packageName);
15137        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15138            Slog.w(TAG, "Cannot suspend package: " + packageName
15139                    + " providing static shared library: "
15140                    + pkg.staticSharedLibName);
15141            return false;
15142        }
15143
15144        return true;
15145    }
15146
15147    private String getActiveLauncherPackageName(int userId) {
15148        Intent intent = new Intent(Intent.ACTION_MAIN);
15149        intent.addCategory(Intent.CATEGORY_HOME);
15150        ResolveInfo resolveInfo = resolveIntent(
15151                intent,
15152                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15153                PackageManager.MATCH_DEFAULT_ONLY,
15154                userId);
15155
15156        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15157    }
15158
15159    private String getDefaultDialerPackageName(int userId) {
15160        synchronized (mPackages) {
15161            return mSettings.getDefaultDialerPackageNameLPw(userId);
15162        }
15163    }
15164
15165    @Override
15166    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15167        mContext.enforceCallingOrSelfPermission(
15168                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15169                "Only package verification agents can verify applications");
15170
15171        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15172        final PackageVerificationResponse response = new PackageVerificationResponse(
15173                verificationCode, Binder.getCallingUid());
15174        msg.arg1 = id;
15175        msg.obj = response;
15176        mHandler.sendMessage(msg);
15177    }
15178
15179    @Override
15180    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15181            long millisecondsToDelay) {
15182        mContext.enforceCallingOrSelfPermission(
15183                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15184                "Only package verification agents can extend verification timeouts");
15185
15186        final PackageVerificationState state = mPendingVerification.get(id);
15187        final PackageVerificationResponse response = new PackageVerificationResponse(
15188                verificationCodeAtTimeout, Binder.getCallingUid());
15189
15190        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15191            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15192        }
15193        if (millisecondsToDelay < 0) {
15194            millisecondsToDelay = 0;
15195        }
15196        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15197                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15198            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15199        }
15200
15201        if ((state != null) && !state.timeoutExtended()) {
15202            state.extendTimeout();
15203
15204            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15205            msg.arg1 = id;
15206            msg.obj = response;
15207            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15208        }
15209    }
15210
15211    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15212            int verificationCode, UserHandle user) {
15213        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15214        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15215        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15216        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15217        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15218
15219        mContext.sendBroadcastAsUser(intent, user,
15220                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15221    }
15222
15223    private ComponentName matchComponentForVerifier(String packageName,
15224            List<ResolveInfo> receivers) {
15225        ActivityInfo targetReceiver = null;
15226
15227        final int NR = receivers.size();
15228        for (int i = 0; i < NR; i++) {
15229            final ResolveInfo info = receivers.get(i);
15230            if (info.activityInfo == null) {
15231                continue;
15232            }
15233
15234            if (packageName.equals(info.activityInfo.packageName)) {
15235                targetReceiver = info.activityInfo;
15236                break;
15237            }
15238        }
15239
15240        if (targetReceiver == null) {
15241            return null;
15242        }
15243
15244        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15245    }
15246
15247    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15248            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15249        if (pkgInfo.verifiers.length == 0) {
15250            return null;
15251        }
15252
15253        final int N = pkgInfo.verifiers.length;
15254        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15255        for (int i = 0; i < N; i++) {
15256            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15257
15258            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15259                    receivers);
15260            if (comp == null) {
15261                continue;
15262            }
15263
15264            final int verifierUid = getUidForVerifier(verifierInfo);
15265            if (verifierUid == -1) {
15266                continue;
15267            }
15268
15269            if (DEBUG_VERIFY) {
15270                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15271                        + " with the correct signature");
15272            }
15273            sufficientVerifiers.add(comp);
15274            verificationState.addSufficientVerifier(verifierUid);
15275        }
15276
15277        return sufficientVerifiers;
15278    }
15279
15280    private int getUidForVerifier(VerifierInfo verifierInfo) {
15281        synchronized (mPackages) {
15282            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15283            if (pkg == null) {
15284                return -1;
15285            } else if (pkg.mSignatures.length != 1) {
15286                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15287                        + " has more than one signature; ignoring");
15288                return -1;
15289            }
15290
15291            /*
15292             * If the public key of the package's signature does not match
15293             * our expected public key, then this is a different package and
15294             * we should skip.
15295             */
15296
15297            final byte[] expectedPublicKey;
15298            try {
15299                final Signature verifierSig = pkg.mSignatures[0];
15300                final PublicKey publicKey = verifierSig.getPublicKey();
15301                expectedPublicKey = publicKey.getEncoded();
15302            } catch (CertificateException e) {
15303                return -1;
15304            }
15305
15306            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15307
15308            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15309                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15310                        + " does not have the expected public key; ignoring");
15311                return -1;
15312            }
15313
15314            return pkg.applicationInfo.uid;
15315        }
15316    }
15317
15318    @Override
15319    public void finishPackageInstall(int token, boolean didLaunch) {
15320        enforceSystemOrRoot("Only the system is allowed to finish installs");
15321
15322        if (DEBUG_INSTALL) {
15323            Slog.v(TAG, "BM finishing package install for " + token);
15324        }
15325        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15326
15327        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15328        mHandler.sendMessage(msg);
15329    }
15330
15331    /**
15332     * Get the verification agent timeout.  Used for both the APK verifier and the
15333     * intent filter verifier.
15334     *
15335     * @return verification timeout in milliseconds
15336     */
15337    private long getVerificationTimeout() {
15338        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15339                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15340                DEFAULT_VERIFICATION_TIMEOUT);
15341    }
15342
15343    /**
15344     * Get the default verification agent response code.
15345     *
15346     * @return default verification response code
15347     */
15348    private int getDefaultVerificationResponse(UserHandle user) {
15349        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15350            return PackageManager.VERIFICATION_REJECT;
15351        }
15352        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15353                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15354                DEFAULT_VERIFICATION_RESPONSE);
15355    }
15356
15357    /**
15358     * Check whether or not package verification has been enabled.
15359     *
15360     * @return true if verification should be performed
15361     */
15362    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15363        if (!DEFAULT_VERIFY_ENABLE) {
15364            return false;
15365        }
15366
15367        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15368
15369        // Check if installing from ADB
15370        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15371            // Do not run verification in a test harness environment
15372            if (ActivityManager.isRunningInTestHarness()) {
15373                return false;
15374            }
15375            if (ensureVerifyAppsEnabled) {
15376                return true;
15377            }
15378            // Check if the developer does not want package verification for ADB installs
15379            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15380                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15381                return false;
15382            }
15383        } else {
15384            // only when not installed from ADB, skip verification for instant apps when
15385            // the installer and verifier are the same.
15386            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15387                if (mInstantAppInstallerActivity != null
15388                        && mInstantAppInstallerActivity.packageName.equals(
15389                                mRequiredVerifierPackage)) {
15390                    try {
15391                        mContext.getSystemService(AppOpsManager.class)
15392                                .checkPackage(installerUid, mRequiredVerifierPackage);
15393                        if (DEBUG_VERIFY) {
15394                            Slog.i(TAG, "disable verification for instant app");
15395                        }
15396                        return false;
15397                    } catch (SecurityException ignore) { }
15398                }
15399            }
15400        }
15401
15402        if (ensureVerifyAppsEnabled) {
15403            return true;
15404        }
15405
15406        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15407                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15408    }
15409
15410    @Override
15411    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15412            throws RemoteException {
15413        mContext.enforceCallingOrSelfPermission(
15414                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15415                "Only intentfilter verification agents can verify applications");
15416
15417        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15418        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15419                Binder.getCallingUid(), verificationCode, failedDomains);
15420        msg.arg1 = id;
15421        msg.obj = response;
15422        mHandler.sendMessage(msg);
15423    }
15424
15425    @Override
15426    public int getIntentVerificationStatus(String packageName, int userId) {
15427        final int callingUid = Binder.getCallingUid();
15428        if (UserHandle.getUserId(callingUid) != userId) {
15429            mContext.enforceCallingOrSelfPermission(
15430                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15431                    "getIntentVerificationStatus" + userId);
15432        }
15433        if (getInstantAppPackageName(callingUid) != null) {
15434            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15435        }
15436        synchronized (mPackages) {
15437            final PackageSetting ps = mSettings.mPackages.get(packageName);
15438            if (ps == null
15439                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15440                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15441            }
15442            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15443        }
15444    }
15445
15446    @Override
15447    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15448        mContext.enforceCallingOrSelfPermission(
15449                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15450
15451        boolean result = false;
15452        synchronized (mPackages) {
15453            final PackageSetting ps = mSettings.mPackages.get(packageName);
15454            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15455                return false;
15456            }
15457            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15458        }
15459        if (result) {
15460            scheduleWritePackageRestrictionsLocked(userId);
15461        }
15462        return result;
15463    }
15464
15465    @Override
15466    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15467            String packageName) {
15468        final int callingUid = Binder.getCallingUid();
15469        if (getInstantAppPackageName(callingUid) != null) {
15470            return ParceledListSlice.emptyList();
15471        }
15472        synchronized (mPackages) {
15473            final PackageSetting ps = mSettings.mPackages.get(packageName);
15474            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15475                return ParceledListSlice.emptyList();
15476            }
15477            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15478        }
15479    }
15480
15481    @Override
15482    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15483        if (TextUtils.isEmpty(packageName)) {
15484            return ParceledListSlice.emptyList();
15485        }
15486        final int callingUid = Binder.getCallingUid();
15487        final int callingUserId = UserHandle.getUserId(callingUid);
15488        synchronized (mPackages) {
15489            PackageParser.Package pkg = mPackages.get(packageName);
15490            if (pkg == null || pkg.activities == null) {
15491                return ParceledListSlice.emptyList();
15492            }
15493            if (pkg.mExtras == null) {
15494                return ParceledListSlice.emptyList();
15495            }
15496            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15497            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15498                return ParceledListSlice.emptyList();
15499            }
15500            final int count = pkg.activities.size();
15501            ArrayList<IntentFilter> result = new ArrayList<>();
15502            for (int n=0; n<count; n++) {
15503                PackageParser.Activity activity = pkg.activities.get(n);
15504                if (activity.intents != null && activity.intents.size() > 0) {
15505                    result.addAll(activity.intents);
15506                }
15507            }
15508            return new ParceledListSlice<>(result);
15509        }
15510    }
15511
15512    @Override
15513    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15514        mContext.enforceCallingOrSelfPermission(
15515                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15516        if (UserHandle.getCallingUserId() != userId) {
15517            mContext.enforceCallingOrSelfPermission(
15518                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15519        }
15520
15521        synchronized (mPackages) {
15522            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15523            if (packageName != null) {
15524                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15525                        packageName, userId);
15526            }
15527            return result;
15528        }
15529    }
15530
15531    @Override
15532    public String getDefaultBrowserPackageName(int userId) {
15533        if (UserHandle.getCallingUserId() != userId) {
15534            mContext.enforceCallingOrSelfPermission(
15535                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15536        }
15537        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15538            return null;
15539        }
15540        synchronized (mPackages) {
15541            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15542        }
15543    }
15544
15545    /**
15546     * Get the "allow unknown sources" setting.
15547     *
15548     * @return the current "allow unknown sources" setting
15549     */
15550    private int getUnknownSourcesSettings() {
15551        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15552                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15553                -1);
15554    }
15555
15556    @Override
15557    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15558        final int callingUid = Binder.getCallingUid();
15559        if (getInstantAppPackageName(callingUid) != null) {
15560            return;
15561        }
15562        // writer
15563        synchronized (mPackages) {
15564            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15565            if (targetPackageSetting == null
15566                    || filterAppAccessLPr(
15567                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15568                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15569            }
15570
15571            PackageSetting installerPackageSetting;
15572            if (installerPackageName != null) {
15573                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15574                if (installerPackageSetting == null) {
15575                    throw new IllegalArgumentException("Unknown installer package: "
15576                            + installerPackageName);
15577                }
15578            } else {
15579                installerPackageSetting = null;
15580            }
15581
15582            Signature[] callerSignature;
15583            Object obj = mSettings.getUserIdLPr(callingUid);
15584            if (obj != null) {
15585                if (obj instanceof SharedUserSetting) {
15586                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15587                } else if (obj instanceof PackageSetting) {
15588                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15589                } else {
15590                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15591                }
15592            } else {
15593                throw new SecurityException("Unknown calling UID: " + callingUid);
15594            }
15595
15596            // Verify: can't set installerPackageName to a package that is
15597            // not signed with the same cert as the caller.
15598            if (installerPackageSetting != null) {
15599                if (compareSignatures(callerSignature,
15600                        installerPackageSetting.signatures.mSignatures)
15601                        != PackageManager.SIGNATURE_MATCH) {
15602                    throw new SecurityException(
15603                            "Caller does not have same cert as new installer package "
15604                            + installerPackageName);
15605                }
15606            }
15607
15608            // Verify: if target already has an installer package, it must
15609            // be signed with the same cert as the caller.
15610            if (targetPackageSetting.installerPackageName != null) {
15611                PackageSetting setting = mSettings.mPackages.get(
15612                        targetPackageSetting.installerPackageName);
15613                // If the currently set package isn't valid, then it's always
15614                // okay to change it.
15615                if (setting != null) {
15616                    if (compareSignatures(callerSignature,
15617                            setting.signatures.mSignatures)
15618                            != PackageManager.SIGNATURE_MATCH) {
15619                        throw new SecurityException(
15620                                "Caller does not have same cert as old installer package "
15621                                + targetPackageSetting.installerPackageName);
15622                    }
15623                }
15624            }
15625
15626            // Okay!
15627            targetPackageSetting.installerPackageName = installerPackageName;
15628            if (installerPackageName != null) {
15629                mSettings.mInstallerPackages.add(installerPackageName);
15630            }
15631            scheduleWriteSettingsLocked();
15632        }
15633    }
15634
15635    @Override
15636    public void setApplicationCategoryHint(String packageName, int categoryHint,
15637            String callerPackageName) {
15638        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15639            throw new SecurityException("Instant applications don't have access to this method");
15640        }
15641        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15642                callerPackageName);
15643        synchronized (mPackages) {
15644            PackageSetting ps = mSettings.mPackages.get(packageName);
15645            if (ps == null) {
15646                throw new IllegalArgumentException("Unknown target package " + packageName);
15647            }
15648            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15649                throw new IllegalArgumentException("Unknown target package " + packageName);
15650            }
15651            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15652                throw new IllegalArgumentException("Calling package " + callerPackageName
15653                        + " is not installer for " + packageName);
15654            }
15655
15656            if (ps.categoryHint != categoryHint) {
15657                ps.categoryHint = categoryHint;
15658                scheduleWriteSettingsLocked();
15659            }
15660        }
15661    }
15662
15663    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15664        // Queue up an async operation since the package installation may take a little while.
15665        mHandler.post(new Runnable() {
15666            public void run() {
15667                mHandler.removeCallbacks(this);
15668                 // Result object to be returned
15669                PackageInstalledInfo res = new PackageInstalledInfo();
15670                res.setReturnCode(currentStatus);
15671                res.uid = -1;
15672                res.pkg = null;
15673                res.removedInfo = null;
15674                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15675                    args.doPreInstall(res.returnCode);
15676                    synchronized (mInstallLock) {
15677                        installPackageTracedLI(args, res);
15678                    }
15679                    args.doPostInstall(res.returnCode, res.uid);
15680                }
15681
15682                // A restore should be performed at this point if (a) the install
15683                // succeeded, (b) the operation is not an update, and (c) the new
15684                // package has not opted out of backup participation.
15685                final boolean update = res.removedInfo != null
15686                        && res.removedInfo.removedPackage != null;
15687                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15688                boolean doRestore = !update
15689                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15690
15691                // Set up the post-install work request bookkeeping.  This will be used
15692                // and cleaned up by the post-install event handling regardless of whether
15693                // there's a restore pass performed.  Token values are >= 1.
15694                int token;
15695                if (mNextInstallToken < 0) mNextInstallToken = 1;
15696                token = mNextInstallToken++;
15697
15698                PostInstallData data = new PostInstallData(args, res);
15699                mRunningInstalls.put(token, data);
15700                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15701
15702                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15703                    // Pass responsibility to the Backup Manager.  It will perform a
15704                    // restore if appropriate, then pass responsibility back to the
15705                    // Package Manager to run the post-install observer callbacks
15706                    // and broadcasts.
15707                    IBackupManager bm = IBackupManager.Stub.asInterface(
15708                            ServiceManager.getService(Context.BACKUP_SERVICE));
15709                    if (bm != null) {
15710                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15711                                + " to BM for possible restore");
15712                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15713                        try {
15714                            // TODO: http://b/22388012
15715                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15716                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15717                            } else {
15718                                doRestore = false;
15719                            }
15720                        } catch (RemoteException e) {
15721                            // can't happen; the backup manager is local
15722                        } catch (Exception e) {
15723                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15724                            doRestore = false;
15725                        }
15726                    } else {
15727                        Slog.e(TAG, "Backup Manager not found!");
15728                        doRestore = false;
15729                    }
15730                }
15731
15732                if (!doRestore) {
15733                    // No restore possible, or the Backup Manager was mysteriously not
15734                    // available -- just fire the post-install work request directly.
15735                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15736
15737                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15738
15739                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15740                    mHandler.sendMessage(msg);
15741                }
15742            }
15743        });
15744    }
15745
15746    /**
15747     * Callback from PackageSettings whenever an app is first transitioned out of the
15748     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15749     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15750     * here whether the app is the target of an ongoing install, and only send the
15751     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15752     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15753     * handling.
15754     */
15755    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15756        // Serialize this with the rest of the install-process message chain.  In the
15757        // restore-at-install case, this Runnable will necessarily run before the
15758        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15759        // are coherent.  In the non-restore case, the app has already completed install
15760        // and been launched through some other means, so it is not in a problematic
15761        // state for observers to see the FIRST_LAUNCH signal.
15762        mHandler.post(new Runnable() {
15763            @Override
15764            public void run() {
15765                for (int i = 0; i < mRunningInstalls.size(); i++) {
15766                    final PostInstallData data = mRunningInstalls.valueAt(i);
15767                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15768                        continue;
15769                    }
15770                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15771                        // right package; but is it for the right user?
15772                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15773                            if (userId == data.res.newUsers[uIndex]) {
15774                                if (DEBUG_BACKUP) {
15775                                    Slog.i(TAG, "Package " + pkgName
15776                                            + " being restored so deferring FIRST_LAUNCH");
15777                                }
15778                                return;
15779                            }
15780                        }
15781                    }
15782                }
15783                // didn't find it, so not being restored
15784                if (DEBUG_BACKUP) {
15785                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15786                }
15787                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15788            }
15789        });
15790    }
15791
15792    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15793        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15794                installerPkg, null, userIds);
15795    }
15796
15797    private abstract class HandlerParams {
15798        private static final int MAX_RETRIES = 4;
15799
15800        /**
15801         * Number of times startCopy() has been attempted and had a non-fatal
15802         * error.
15803         */
15804        private int mRetries = 0;
15805
15806        /** User handle for the user requesting the information or installation. */
15807        private final UserHandle mUser;
15808        String traceMethod;
15809        int traceCookie;
15810
15811        HandlerParams(UserHandle user) {
15812            mUser = user;
15813        }
15814
15815        UserHandle getUser() {
15816            return mUser;
15817        }
15818
15819        HandlerParams setTraceMethod(String traceMethod) {
15820            this.traceMethod = traceMethod;
15821            return this;
15822        }
15823
15824        HandlerParams setTraceCookie(int traceCookie) {
15825            this.traceCookie = traceCookie;
15826            return this;
15827        }
15828
15829        final boolean startCopy() {
15830            boolean res;
15831            try {
15832                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15833
15834                if (++mRetries > MAX_RETRIES) {
15835                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15836                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15837                    handleServiceError();
15838                    return false;
15839                } else {
15840                    handleStartCopy();
15841                    res = true;
15842                }
15843            } catch (RemoteException e) {
15844                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15845                mHandler.sendEmptyMessage(MCS_RECONNECT);
15846                res = false;
15847            }
15848            handleReturnCode();
15849            return res;
15850        }
15851
15852        final void serviceError() {
15853            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15854            handleServiceError();
15855            handleReturnCode();
15856        }
15857
15858        abstract void handleStartCopy() throws RemoteException;
15859        abstract void handleServiceError();
15860        abstract void handleReturnCode();
15861    }
15862
15863    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15864        for (File path : paths) {
15865            try {
15866                mcs.clearDirectory(path.getAbsolutePath());
15867            } catch (RemoteException e) {
15868            }
15869        }
15870    }
15871
15872    static class OriginInfo {
15873        /**
15874         * Location where install is coming from, before it has been
15875         * copied/renamed into place. This could be a single monolithic APK
15876         * file, or a cluster directory. This location may be untrusted.
15877         */
15878        final File file;
15879        final String cid;
15880
15881        /**
15882         * Flag indicating that {@link #file} or {@link #cid} has already been
15883         * staged, meaning downstream users don't need to defensively copy the
15884         * contents.
15885         */
15886        final boolean staged;
15887
15888        /**
15889         * Flag indicating that {@link #file} or {@link #cid} is an already
15890         * installed app that is being moved.
15891         */
15892        final boolean existing;
15893
15894        final String resolvedPath;
15895        final File resolvedFile;
15896
15897        static OriginInfo fromNothing() {
15898            return new OriginInfo(null, null, false, false);
15899        }
15900
15901        static OriginInfo fromUntrustedFile(File file) {
15902            return new OriginInfo(file, null, false, false);
15903        }
15904
15905        static OriginInfo fromExistingFile(File file) {
15906            return new OriginInfo(file, null, false, true);
15907        }
15908
15909        static OriginInfo fromStagedFile(File file) {
15910            return new OriginInfo(file, null, true, false);
15911        }
15912
15913        static OriginInfo fromStagedContainer(String cid) {
15914            return new OriginInfo(null, cid, true, false);
15915        }
15916
15917        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15918            this.file = file;
15919            this.cid = cid;
15920            this.staged = staged;
15921            this.existing = existing;
15922
15923            if (cid != null) {
15924                resolvedPath = PackageHelper.getSdDir(cid);
15925                resolvedFile = new File(resolvedPath);
15926            } else if (file != null) {
15927                resolvedPath = file.getAbsolutePath();
15928                resolvedFile = file;
15929            } else {
15930                resolvedPath = null;
15931                resolvedFile = null;
15932            }
15933        }
15934    }
15935
15936    static class MoveInfo {
15937        final int moveId;
15938        final String fromUuid;
15939        final String toUuid;
15940        final String packageName;
15941        final String dataAppName;
15942        final int appId;
15943        final String seinfo;
15944        final int targetSdkVersion;
15945
15946        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15947                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15948            this.moveId = moveId;
15949            this.fromUuid = fromUuid;
15950            this.toUuid = toUuid;
15951            this.packageName = packageName;
15952            this.dataAppName = dataAppName;
15953            this.appId = appId;
15954            this.seinfo = seinfo;
15955            this.targetSdkVersion = targetSdkVersion;
15956        }
15957    }
15958
15959    static class VerificationInfo {
15960        /** A constant used to indicate that a uid value is not present. */
15961        public static final int NO_UID = -1;
15962
15963        /** URI referencing where the package was downloaded from. */
15964        final Uri originatingUri;
15965
15966        /** HTTP referrer URI associated with the originatingURI. */
15967        final Uri referrer;
15968
15969        /** UID of the application that the install request originated from. */
15970        final int originatingUid;
15971
15972        /** UID of application requesting the install */
15973        final int installerUid;
15974
15975        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15976            this.originatingUri = originatingUri;
15977            this.referrer = referrer;
15978            this.originatingUid = originatingUid;
15979            this.installerUid = installerUid;
15980        }
15981    }
15982
15983    class InstallParams extends HandlerParams {
15984        final OriginInfo origin;
15985        final MoveInfo move;
15986        final IPackageInstallObserver2 observer;
15987        int installFlags;
15988        final String installerPackageName;
15989        final String volumeUuid;
15990        private InstallArgs mArgs;
15991        private int mRet;
15992        final String packageAbiOverride;
15993        final String[] grantedRuntimePermissions;
15994        final VerificationInfo verificationInfo;
15995        final Certificate[][] certificates;
15996        final int installReason;
15997
15998        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15999                int installFlags, String installerPackageName, String volumeUuid,
16000                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16001                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16002            super(user);
16003            this.origin = origin;
16004            this.move = move;
16005            this.observer = observer;
16006            this.installFlags = installFlags;
16007            this.installerPackageName = installerPackageName;
16008            this.volumeUuid = volumeUuid;
16009            this.verificationInfo = verificationInfo;
16010            this.packageAbiOverride = packageAbiOverride;
16011            this.grantedRuntimePermissions = grantedPermissions;
16012            this.certificates = certificates;
16013            this.installReason = installReason;
16014        }
16015
16016        @Override
16017        public String toString() {
16018            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16019                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16020        }
16021
16022        private int installLocationPolicy(PackageInfoLite pkgLite) {
16023            String packageName = pkgLite.packageName;
16024            int installLocation = pkgLite.installLocation;
16025            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16026            // reader
16027            synchronized (mPackages) {
16028                // Currently installed package which the new package is attempting to replace or
16029                // null if no such package is installed.
16030                PackageParser.Package installedPkg = mPackages.get(packageName);
16031                // Package which currently owns the data which the new package will own if installed.
16032                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16033                // will be null whereas dataOwnerPkg will contain information about the package
16034                // which was uninstalled while keeping its data.
16035                PackageParser.Package dataOwnerPkg = installedPkg;
16036                if (dataOwnerPkg  == null) {
16037                    PackageSetting ps = mSettings.mPackages.get(packageName);
16038                    if (ps != null) {
16039                        dataOwnerPkg = ps.pkg;
16040                    }
16041                }
16042
16043                if (dataOwnerPkg != null) {
16044                    // If installed, the package will get access to data left on the device by its
16045                    // predecessor. As a security measure, this is permited only if this is not a
16046                    // version downgrade or if the predecessor package is marked as debuggable and
16047                    // a downgrade is explicitly requested.
16048                    //
16049                    // On debuggable platform builds, downgrades are permitted even for
16050                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16051                    // not offer security guarantees and thus it's OK to disable some security
16052                    // mechanisms to make debugging/testing easier on those builds. However, even on
16053                    // debuggable builds downgrades of packages are permitted only if requested via
16054                    // installFlags. This is because we aim to keep the behavior of debuggable
16055                    // platform builds as close as possible to the behavior of non-debuggable
16056                    // platform builds.
16057                    final boolean downgradeRequested =
16058                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16059                    final boolean packageDebuggable =
16060                                (dataOwnerPkg.applicationInfo.flags
16061                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16062                    final boolean downgradePermitted =
16063                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16064                    if (!downgradePermitted) {
16065                        try {
16066                            checkDowngrade(dataOwnerPkg, pkgLite);
16067                        } catch (PackageManagerException e) {
16068                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16069                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16070                        }
16071                    }
16072                }
16073
16074                if (installedPkg != null) {
16075                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16076                        // Check for updated system application.
16077                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16078                            if (onSd) {
16079                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16080                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16081                            }
16082                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16083                        } else {
16084                            if (onSd) {
16085                                // Install flag overrides everything.
16086                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16087                            }
16088                            // If current upgrade specifies particular preference
16089                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16090                                // Application explicitly specified internal.
16091                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16092                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16093                                // App explictly prefers external. Let policy decide
16094                            } else {
16095                                // Prefer previous location
16096                                if (isExternal(installedPkg)) {
16097                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16098                                }
16099                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16100                            }
16101                        }
16102                    } else {
16103                        // Invalid install. Return error code
16104                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16105                    }
16106                }
16107            }
16108            // All the special cases have been taken care of.
16109            // Return result based on recommended install location.
16110            if (onSd) {
16111                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16112            }
16113            return pkgLite.recommendedInstallLocation;
16114        }
16115
16116        /*
16117         * Invoke remote method to get package information and install
16118         * location values. Override install location based on default
16119         * policy if needed and then create install arguments based
16120         * on the install location.
16121         */
16122        public void handleStartCopy() throws RemoteException {
16123            int ret = PackageManager.INSTALL_SUCCEEDED;
16124
16125            // If we're already staged, we've firmly committed to an install location
16126            if (origin.staged) {
16127                if (origin.file != null) {
16128                    installFlags |= PackageManager.INSTALL_INTERNAL;
16129                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16130                } else if (origin.cid != null) {
16131                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16132                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16133                } else {
16134                    throw new IllegalStateException("Invalid stage location");
16135                }
16136            }
16137
16138            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16139            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16140            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16141            PackageInfoLite pkgLite = null;
16142
16143            if (onInt && onSd) {
16144                // Check if both bits are set.
16145                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16146                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16147            } else if (onSd && ephemeral) {
16148                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16149                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16150            } else {
16151                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16152                        packageAbiOverride);
16153
16154                if (DEBUG_EPHEMERAL && ephemeral) {
16155                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16156                }
16157
16158                /*
16159                 * If we have too little free space, try to free cache
16160                 * before giving up.
16161                 */
16162                if (!origin.staged && pkgLite.recommendedInstallLocation
16163                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16164                    // TODO: focus freeing disk space on the target device
16165                    final StorageManager storage = StorageManager.from(mContext);
16166                    final long lowThreshold = storage.getStorageLowBytes(
16167                            Environment.getDataDirectory());
16168
16169                    final long sizeBytes = mContainerService.calculateInstalledSize(
16170                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16171
16172                    try {
16173                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16174                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16175                                installFlags, packageAbiOverride);
16176                    } catch (InstallerException e) {
16177                        Slog.w(TAG, "Failed to free cache", e);
16178                    }
16179
16180                    /*
16181                     * The cache free must have deleted the file we
16182                     * downloaded to install.
16183                     *
16184                     * TODO: fix the "freeCache" call to not delete
16185                     *       the file we care about.
16186                     */
16187                    if (pkgLite.recommendedInstallLocation
16188                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16189                        pkgLite.recommendedInstallLocation
16190                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16191                    }
16192                }
16193            }
16194
16195            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16196                int loc = pkgLite.recommendedInstallLocation;
16197                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16198                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16199                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16200                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16201                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16202                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16203                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16204                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16205                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16206                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16207                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16208                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16209                } else {
16210                    // Override with defaults if needed.
16211                    loc = installLocationPolicy(pkgLite);
16212                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16213                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16214                    } else if (!onSd && !onInt) {
16215                        // Override install location with flags
16216                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16217                            // Set the flag to install on external media.
16218                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16219                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16220                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16221                            if (DEBUG_EPHEMERAL) {
16222                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16223                            }
16224                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16225                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16226                                    |PackageManager.INSTALL_INTERNAL);
16227                        } else {
16228                            // Make sure the flag for installing on external
16229                            // media is unset
16230                            installFlags |= PackageManager.INSTALL_INTERNAL;
16231                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16232                        }
16233                    }
16234                }
16235            }
16236
16237            final InstallArgs args = createInstallArgs(this);
16238            mArgs = args;
16239
16240            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16241                // TODO: http://b/22976637
16242                // Apps installed for "all" users use the device owner to verify the app
16243                UserHandle verifierUser = getUser();
16244                if (verifierUser == UserHandle.ALL) {
16245                    verifierUser = UserHandle.SYSTEM;
16246                }
16247
16248                /*
16249                 * Determine if we have any installed package verifiers. If we
16250                 * do, then we'll defer to them to verify the packages.
16251                 */
16252                final int requiredUid = mRequiredVerifierPackage == null ? -1
16253                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16254                                verifierUser.getIdentifier());
16255                final int installerUid =
16256                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16257                if (!origin.existing && requiredUid != -1
16258                        && isVerificationEnabled(
16259                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16260                    final Intent verification = new Intent(
16261                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16262                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16263                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16264                            PACKAGE_MIME_TYPE);
16265                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16266
16267                    // Query all live verifiers based on current user state
16268                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16269                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16270                            false /*allowDynamicSplits*/);
16271
16272                    if (DEBUG_VERIFY) {
16273                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16274                                + verification.toString() + " with " + pkgLite.verifiers.length
16275                                + " optional verifiers");
16276                    }
16277
16278                    final int verificationId = mPendingVerificationToken++;
16279
16280                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16281
16282                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16283                            installerPackageName);
16284
16285                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16286                            installFlags);
16287
16288                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16289                            pkgLite.packageName);
16290
16291                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16292                            pkgLite.versionCode);
16293
16294                    if (verificationInfo != null) {
16295                        if (verificationInfo.originatingUri != null) {
16296                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16297                                    verificationInfo.originatingUri);
16298                        }
16299                        if (verificationInfo.referrer != null) {
16300                            verification.putExtra(Intent.EXTRA_REFERRER,
16301                                    verificationInfo.referrer);
16302                        }
16303                        if (verificationInfo.originatingUid >= 0) {
16304                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16305                                    verificationInfo.originatingUid);
16306                        }
16307                        if (verificationInfo.installerUid >= 0) {
16308                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16309                                    verificationInfo.installerUid);
16310                        }
16311                    }
16312
16313                    final PackageVerificationState verificationState = new PackageVerificationState(
16314                            requiredUid, args);
16315
16316                    mPendingVerification.append(verificationId, verificationState);
16317
16318                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16319                            receivers, verificationState);
16320
16321                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16322                    final long idleDuration = getVerificationTimeout();
16323
16324                    /*
16325                     * If any sufficient verifiers were listed in the package
16326                     * manifest, attempt to ask them.
16327                     */
16328                    if (sufficientVerifiers != null) {
16329                        final int N = sufficientVerifiers.size();
16330                        if (N == 0) {
16331                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16332                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16333                        } else {
16334                            for (int i = 0; i < N; i++) {
16335                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16336                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16337                                        verifierComponent.getPackageName(), idleDuration,
16338                                        verifierUser.getIdentifier(), false, "package verifier");
16339
16340                                final Intent sufficientIntent = new Intent(verification);
16341                                sufficientIntent.setComponent(verifierComponent);
16342                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16343                            }
16344                        }
16345                    }
16346
16347                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16348                            mRequiredVerifierPackage, receivers);
16349                    if (ret == PackageManager.INSTALL_SUCCEEDED
16350                            && mRequiredVerifierPackage != null) {
16351                        Trace.asyncTraceBegin(
16352                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16353                        /*
16354                         * Send the intent to the required verification agent,
16355                         * but only start the verification timeout after the
16356                         * target BroadcastReceivers have run.
16357                         */
16358                        verification.setComponent(requiredVerifierComponent);
16359                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16360                                mRequiredVerifierPackage, idleDuration,
16361                                verifierUser.getIdentifier(), false, "package verifier");
16362                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16363                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16364                                new BroadcastReceiver() {
16365                                    @Override
16366                                    public void onReceive(Context context, Intent intent) {
16367                                        final Message msg = mHandler
16368                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16369                                        msg.arg1 = verificationId;
16370                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16371                                    }
16372                                }, null, 0, null, null);
16373
16374                        /*
16375                         * We don't want the copy to proceed until verification
16376                         * succeeds, so null out this field.
16377                         */
16378                        mArgs = null;
16379                    }
16380                } else {
16381                    /*
16382                     * No package verification is enabled, so immediately start
16383                     * the remote call to initiate copy using temporary file.
16384                     */
16385                    ret = args.copyApk(mContainerService, true);
16386                }
16387            }
16388
16389            mRet = ret;
16390        }
16391
16392        @Override
16393        void handleReturnCode() {
16394            // If mArgs is null, then MCS couldn't be reached. When it
16395            // reconnects, it will try again to install. At that point, this
16396            // will succeed.
16397            if (mArgs != null) {
16398                processPendingInstall(mArgs, mRet);
16399            }
16400        }
16401
16402        @Override
16403        void handleServiceError() {
16404            mArgs = createInstallArgs(this);
16405            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16406        }
16407
16408        public boolean isForwardLocked() {
16409            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16410        }
16411    }
16412
16413    /**
16414     * Used during creation of InstallArgs
16415     *
16416     * @param installFlags package installation flags
16417     * @return true if should be installed on external storage
16418     */
16419    private static boolean installOnExternalAsec(int installFlags) {
16420        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16421            return false;
16422        }
16423        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16424            return true;
16425        }
16426        return false;
16427    }
16428
16429    /**
16430     * Used during creation of InstallArgs
16431     *
16432     * @param installFlags package installation flags
16433     * @return true if should be installed as forward locked
16434     */
16435    private static boolean installForwardLocked(int installFlags) {
16436        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16437    }
16438
16439    private InstallArgs createInstallArgs(InstallParams params) {
16440        if (params.move != null) {
16441            return new MoveInstallArgs(params);
16442        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16443            return new AsecInstallArgs(params);
16444        } else {
16445            return new FileInstallArgs(params);
16446        }
16447    }
16448
16449    /**
16450     * Create args that describe an existing installed package. Typically used
16451     * when cleaning up old installs, or used as a move source.
16452     */
16453    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16454            String resourcePath, String[] instructionSets) {
16455        final boolean isInAsec;
16456        if (installOnExternalAsec(installFlags)) {
16457            /* Apps on SD card are always in ASEC containers. */
16458            isInAsec = true;
16459        } else if (installForwardLocked(installFlags)
16460                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16461            /*
16462             * Forward-locked apps are only in ASEC containers if they're the
16463             * new style
16464             */
16465            isInAsec = true;
16466        } else {
16467            isInAsec = false;
16468        }
16469
16470        if (isInAsec) {
16471            return new AsecInstallArgs(codePath, instructionSets,
16472                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16473        } else {
16474            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16475        }
16476    }
16477
16478    static abstract class InstallArgs {
16479        /** @see InstallParams#origin */
16480        final OriginInfo origin;
16481        /** @see InstallParams#move */
16482        final MoveInfo move;
16483
16484        final IPackageInstallObserver2 observer;
16485        // Always refers to PackageManager flags only
16486        final int installFlags;
16487        final String installerPackageName;
16488        final String volumeUuid;
16489        final UserHandle user;
16490        final String abiOverride;
16491        final String[] installGrantPermissions;
16492        /** If non-null, drop an async trace when the install completes */
16493        final String traceMethod;
16494        final int traceCookie;
16495        final Certificate[][] certificates;
16496        final int installReason;
16497
16498        // The list of instruction sets supported by this app. This is currently
16499        // only used during the rmdex() phase to clean up resources. We can get rid of this
16500        // if we move dex files under the common app path.
16501        /* nullable */ String[] instructionSets;
16502
16503        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16504                int installFlags, String installerPackageName, String volumeUuid,
16505                UserHandle user, String[] instructionSets,
16506                String abiOverride, String[] installGrantPermissions,
16507                String traceMethod, int traceCookie, Certificate[][] certificates,
16508                int installReason) {
16509            this.origin = origin;
16510            this.move = move;
16511            this.installFlags = installFlags;
16512            this.observer = observer;
16513            this.installerPackageName = installerPackageName;
16514            this.volumeUuid = volumeUuid;
16515            this.user = user;
16516            this.instructionSets = instructionSets;
16517            this.abiOverride = abiOverride;
16518            this.installGrantPermissions = installGrantPermissions;
16519            this.traceMethod = traceMethod;
16520            this.traceCookie = traceCookie;
16521            this.certificates = certificates;
16522            this.installReason = installReason;
16523        }
16524
16525        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16526        abstract int doPreInstall(int status);
16527
16528        /**
16529         * Rename package into final resting place. All paths on the given
16530         * scanned package should be updated to reflect the rename.
16531         */
16532        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16533        abstract int doPostInstall(int status, int uid);
16534
16535        /** @see PackageSettingBase#codePathString */
16536        abstract String getCodePath();
16537        /** @see PackageSettingBase#resourcePathString */
16538        abstract String getResourcePath();
16539
16540        // Need installer lock especially for dex file removal.
16541        abstract void cleanUpResourcesLI();
16542        abstract boolean doPostDeleteLI(boolean delete);
16543
16544        /**
16545         * Called before the source arguments are copied. This is used mostly
16546         * for MoveParams when it needs to read the source file to put it in the
16547         * destination.
16548         */
16549        int doPreCopy() {
16550            return PackageManager.INSTALL_SUCCEEDED;
16551        }
16552
16553        /**
16554         * Called after the source arguments are copied. This is used mostly for
16555         * MoveParams when it needs to read the source file to put it in the
16556         * destination.
16557         */
16558        int doPostCopy(int uid) {
16559            return PackageManager.INSTALL_SUCCEEDED;
16560        }
16561
16562        protected boolean isFwdLocked() {
16563            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16564        }
16565
16566        protected boolean isExternalAsec() {
16567            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16568        }
16569
16570        protected boolean isEphemeral() {
16571            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16572        }
16573
16574        UserHandle getUser() {
16575            return user;
16576        }
16577    }
16578
16579    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16580        if (!allCodePaths.isEmpty()) {
16581            if (instructionSets == null) {
16582                throw new IllegalStateException("instructionSet == null");
16583            }
16584            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16585            for (String codePath : allCodePaths) {
16586                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16587                    try {
16588                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16589                    } catch (InstallerException ignored) {
16590                    }
16591                }
16592            }
16593        }
16594    }
16595
16596    /**
16597     * Logic to handle installation of non-ASEC applications, including copying
16598     * and renaming logic.
16599     */
16600    class FileInstallArgs extends InstallArgs {
16601        private File codeFile;
16602        private File resourceFile;
16603
16604        // Example topology:
16605        // /data/app/com.example/base.apk
16606        // /data/app/com.example/split_foo.apk
16607        // /data/app/com.example/lib/arm/libfoo.so
16608        // /data/app/com.example/lib/arm64/libfoo.so
16609        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16610
16611        /** New install */
16612        FileInstallArgs(InstallParams params) {
16613            super(params.origin, params.move, params.observer, params.installFlags,
16614                    params.installerPackageName, params.volumeUuid,
16615                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16616                    params.grantedRuntimePermissions,
16617                    params.traceMethod, params.traceCookie, params.certificates,
16618                    params.installReason);
16619            if (isFwdLocked()) {
16620                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16621            }
16622        }
16623
16624        /** Existing install */
16625        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16626            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16627                    null, null, null, 0, null /*certificates*/,
16628                    PackageManager.INSTALL_REASON_UNKNOWN);
16629            this.codeFile = (codePath != null) ? new File(codePath) : null;
16630            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16631        }
16632
16633        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16634            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16635            try {
16636                return doCopyApk(imcs, temp);
16637            } finally {
16638                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16639            }
16640        }
16641
16642        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16643            if (origin.staged) {
16644                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16645                codeFile = origin.file;
16646                resourceFile = origin.file;
16647                return PackageManager.INSTALL_SUCCEEDED;
16648            }
16649
16650            try {
16651                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16652                final File tempDir =
16653                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16654                codeFile = tempDir;
16655                resourceFile = tempDir;
16656            } catch (IOException e) {
16657                Slog.w(TAG, "Failed to create copy file: " + e);
16658                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16659            }
16660
16661            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16662                @Override
16663                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16664                    if (!FileUtils.isValidExtFilename(name)) {
16665                        throw new IllegalArgumentException("Invalid filename: " + name);
16666                    }
16667                    try {
16668                        final File file = new File(codeFile, name);
16669                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16670                                O_RDWR | O_CREAT, 0644);
16671                        Os.chmod(file.getAbsolutePath(), 0644);
16672                        return new ParcelFileDescriptor(fd);
16673                    } catch (ErrnoException e) {
16674                        throw new RemoteException("Failed to open: " + e.getMessage());
16675                    }
16676                }
16677            };
16678
16679            int ret = PackageManager.INSTALL_SUCCEEDED;
16680            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16681            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16682                Slog.e(TAG, "Failed to copy package");
16683                return ret;
16684            }
16685
16686            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16687            NativeLibraryHelper.Handle handle = null;
16688            try {
16689                handle = NativeLibraryHelper.Handle.create(codeFile);
16690                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16691                        abiOverride);
16692            } catch (IOException e) {
16693                Slog.e(TAG, "Copying native libraries failed", e);
16694                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16695            } finally {
16696                IoUtils.closeQuietly(handle);
16697            }
16698
16699            return ret;
16700        }
16701
16702        int doPreInstall(int status) {
16703            if (status != PackageManager.INSTALL_SUCCEEDED) {
16704                cleanUp();
16705            }
16706            return status;
16707        }
16708
16709        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16710            if (status != PackageManager.INSTALL_SUCCEEDED) {
16711                cleanUp();
16712                return false;
16713            }
16714
16715            final File targetDir = codeFile.getParentFile();
16716            final File beforeCodeFile = codeFile;
16717            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16718
16719            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16720            try {
16721                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16722            } catch (ErrnoException e) {
16723                Slog.w(TAG, "Failed to rename", e);
16724                return false;
16725            }
16726
16727            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16728                Slog.w(TAG, "Failed to restorecon");
16729                return false;
16730            }
16731
16732            // Reflect the rename internally
16733            codeFile = afterCodeFile;
16734            resourceFile = afterCodeFile;
16735
16736            // Reflect the rename in scanned details
16737            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16738            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16739                    afterCodeFile, pkg.baseCodePath));
16740            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16741                    afterCodeFile, pkg.splitCodePaths));
16742
16743            // Reflect the rename in app info
16744            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16745            pkg.setApplicationInfoCodePath(pkg.codePath);
16746            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16747            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16748            pkg.setApplicationInfoResourcePath(pkg.codePath);
16749            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16750            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16751
16752            return true;
16753        }
16754
16755        int doPostInstall(int status, int uid) {
16756            if (status != PackageManager.INSTALL_SUCCEEDED) {
16757                cleanUp();
16758            }
16759            return status;
16760        }
16761
16762        @Override
16763        String getCodePath() {
16764            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16765        }
16766
16767        @Override
16768        String getResourcePath() {
16769            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16770        }
16771
16772        private boolean cleanUp() {
16773            if (codeFile == null || !codeFile.exists()) {
16774                return false;
16775            }
16776
16777            removeCodePathLI(codeFile);
16778
16779            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16780                resourceFile.delete();
16781            }
16782
16783            return true;
16784        }
16785
16786        void cleanUpResourcesLI() {
16787            // Try enumerating all code paths before deleting
16788            List<String> allCodePaths = Collections.EMPTY_LIST;
16789            if (codeFile != null && codeFile.exists()) {
16790                try {
16791                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16792                    allCodePaths = pkg.getAllCodePaths();
16793                } catch (PackageParserException e) {
16794                    // Ignored; we tried our best
16795                }
16796            }
16797
16798            cleanUp();
16799            removeDexFiles(allCodePaths, instructionSets);
16800        }
16801
16802        boolean doPostDeleteLI(boolean delete) {
16803            // XXX err, shouldn't we respect the delete flag?
16804            cleanUpResourcesLI();
16805            return true;
16806        }
16807    }
16808
16809    private boolean isAsecExternal(String cid) {
16810        final String asecPath = PackageHelper.getSdFilesystem(cid);
16811        return !asecPath.startsWith(mAsecInternalPath);
16812    }
16813
16814    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16815            PackageManagerException {
16816        if (copyRet < 0) {
16817            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16818                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16819                throw new PackageManagerException(copyRet, message);
16820            }
16821        }
16822    }
16823
16824    /**
16825     * Extract the StorageManagerService "container ID" from the full code path of an
16826     * .apk.
16827     */
16828    static String cidFromCodePath(String fullCodePath) {
16829        int eidx = fullCodePath.lastIndexOf("/");
16830        String subStr1 = fullCodePath.substring(0, eidx);
16831        int sidx = subStr1.lastIndexOf("/");
16832        return subStr1.substring(sidx+1, eidx);
16833    }
16834
16835    /**
16836     * Logic to handle installation of ASEC applications, including copying and
16837     * renaming logic.
16838     */
16839    class AsecInstallArgs extends InstallArgs {
16840        static final String RES_FILE_NAME = "pkg.apk";
16841        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16842
16843        String cid;
16844        String packagePath;
16845        String resourcePath;
16846
16847        /** New install */
16848        AsecInstallArgs(InstallParams params) {
16849            super(params.origin, params.move, params.observer, params.installFlags,
16850                    params.installerPackageName, params.volumeUuid,
16851                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16852                    params.grantedRuntimePermissions,
16853                    params.traceMethod, params.traceCookie, params.certificates,
16854                    params.installReason);
16855        }
16856
16857        /** Existing install */
16858        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16859                        boolean isExternal, boolean isForwardLocked) {
16860            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16861                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16862                    instructionSets, null, null, null, 0, null /*certificates*/,
16863                    PackageManager.INSTALL_REASON_UNKNOWN);
16864            // Hackily pretend we're still looking at a full code path
16865            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16866                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16867            }
16868
16869            // Extract cid from fullCodePath
16870            int eidx = fullCodePath.lastIndexOf("/");
16871            String subStr1 = fullCodePath.substring(0, eidx);
16872            int sidx = subStr1.lastIndexOf("/");
16873            cid = subStr1.substring(sidx+1, eidx);
16874            setMountPath(subStr1);
16875        }
16876
16877        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16878            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16879                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16880                    instructionSets, null, null, null, 0, null /*certificates*/,
16881                    PackageManager.INSTALL_REASON_UNKNOWN);
16882            this.cid = cid;
16883            setMountPath(PackageHelper.getSdDir(cid));
16884        }
16885
16886        void createCopyFile() {
16887            cid = mInstallerService.allocateExternalStageCidLegacy();
16888        }
16889
16890        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16891            if (origin.staged && origin.cid != null) {
16892                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16893                cid = origin.cid;
16894                setMountPath(PackageHelper.getSdDir(cid));
16895                return PackageManager.INSTALL_SUCCEEDED;
16896            }
16897
16898            if (temp) {
16899                createCopyFile();
16900            } else {
16901                /*
16902                 * Pre-emptively destroy the container since it's destroyed if
16903                 * copying fails due to it existing anyway.
16904                 */
16905                PackageHelper.destroySdDir(cid);
16906            }
16907
16908            final String newMountPath = imcs.copyPackageToContainer(
16909                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16910                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16911
16912            if (newMountPath != null) {
16913                setMountPath(newMountPath);
16914                return PackageManager.INSTALL_SUCCEEDED;
16915            } else {
16916                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16917            }
16918        }
16919
16920        @Override
16921        String getCodePath() {
16922            return packagePath;
16923        }
16924
16925        @Override
16926        String getResourcePath() {
16927            return resourcePath;
16928        }
16929
16930        int doPreInstall(int status) {
16931            if (status != PackageManager.INSTALL_SUCCEEDED) {
16932                // Destroy container
16933                PackageHelper.destroySdDir(cid);
16934            } else {
16935                boolean mounted = PackageHelper.isContainerMounted(cid);
16936                if (!mounted) {
16937                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16938                            Process.SYSTEM_UID);
16939                    if (newMountPath != null) {
16940                        setMountPath(newMountPath);
16941                    } else {
16942                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16943                    }
16944                }
16945            }
16946            return status;
16947        }
16948
16949        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16950            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16951            String newMountPath = null;
16952            if (PackageHelper.isContainerMounted(cid)) {
16953                // Unmount the container
16954                if (!PackageHelper.unMountSdDir(cid)) {
16955                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16956                    return false;
16957                }
16958            }
16959            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16960                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16961                        " which might be stale. Will try to clean up.");
16962                // Clean up the stale container and proceed to recreate.
16963                if (!PackageHelper.destroySdDir(newCacheId)) {
16964                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16965                    return false;
16966                }
16967                // Successfully cleaned up stale container. Try to rename again.
16968                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16969                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16970                            + " inspite of cleaning it up.");
16971                    return false;
16972                }
16973            }
16974            if (!PackageHelper.isContainerMounted(newCacheId)) {
16975                Slog.w(TAG, "Mounting container " + newCacheId);
16976                newMountPath = PackageHelper.mountSdDir(newCacheId,
16977                        getEncryptKey(), Process.SYSTEM_UID);
16978            } else {
16979                newMountPath = PackageHelper.getSdDir(newCacheId);
16980            }
16981            if (newMountPath == null) {
16982                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16983                return false;
16984            }
16985            Log.i(TAG, "Succesfully renamed " + cid +
16986                    " to " + newCacheId +
16987                    " at new path: " + newMountPath);
16988            cid = newCacheId;
16989
16990            final File beforeCodeFile = new File(packagePath);
16991            setMountPath(newMountPath);
16992            final File afterCodeFile = new File(packagePath);
16993
16994            // Reflect the rename in scanned details
16995            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16996            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16997                    afterCodeFile, pkg.baseCodePath));
16998            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16999                    afterCodeFile, pkg.splitCodePaths));
17000
17001            // Reflect the rename in app info
17002            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17003            pkg.setApplicationInfoCodePath(pkg.codePath);
17004            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17005            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17006            pkg.setApplicationInfoResourcePath(pkg.codePath);
17007            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17008            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17009
17010            return true;
17011        }
17012
17013        private void setMountPath(String mountPath) {
17014            final File mountFile = new File(mountPath);
17015
17016            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17017            if (monolithicFile.exists()) {
17018                packagePath = monolithicFile.getAbsolutePath();
17019                if (isFwdLocked()) {
17020                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17021                } else {
17022                    resourcePath = packagePath;
17023                }
17024            } else {
17025                packagePath = mountFile.getAbsolutePath();
17026                resourcePath = packagePath;
17027            }
17028        }
17029
17030        int doPostInstall(int status, int uid) {
17031            if (status != PackageManager.INSTALL_SUCCEEDED) {
17032                cleanUp();
17033            } else {
17034                final int groupOwner;
17035                final String protectedFile;
17036                if (isFwdLocked()) {
17037                    groupOwner = UserHandle.getSharedAppGid(uid);
17038                    protectedFile = RES_FILE_NAME;
17039                } else {
17040                    groupOwner = -1;
17041                    protectedFile = null;
17042                }
17043
17044                if (uid < Process.FIRST_APPLICATION_UID
17045                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17046                    Slog.e(TAG, "Failed to finalize " + cid);
17047                    PackageHelper.destroySdDir(cid);
17048                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17049                }
17050
17051                boolean mounted = PackageHelper.isContainerMounted(cid);
17052                if (!mounted) {
17053                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17054                }
17055            }
17056            return status;
17057        }
17058
17059        private void cleanUp() {
17060            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17061
17062            // Destroy secure container
17063            PackageHelper.destroySdDir(cid);
17064        }
17065
17066        private List<String> getAllCodePaths() {
17067            final File codeFile = new File(getCodePath());
17068            if (codeFile != null && codeFile.exists()) {
17069                try {
17070                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17071                    return pkg.getAllCodePaths();
17072                } catch (PackageParserException e) {
17073                    // Ignored; we tried our best
17074                }
17075            }
17076            return Collections.EMPTY_LIST;
17077        }
17078
17079        void cleanUpResourcesLI() {
17080            // Enumerate all code paths before deleting
17081            cleanUpResourcesLI(getAllCodePaths());
17082        }
17083
17084        private void cleanUpResourcesLI(List<String> allCodePaths) {
17085            cleanUp();
17086            removeDexFiles(allCodePaths, instructionSets);
17087        }
17088
17089        String getPackageName() {
17090            return getAsecPackageName(cid);
17091        }
17092
17093        boolean doPostDeleteLI(boolean delete) {
17094            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17095            final List<String> allCodePaths = getAllCodePaths();
17096            boolean mounted = PackageHelper.isContainerMounted(cid);
17097            if (mounted) {
17098                // Unmount first
17099                if (PackageHelper.unMountSdDir(cid)) {
17100                    mounted = false;
17101                }
17102            }
17103            if (!mounted && delete) {
17104                cleanUpResourcesLI(allCodePaths);
17105            }
17106            return !mounted;
17107        }
17108
17109        @Override
17110        int doPreCopy() {
17111            if (isFwdLocked()) {
17112                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17113                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17114                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17115                }
17116            }
17117
17118            return PackageManager.INSTALL_SUCCEEDED;
17119        }
17120
17121        @Override
17122        int doPostCopy(int uid) {
17123            if (isFwdLocked()) {
17124                if (uid < Process.FIRST_APPLICATION_UID
17125                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17126                                RES_FILE_NAME)) {
17127                    Slog.e(TAG, "Failed to finalize " + cid);
17128                    PackageHelper.destroySdDir(cid);
17129                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17130                }
17131            }
17132
17133            return PackageManager.INSTALL_SUCCEEDED;
17134        }
17135    }
17136
17137    /**
17138     * Logic to handle movement of existing installed applications.
17139     */
17140    class MoveInstallArgs extends InstallArgs {
17141        private File codeFile;
17142        private File resourceFile;
17143
17144        /** New install */
17145        MoveInstallArgs(InstallParams params) {
17146            super(params.origin, params.move, params.observer, params.installFlags,
17147                    params.installerPackageName, params.volumeUuid,
17148                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17149                    params.grantedRuntimePermissions,
17150                    params.traceMethod, params.traceCookie, params.certificates,
17151                    params.installReason);
17152        }
17153
17154        int copyApk(IMediaContainerService imcs, boolean temp) {
17155            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17156                    + move.fromUuid + " to " + move.toUuid);
17157            synchronized (mInstaller) {
17158                try {
17159                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17160                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17161                } catch (InstallerException e) {
17162                    Slog.w(TAG, "Failed to move app", e);
17163                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17164                }
17165            }
17166
17167            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17168            resourceFile = codeFile;
17169            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17170
17171            return PackageManager.INSTALL_SUCCEEDED;
17172        }
17173
17174        int doPreInstall(int status) {
17175            if (status != PackageManager.INSTALL_SUCCEEDED) {
17176                cleanUp(move.toUuid);
17177            }
17178            return status;
17179        }
17180
17181        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17182            if (status != PackageManager.INSTALL_SUCCEEDED) {
17183                cleanUp(move.toUuid);
17184                return false;
17185            }
17186
17187            // Reflect the move in app info
17188            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17189            pkg.setApplicationInfoCodePath(pkg.codePath);
17190            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17191            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17192            pkg.setApplicationInfoResourcePath(pkg.codePath);
17193            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17194            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17195
17196            return true;
17197        }
17198
17199        int doPostInstall(int status, int uid) {
17200            if (status == PackageManager.INSTALL_SUCCEEDED) {
17201                cleanUp(move.fromUuid);
17202            } else {
17203                cleanUp(move.toUuid);
17204            }
17205            return status;
17206        }
17207
17208        @Override
17209        String getCodePath() {
17210            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17211        }
17212
17213        @Override
17214        String getResourcePath() {
17215            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17216        }
17217
17218        private boolean cleanUp(String volumeUuid) {
17219            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17220                    move.dataAppName);
17221            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17222            final int[] userIds = sUserManager.getUserIds();
17223            synchronized (mInstallLock) {
17224                // Clean up both app data and code
17225                // All package moves are frozen until finished
17226                for (int userId : userIds) {
17227                    try {
17228                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17229                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17230                    } catch (InstallerException e) {
17231                        Slog.w(TAG, String.valueOf(e));
17232                    }
17233                }
17234                removeCodePathLI(codeFile);
17235            }
17236            return true;
17237        }
17238
17239        void cleanUpResourcesLI() {
17240            throw new UnsupportedOperationException();
17241        }
17242
17243        boolean doPostDeleteLI(boolean delete) {
17244            throw new UnsupportedOperationException();
17245        }
17246    }
17247
17248    static String getAsecPackageName(String packageCid) {
17249        int idx = packageCid.lastIndexOf("-");
17250        if (idx == -1) {
17251            return packageCid;
17252        }
17253        return packageCid.substring(0, idx);
17254    }
17255
17256    // Utility method used to create code paths based on package name and available index.
17257    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17258        String idxStr = "";
17259        int idx = 1;
17260        // Fall back to default value of idx=1 if prefix is not
17261        // part of oldCodePath
17262        if (oldCodePath != null) {
17263            String subStr = oldCodePath;
17264            // Drop the suffix right away
17265            if (suffix != null && subStr.endsWith(suffix)) {
17266                subStr = subStr.substring(0, subStr.length() - suffix.length());
17267            }
17268            // If oldCodePath already contains prefix find out the
17269            // ending index to either increment or decrement.
17270            int sidx = subStr.lastIndexOf(prefix);
17271            if (sidx != -1) {
17272                subStr = subStr.substring(sidx + prefix.length());
17273                if (subStr != null) {
17274                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17275                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17276                    }
17277                    try {
17278                        idx = Integer.parseInt(subStr);
17279                        if (idx <= 1) {
17280                            idx++;
17281                        } else {
17282                            idx--;
17283                        }
17284                    } catch(NumberFormatException e) {
17285                    }
17286                }
17287            }
17288        }
17289        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17290        return prefix + idxStr;
17291    }
17292
17293    private File getNextCodePath(File targetDir, String packageName) {
17294        File result;
17295        SecureRandom random = new SecureRandom();
17296        byte[] bytes = new byte[16];
17297        do {
17298            random.nextBytes(bytes);
17299            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17300            result = new File(targetDir, packageName + "-" + suffix);
17301        } while (result.exists());
17302        return result;
17303    }
17304
17305    // Utility method that returns the relative package path with respect
17306    // to the installation directory. Like say for /data/data/com.test-1.apk
17307    // string com.test-1 is returned.
17308    static String deriveCodePathName(String codePath) {
17309        if (codePath == null) {
17310            return null;
17311        }
17312        final File codeFile = new File(codePath);
17313        final String name = codeFile.getName();
17314        if (codeFile.isDirectory()) {
17315            return name;
17316        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17317            final int lastDot = name.lastIndexOf('.');
17318            return name.substring(0, lastDot);
17319        } else {
17320            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17321            return null;
17322        }
17323    }
17324
17325    static class PackageInstalledInfo {
17326        String name;
17327        int uid;
17328        // The set of users that originally had this package installed.
17329        int[] origUsers;
17330        // The set of users that now have this package installed.
17331        int[] newUsers;
17332        PackageParser.Package pkg;
17333        int returnCode;
17334        String returnMsg;
17335        PackageRemovedInfo removedInfo;
17336        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17337
17338        public void setError(int code, String msg) {
17339            setReturnCode(code);
17340            setReturnMessage(msg);
17341            Slog.w(TAG, msg);
17342        }
17343
17344        public void setError(String msg, PackageParserException e) {
17345            setReturnCode(e.error);
17346            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17347            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17348            for (int i = 0; i < childCount; i++) {
17349                addedChildPackages.valueAt(i).setError(msg, e);
17350            }
17351            Slog.w(TAG, msg, e);
17352        }
17353
17354        public void setError(String msg, PackageManagerException e) {
17355            returnCode = e.error;
17356            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17357            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17358            for (int i = 0; i < childCount; i++) {
17359                addedChildPackages.valueAt(i).setError(msg, e);
17360            }
17361            Slog.w(TAG, msg, e);
17362        }
17363
17364        public void setReturnCode(int returnCode) {
17365            this.returnCode = returnCode;
17366            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17367            for (int i = 0; i < childCount; i++) {
17368                addedChildPackages.valueAt(i).returnCode = returnCode;
17369            }
17370        }
17371
17372        private void setReturnMessage(String returnMsg) {
17373            this.returnMsg = returnMsg;
17374            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17375            for (int i = 0; i < childCount; i++) {
17376                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17377            }
17378        }
17379
17380        // In some error cases we want to convey more info back to the observer
17381        String origPackage;
17382        String origPermission;
17383    }
17384
17385    /*
17386     * Install a non-existing package.
17387     */
17388    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17389            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17390            PackageInstalledInfo res, int installReason) {
17391        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17392
17393        // Remember this for later, in case we need to rollback this install
17394        String pkgName = pkg.packageName;
17395
17396        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17397
17398        synchronized(mPackages) {
17399            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17400            if (renamedPackage != null) {
17401                // A package with the same name is already installed, though
17402                // it has been renamed to an older name.  The package we
17403                // are trying to install should be installed as an update to
17404                // the existing one, but that has not been requested, so bail.
17405                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17406                        + " without first uninstalling package running as "
17407                        + renamedPackage);
17408                return;
17409            }
17410            if (mPackages.containsKey(pkgName)) {
17411                // Don't allow installation over an existing package with the same name.
17412                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17413                        + " without first uninstalling.");
17414                return;
17415            }
17416        }
17417
17418        try {
17419            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17420                    System.currentTimeMillis(), user);
17421
17422            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17423
17424            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17425                prepareAppDataAfterInstallLIF(newPackage);
17426
17427            } else {
17428                // Remove package from internal structures, but keep around any
17429                // data that might have already existed
17430                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17431                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17432            }
17433        } catch (PackageManagerException e) {
17434            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17435        }
17436
17437        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17438    }
17439
17440    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17441        // Can't rotate keys during boot or if sharedUser.
17442        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17443                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17444            return false;
17445        }
17446        // app is using upgradeKeySets; make sure all are valid
17447        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17448        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17449        for (int i = 0; i < upgradeKeySets.length; i++) {
17450            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17451                Slog.wtf(TAG, "Package "
17452                         + (oldPs.name != null ? oldPs.name : "<null>")
17453                         + " contains upgrade-key-set reference to unknown key-set: "
17454                         + upgradeKeySets[i]
17455                         + " reverting to signatures check.");
17456                return false;
17457            }
17458        }
17459        return true;
17460    }
17461
17462    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17463        // Upgrade keysets are being used.  Determine if new package has a superset of the
17464        // required keys.
17465        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17466        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17467        for (int i = 0; i < upgradeKeySets.length; i++) {
17468            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17469            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17470                return true;
17471            }
17472        }
17473        return false;
17474    }
17475
17476    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17477        try (DigestInputStream digestStream =
17478                new DigestInputStream(new FileInputStream(file), digest)) {
17479            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17480        }
17481    }
17482
17483    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17484            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17485            int installReason) {
17486        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17487
17488        final PackageParser.Package oldPackage;
17489        final PackageSetting ps;
17490        final String pkgName = pkg.packageName;
17491        final int[] allUsers;
17492        final int[] installedUsers;
17493
17494        synchronized(mPackages) {
17495            oldPackage = mPackages.get(pkgName);
17496            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17497
17498            // don't allow upgrade to target a release SDK from a pre-release SDK
17499            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17500                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17501            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17502                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17503            if (oldTargetsPreRelease
17504                    && !newTargetsPreRelease
17505                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17506                Slog.w(TAG, "Can't install package targeting released sdk");
17507                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17508                return;
17509            }
17510
17511            ps = mSettings.mPackages.get(pkgName);
17512
17513            // verify signatures are valid
17514            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17515                if (!checkUpgradeKeySetLP(ps, pkg)) {
17516                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17517                            "New package not signed by keys specified by upgrade-keysets: "
17518                                    + pkgName);
17519                    return;
17520                }
17521            } else {
17522                // default to original signature matching
17523                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17524                        != PackageManager.SIGNATURE_MATCH) {
17525                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17526                            "New package has a different signature: " + pkgName);
17527                    return;
17528                }
17529            }
17530
17531            // don't allow a system upgrade unless the upgrade hash matches
17532            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17533                byte[] digestBytes = null;
17534                try {
17535                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17536                    updateDigest(digest, new File(pkg.baseCodePath));
17537                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17538                        for (String path : pkg.splitCodePaths) {
17539                            updateDigest(digest, new File(path));
17540                        }
17541                    }
17542                    digestBytes = digest.digest();
17543                } catch (NoSuchAlgorithmException | IOException e) {
17544                    res.setError(INSTALL_FAILED_INVALID_APK,
17545                            "Could not compute hash: " + pkgName);
17546                    return;
17547                }
17548                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17549                    res.setError(INSTALL_FAILED_INVALID_APK,
17550                            "New package fails restrict-update check: " + pkgName);
17551                    return;
17552                }
17553                // retain upgrade restriction
17554                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17555            }
17556
17557            // Check for shared user id changes
17558            String invalidPackageName =
17559                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17560            if (invalidPackageName != null) {
17561                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17562                        "Package " + invalidPackageName + " tried to change user "
17563                                + oldPackage.mSharedUserId);
17564                return;
17565            }
17566
17567            // In case of rollback, remember per-user/profile install state
17568            allUsers = sUserManager.getUserIds();
17569            installedUsers = ps.queryInstalledUsers(allUsers, true);
17570
17571            // don't allow an upgrade from full to ephemeral
17572            if (isInstantApp) {
17573                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17574                    for (int currentUser : allUsers) {
17575                        if (!ps.getInstantApp(currentUser)) {
17576                            // can't downgrade from full to instant
17577                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17578                                    + " for user: " + currentUser);
17579                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17580                            return;
17581                        }
17582                    }
17583                } else if (!ps.getInstantApp(user.getIdentifier())) {
17584                    // can't downgrade from full to instant
17585                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17586                            + " for user: " + user.getIdentifier());
17587                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17588                    return;
17589                }
17590            }
17591        }
17592
17593        // Update what is removed
17594        res.removedInfo = new PackageRemovedInfo(this);
17595        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17596        res.removedInfo.removedPackage = oldPackage.packageName;
17597        res.removedInfo.installerPackageName = ps.installerPackageName;
17598        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17599        res.removedInfo.isUpdate = true;
17600        res.removedInfo.origUsers = installedUsers;
17601        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17602        for (int i = 0; i < installedUsers.length; i++) {
17603            final int userId = installedUsers[i];
17604            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17605        }
17606
17607        final int childCount = (oldPackage.childPackages != null)
17608                ? oldPackage.childPackages.size() : 0;
17609        for (int i = 0; i < childCount; i++) {
17610            boolean childPackageUpdated = false;
17611            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17612            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17613            if (res.addedChildPackages != null) {
17614                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17615                if (childRes != null) {
17616                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17617                    childRes.removedInfo.removedPackage = childPkg.packageName;
17618                    if (childPs != null) {
17619                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17620                    }
17621                    childRes.removedInfo.isUpdate = true;
17622                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17623                    childPackageUpdated = true;
17624                }
17625            }
17626            if (!childPackageUpdated) {
17627                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17628                childRemovedRes.removedPackage = childPkg.packageName;
17629                if (childPs != null) {
17630                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17631                }
17632                childRemovedRes.isUpdate = false;
17633                childRemovedRes.dataRemoved = true;
17634                synchronized (mPackages) {
17635                    if (childPs != null) {
17636                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17637                    }
17638                }
17639                if (res.removedInfo.removedChildPackages == null) {
17640                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17641                }
17642                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17643            }
17644        }
17645
17646        boolean sysPkg = (isSystemApp(oldPackage));
17647        if (sysPkg) {
17648            // Set the system/privileged flags as needed
17649            final boolean privileged =
17650                    (oldPackage.applicationInfo.privateFlags
17651                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17652            final int systemPolicyFlags = policyFlags
17653                    | PackageParser.PARSE_IS_SYSTEM
17654                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17655
17656            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17657                    user, allUsers, installerPackageName, res, installReason);
17658        } else {
17659            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17660                    user, allUsers, installerPackageName, res, installReason);
17661        }
17662    }
17663
17664    @Override
17665    public List<String> getPreviousCodePaths(String packageName) {
17666        final int callingUid = Binder.getCallingUid();
17667        final List<String> result = new ArrayList<>();
17668        if (getInstantAppPackageName(callingUid) != null) {
17669            return result;
17670        }
17671        final PackageSetting ps = mSettings.mPackages.get(packageName);
17672        if (ps != null
17673                && ps.oldCodePaths != null
17674                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17675            result.addAll(ps.oldCodePaths);
17676        }
17677        return result;
17678    }
17679
17680    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17681            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17682            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17683            int installReason) {
17684        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17685                + deletedPackage);
17686
17687        String pkgName = deletedPackage.packageName;
17688        boolean deletedPkg = true;
17689        boolean addedPkg = false;
17690        boolean updatedSettings = false;
17691        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17692        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17693                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17694
17695        final long origUpdateTime = (pkg.mExtras != null)
17696                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17697
17698        // First delete the existing package while retaining the data directory
17699        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17700                res.removedInfo, true, pkg)) {
17701            // If the existing package wasn't successfully deleted
17702            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17703            deletedPkg = false;
17704        } else {
17705            // Successfully deleted the old package; proceed with replace.
17706
17707            // If deleted package lived in a container, give users a chance to
17708            // relinquish resources before killing.
17709            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17710                if (DEBUG_INSTALL) {
17711                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17712                }
17713                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17714                final ArrayList<String> pkgList = new ArrayList<String>(1);
17715                pkgList.add(deletedPackage.applicationInfo.packageName);
17716                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17717            }
17718
17719            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17720                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17721            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17722
17723            try {
17724                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17725                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17726                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17727                        installReason);
17728
17729                // Update the in-memory copy of the previous code paths.
17730                PackageSetting ps = mSettings.mPackages.get(pkgName);
17731                if (!killApp) {
17732                    if (ps.oldCodePaths == null) {
17733                        ps.oldCodePaths = new ArraySet<>();
17734                    }
17735                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17736                    if (deletedPackage.splitCodePaths != null) {
17737                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17738                    }
17739                } else {
17740                    ps.oldCodePaths = null;
17741                }
17742                if (ps.childPackageNames != null) {
17743                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17744                        final String childPkgName = ps.childPackageNames.get(i);
17745                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17746                        childPs.oldCodePaths = ps.oldCodePaths;
17747                    }
17748                }
17749                // set instant app status, but, only if it's explicitly specified
17750                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17751                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17752                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17753                prepareAppDataAfterInstallLIF(newPackage);
17754                addedPkg = true;
17755                mDexManager.notifyPackageUpdated(newPackage.packageName,
17756                        newPackage.baseCodePath, newPackage.splitCodePaths);
17757            } catch (PackageManagerException e) {
17758                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17759            }
17760        }
17761
17762        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17763            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17764
17765            // Revert all internal state mutations and added folders for the failed install
17766            if (addedPkg) {
17767                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17768                        res.removedInfo, true, null);
17769            }
17770
17771            // Restore the old package
17772            if (deletedPkg) {
17773                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17774                File restoreFile = new File(deletedPackage.codePath);
17775                // Parse old package
17776                boolean oldExternal = isExternal(deletedPackage);
17777                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17778                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17779                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17780                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17781                try {
17782                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17783                            null);
17784                } catch (PackageManagerException e) {
17785                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17786                            + e.getMessage());
17787                    return;
17788                }
17789
17790                synchronized (mPackages) {
17791                    // Ensure the installer package name up to date
17792                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17793
17794                    // Update permissions for restored package
17795                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17796
17797                    mSettings.writeLPr();
17798                }
17799
17800                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17801            }
17802        } else {
17803            synchronized (mPackages) {
17804                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17805                if (ps != null) {
17806                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17807                    if (res.removedInfo.removedChildPackages != null) {
17808                        final int childCount = res.removedInfo.removedChildPackages.size();
17809                        // Iterate in reverse as we may modify the collection
17810                        for (int i = childCount - 1; i >= 0; i--) {
17811                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17812                            if (res.addedChildPackages.containsKey(childPackageName)) {
17813                                res.removedInfo.removedChildPackages.removeAt(i);
17814                            } else {
17815                                PackageRemovedInfo childInfo = res.removedInfo
17816                                        .removedChildPackages.valueAt(i);
17817                                childInfo.removedForAllUsers = mPackages.get(
17818                                        childInfo.removedPackage) == null;
17819                            }
17820                        }
17821                    }
17822                }
17823            }
17824        }
17825    }
17826
17827    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17828            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17829            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17830            int installReason) {
17831        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17832                + ", old=" + deletedPackage);
17833
17834        final boolean disabledSystem;
17835
17836        // Remove existing system package
17837        removePackageLI(deletedPackage, true);
17838
17839        synchronized (mPackages) {
17840            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17841        }
17842        if (!disabledSystem) {
17843            // We didn't need to disable the .apk as a current system package,
17844            // which means we are replacing another update that is already
17845            // installed.  We need to make sure to delete the older one's .apk.
17846            res.removedInfo.args = createInstallArgsForExisting(0,
17847                    deletedPackage.applicationInfo.getCodePath(),
17848                    deletedPackage.applicationInfo.getResourcePath(),
17849                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17850        } else {
17851            res.removedInfo.args = null;
17852        }
17853
17854        // Successfully disabled the old package. Now proceed with re-installation
17855        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17856                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17857        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17858
17859        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17860        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17861                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17862
17863        PackageParser.Package newPackage = null;
17864        try {
17865            // Add the package to the internal data structures
17866            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17867
17868            // Set the update and install times
17869            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17870            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17871                    System.currentTimeMillis());
17872
17873            // Update the package dynamic state if succeeded
17874            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17875                // Now that the install succeeded make sure we remove data
17876                // directories for any child package the update removed.
17877                final int deletedChildCount = (deletedPackage.childPackages != null)
17878                        ? deletedPackage.childPackages.size() : 0;
17879                final int newChildCount = (newPackage.childPackages != null)
17880                        ? newPackage.childPackages.size() : 0;
17881                for (int i = 0; i < deletedChildCount; i++) {
17882                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17883                    boolean childPackageDeleted = true;
17884                    for (int j = 0; j < newChildCount; j++) {
17885                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17886                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17887                            childPackageDeleted = false;
17888                            break;
17889                        }
17890                    }
17891                    if (childPackageDeleted) {
17892                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17893                                deletedChildPkg.packageName);
17894                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17895                            PackageRemovedInfo removedChildRes = res.removedInfo
17896                                    .removedChildPackages.get(deletedChildPkg.packageName);
17897                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17898                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17899                        }
17900                    }
17901                }
17902
17903                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17904                        installReason);
17905                prepareAppDataAfterInstallLIF(newPackage);
17906
17907                mDexManager.notifyPackageUpdated(newPackage.packageName,
17908                            newPackage.baseCodePath, newPackage.splitCodePaths);
17909            }
17910        } catch (PackageManagerException e) {
17911            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17912            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17913        }
17914
17915        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17916            // Re installation failed. Restore old information
17917            // Remove new pkg information
17918            if (newPackage != null) {
17919                removeInstalledPackageLI(newPackage, true);
17920            }
17921            // Add back the old system package
17922            try {
17923                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17924            } catch (PackageManagerException e) {
17925                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17926            }
17927
17928            synchronized (mPackages) {
17929                if (disabledSystem) {
17930                    enableSystemPackageLPw(deletedPackage);
17931                }
17932
17933                // Ensure the installer package name up to date
17934                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17935
17936                // Update permissions for restored package
17937                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17938
17939                mSettings.writeLPr();
17940            }
17941
17942            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17943                    + " after failed upgrade");
17944        }
17945    }
17946
17947    /**
17948     * Checks whether the parent or any of the child packages have a change shared
17949     * user. For a package to be a valid update the shred users of the parent and
17950     * the children should match. We may later support changing child shared users.
17951     * @param oldPkg The updated package.
17952     * @param newPkg The update package.
17953     * @return The shared user that change between the versions.
17954     */
17955    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17956            PackageParser.Package newPkg) {
17957        // Check parent shared user
17958        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17959            return newPkg.packageName;
17960        }
17961        // Check child shared users
17962        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17963        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17964        for (int i = 0; i < newChildCount; i++) {
17965            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17966            // If this child was present, did it have the same shared user?
17967            for (int j = 0; j < oldChildCount; j++) {
17968                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17969                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17970                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17971                    return newChildPkg.packageName;
17972                }
17973            }
17974        }
17975        return null;
17976    }
17977
17978    private void removeNativeBinariesLI(PackageSetting ps) {
17979        // Remove the lib path for the parent package
17980        if (ps != null) {
17981            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17982            // Remove the lib path for the child packages
17983            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17984            for (int i = 0; i < childCount; i++) {
17985                PackageSetting childPs = null;
17986                synchronized (mPackages) {
17987                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17988                }
17989                if (childPs != null) {
17990                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17991                            .legacyNativeLibraryPathString);
17992                }
17993            }
17994        }
17995    }
17996
17997    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17998        // Enable the parent package
17999        mSettings.enableSystemPackageLPw(pkg.packageName);
18000        // Enable the child packages
18001        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18002        for (int i = 0; i < childCount; i++) {
18003            PackageParser.Package childPkg = pkg.childPackages.get(i);
18004            mSettings.enableSystemPackageLPw(childPkg.packageName);
18005        }
18006    }
18007
18008    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18009            PackageParser.Package newPkg) {
18010        // Disable the parent package (parent always replaced)
18011        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18012        // Disable the child packages
18013        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18014        for (int i = 0; i < childCount; i++) {
18015            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18016            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18017            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18018        }
18019        return disabled;
18020    }
18021
18022    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18023            String installerPackageName) {
18024        // Enable the parent package
18025        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18026        // Enable the child packages
18027        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18028        for (int i = 0; i < childCount; i++) {
18029            PackageParser.Package childPkg = pkg.childPackages.get(i);
18030            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18031        }
18032    }
18033
18034    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18035        // Collect all used permissions in the UID
18036        ArraySet<String> usedPermissions = new ArraySet<>();
18037        final int packageCount = su.packages.size();
18038        for (int i = 0; i < packageCount; i++) {
18039            PackageSetting ps = su.packages.valueAt(i);
18040            if (ps.pkg == null) {
18041                continue;
18042            }
18043            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18044            for (int j = 0; j < requestedPermCount; j++) {
18045                String permission = ps.pkg.requestedPermissions.get(j);
18046                BasePermission bp = mSettings.mPermissions.get(permission);
18047                if (bp != null) {
18048                    usedPermissions.add(permission);
18049                }
18050            }
18051        }
18052
18053        PermissionsState permissionsState = su.getPermissionsState();
18054        // Prune install permissions
18055        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18056        final int installPermCount = installPermStates.size();
18057        for (int i = installPermCount - 1; i >= 0;  i--) {
18058            PermissionState permissionState = installPermStates.get(i);
18059            if (!usedPermissions.contains(permissionState.getName())) {
18060                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18061                if (bp != null) {
18062                    permissionsState.revokeInstallPermission(bp);
18063                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18064                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18065                }
18066            }
18067        }
18068
18069        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18070
18071        // Prune runtime permissions
18072        for (int userId : allUserIds) {
18073            List<PermissionState> runtimePermStates = permissionsState
18074                    .getRuntimePermissionStates(userId);
18075            final int runtimePermCount = runtimePermStates.size();
18076            for (int i = runtimePermCount - 1; i >= 0; i--) {
18077                PermissionState permissionState = runtimePermStates.get(i);
18078                if (!usedPermissions.contains(permissionState.getName())) {
18079                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18080                    if (bp != null) {
18081                        permissionsState.revokeRuntimePermission(bp, userId);
18082                        permissionsState.updatePermissionFlags(bp, userId,
18083                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18084                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18085                                runtimePermissionChangedUserIds, userId);
18086                    }
18087                }
18088            }
18089        }
18090
18091        return runtimePermissionChangedUserIds;
18092    }
18093
18094    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18095            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18096        // Update the parent package setting
18097        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18098                res, user, installReason);
18099        // Update the child packages setting
18100        final int childCount = (newPackage.childPackages != null)
18101                ? newPackage.childPackages.size() : 0;
18102        for (int i = 0; i < childCount; i++) {
18103            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18104            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18105            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18106                    childRes.origUsers, childRes, user, installReason);
18107        }
18108    }
18109
18110    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18111            String installerPackageName, int[] allUsers, int[] installedForUsers,
18112            PackageInstalledInfo res, UserHandle user, int installReason) {
18113        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18114
18115        String pkgName = newPackage.packageName;
18116        synchronized (mPackages) {
18117            //write settings. the installStatus will be incomplete at this stage.
18118            //note that the new package setting would have already been
18119            //added to mPackages. It hasn't been persisted yet.
18120            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18121            // TODO: Remove this write? It's also written at the end of this method
18122            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18123            mSettings.writeLPr();
18124            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18125        }
18126
18127        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18128        synchronized (mPackages) {
18129            updatePermissionsLPw(newPackage.packageName, newPackage,
18130                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18131                            ? UPDATE_PERMISSIONS_ALL : 0));
18132            // For system-bundled packages, we assume that installing an upgraded version
18133            // of the package implies that the user actually wants to run that new code,
18134            // so we enable the package.
18135            PackageSetting ps = mSettings.mPackages.get(pkgName);
18136            final int userId = user.getIdentifier();
18137            if (ps != null) {
18138                if (isSystemApp(newPackage)) {
18139                    if (DEBUG_INSTALL) {
18140                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18141                    }
18142                    // Enable system package for requested users
18143                    if (res.origUsers != null) {
18144                        for (int origUserId : res.origUsers) {
18145                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18146                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18147                                        origUserId, installerPackageName);
18148                            }
18149                        }
18150                    }
18151                    // Also convey the prior install/uninstall state
18152                    if (allUsers != null && installedForUsers != null) {
18153                        for (int currentUserId : allUsers) {
18154                            final boolean installed = ArrayUtils.contains(
18155                                    installedForUsers, currentUserId);
18156                            if (DEBUG_INSTALL) {
18157                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18158                            }
18159                            ps.setInstalled(installed, currentUserId);
18160                        }
18161                        // these install state changes will be persisted in the
18162                        // upcoming call to mSettings.writeLPr().
18163                    }
18164                }
18165                // It's implied that when a user requests installation, they want the app to be
18166                // installed and enabled.
18167                if (userId != UserHandle.USER_ALL) {
18168                    ps.setInstalled(true, userId);
18169                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18170                }
18171
18172                // When replacing an existing package, preserve the original install reason for all
18173                // users that had the package installed before.
18174                final Set<Integer> previousUserIds = new ArraySet<>();
18175                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18176                    final int installReasonCount = res.removedInfo.installReasons.size();
18177                    for (int i = 0; i < installReasonCount; i++) {
18178                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18179                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18180                        ps.setInstallReason(previousInstallReason, previousUserId);
18181                        previousUserIds.add(previousUserId);
18182                    }
18183                }
18184
18185                // Set install reason for users that are having the package newly installed.
18186                if (userId == UserHandle.USER_ALL) {
18187                    for (int currentUserId : sUserManager.getUserIds()) {
18188                        if (!previousUserIds.contains(currentUserId)) {
18189                            ps.setInstallReason(installReason, currentUserId);
18190                        }
18191                    }
18192                } else if (!previousUserIds.contains(userId)) {
18193                    ps.setInstallReason(installReason, userId);
18194                }
18195                mSettings.writeKernelMappingLPr(ps);
18196            }
18197            res.name = pkgName;
18198            res.uid = newPackage.applicationInfo.uid;
18199            res.pkg = newPackage;
18200            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18201            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18202            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18203            //to update install status
18204            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18205            mSettings.writeLPr();
18206            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18207        }
18208
18209        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18210    }
18211
18212    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18213        try {
18214            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18215            installPackageLI(args, res);
18216        } finally {
18217            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18218        }
18219    }
18220
18221    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18222        final int installFlags = args.installFlags;
18223        final String installerPackageName = args.installerPackageName;
18224        final String volumeUuid = args.volumeUuid;
18225        final File tmpPackageFile = new File(args.getCodePath());
18226        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18227        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18228                || (args.volumeUuid != null));
18229        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18230        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18231        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18232        final boolean virtualPreload =
18233                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18234        boolean replace = false;
18235        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18236        if (args.move != null) {
18237            // moving a complete application; perform an initial scan on the new install location
18238            scanFlags |= SCAN_INITIAL;
18239        }
18240        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18241            scanFlags |= SCAN_DONT_KILL_APP;
18242        }
18243        if (instantApp) {
18244            scanFlags |= SCAN_AS_INSTANT_APP;
18245        }
18246        if (fullApp) {
18247            scanFlags |= SCAN_AS_FULL_APP;
18248        }
18249        if (virtualPreload) {
18250            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18251        }
18252
18253        // Result object to be returned
18254        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18255
18256        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18257
18258        // Sanity check
18259        if (instantApp && (forwardLocked || onExternal)) {
18260            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18261                    + " external=" + onExternal);
18262            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18263            return;
18264        }
18265
18266        // Retrieve PackageSettings and parse package
18267        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18268                | PackageParser.PARSE_ENFORCE_CODE
18269                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18270                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18271                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18272                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18273        PackageParser pp = new PackageParser();
18274        pp.setSeparateProcesses(mSeparateProcesses);
18275        pp.setDisplayMetrics(mMetrics);
18276        pp.setCallback(mPackageParserCallback);
18277
18278        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18279        final PackageParser.Package pkg;
18280        try {
18281            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18282        } catch (PackageParserException e) {
18283            res.setError("Failed parse during installPackageLI", e);
18284            return;
18285        } finally {
18286            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18287        }
18288
18289        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18290        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18291            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18292            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18293                    "Instant app package must target O");
18294            return;
18295        }
18296        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18297            Slog.w(TAG, "Instant app package " + pkg.packageName
18298                    + " does not target targetSandboxVersion 2");
18299            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18300                    "Instant app package must use targetSanboxVersion 2");
18301            return;
18302        }
18303
18304        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18305            // Static shared libraries have synthetic package names
18306            renameStaticSharedLibraryPackage(pkg);
18307
18308            // No static shared libs on external storage
18309            if (onExternal) {
18310                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18311                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18312                        "Packages declaring static-shared libs cannot be updated");
18313                return;
18314            }
18315        }
18316
18317        // If we are installing a clustered package add results for the children
18318        if (pkg.childPackages != null) {
18319            synchronized (mPackages) {
18320                final int childCount = pkg.childPackages.size();
18321                for (int i = 0; i < childCount; i++) {
18322                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18323                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18324                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18325                    childRes.pkg = childPkg;
18326                    childRes.name = childPkg.packageName;
18327                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18328                    if (childPs != null) {
18329                        childRes.origUsers = childPs.queryInstalledUsers(
18330                                sUserManager.getUserIds(), true);
18331                    }
18332                    if ((mPackages.containsKey(childPkg.packageName))) {
18333                        childRes.removedInfo = new PackageRemovedInfo(this);
18334                        childRes.removedInfo.removedPackage = childPkg.packageName;
18335                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18336                    }
18337                    if (res.addedChildPackages == null) {
18338                        res.addedChildPackages = new ArrayMap<>();
18339                    }
18340                    res.addedChildPackages.put(childPkg.packageName, childRes);
18341                }
18342            }
18343        }
18344
18345        // If package doesn't declare API override, mark that we have an install
18346        // time CPU ABI override.
18347        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18348            pkg.cpuAbiOverride = args.abiOverride;
18349        }
18350
18351        String pkgName = res.name = pkg.packageName;
18352        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18353            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18354                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18355                return;
18356            }
18357        }
18358
18359        try {
18360            // either use what we've been given or parse directly from the APK
18361            if (args.certificates != null) {
18362                try {
18363                    PackageParser.populateCertificates(pkg, args.certificates);
18364                } catch (PackageParserException e) {
18365                    // there was something wrong with the certificates we were given;
18366                    // try to pull them from the APK
18367                    PackageParser.collectCertificates(pkg, parseFlags);
18368                }
18369            } else {
18370                PackageParser.collectCertificates(pkg, parseFlags);
18371            }
18372        } catch (PackageParserException e) {
18373            res.setError("Failed collect during installPackageLI", e);
18374            return;
18375        }
18376
18377        // Get rid of all references to package scan path via parser.
18378        pp = null;
18379        String oldCodePath = null;
18380        boolean systemApp = false;
18381        synchronized (mPackages) {
18382            // Check if installing already existing package
18383            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18384                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18385                if (pkg.mOriginalPackages != null
18386                        && pkg.mOriginalPackages.contains(oldName)
18387                        && mPackages.containsKey(oldName)) {
18388                    // This package is derived from an original package,
18389                    // and this device has been updating from that original
18390                    // name.  We must continue using the original name, so
18391                    // rename the new package here.
18392                    pkg.setPackageName(oldName);
18393                    pkgName = pkg.packageName;
18394                    replace = true;
18395                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18396                            + oldName + " pkgName=" + pkgName);
18397                } else if (mPackages.containsKey(pkgName)) {
18398                    // This package, under its official name, already exists
18399                    // on the device; we should replace it.
18400                    replace = true;
18401                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18402                }
18403
18404                // Child packages are installed through the parent package
18405                if (pkg.parentPackage != null) {
18406                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18407                            "Package " + pkg.packageName + " is child of package "
18408                                    + pkg.parentPackage.parentPackage + ". Child packages "
18409                                    + "can be updated only through the parent package.");
18410                    return;
18411                }
18412
18413                if (replace) {
18414                    // Prevent apps opting out from runtime permissions
18415                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18416                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18417                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18418                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18419                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18420                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18421                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18422                                        + " doesn't support runtime permissions but the old"
18423                                        + " target SDK " + oldTargetSdk + " does.");
18424                        return;
18425                    }
18426                    // Prevent apps from downgrading their targetSandbox.
18427                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18428                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18429                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18430                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18431                                "Package " + pkg.packageName + " new target sandbox "
18432                                + newTargetSandbox + " is incompatible with the previous value of"
18433                                + oldTargetSandbox + ".");
18434                        return;
18435                    }
18436
18437                    // Prevent installing of child packages
18438                    if (oldPackage.parentPackage != null) {
18439                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18440                                "Package " + pkg.packageName + " is child of package "
18441                                        + oldPackage.parentPackage + ". Child packages "
18442                                        + "can be updated only through the parent package.");
18443                        return;
18444                    }
18445                }
18446            }
18447
18448            PackageSetting ps = mSettings.mPackages.get(pkgName);
18449            if (ps != null) {
18450                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18451
18452                // Static shared libs have same package with different versions where
18453                // we internally use a synthetic package name to allow multiple versions
18454                // of the same package, therefore we need to compare signatures against
18455                // the package setting for the latest library version.
18456                PackageSetting signatureCheckPs = ps;
18457                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18458                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18459                    if (libraryEntry != null) {
18460                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18461                    }
18462                }
18463
18464                // Quick sanity check that we're signed correctly if updating;
18465                // we'll check this again later when scanning, but we want to
18466                // bail early here before tripping over redefined permissions.
18467                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18468                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18469                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18470                                + pkg.packageName + " upgrade keys do not match the "
18471                                + "previously installed version");
18472                        return;
18473                    }
18474                } else {
18475                    try {
18476                        verifySignaturesLP(signatureCheckPs, pkg);
18477                    } catch (PackageManagerException e) {
18478                        res.setError(e.error, e.getMessage());
18479                        return;
18480                    }
18481                }
18482
18483                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18484                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18485                    systemApp = (ps.pkg.applicationInfo.flags &
18486                            ApplicationInfo.FLAG_SYSTEM) != 0;
18487                }
18488                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18489            }
18490
18491            int N = pkg.permissions.size();
18492            for (int i = N-1; i >= 0; i--) {
18493                PackageParser.Permission perm = pkg.permissions.get(i);
18494                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18495
18496                // Don't allow anyone but the system to define ephemeral permissions.
18497                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18498                        && !systemApp) {
18499                    Slog.w(TAG, "Non-System package " + pkg.packageName
18500                            + " attempting to delcare ephemeral permission "
18501                            + perm.info.name + "; Removing ephemeral.");
18502                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18503                }
18504                // Check whether the newly-scanned package wants to define an already-defined perm
18505                if (bp != null) {
18506                    // If the defining package is signed with our cert, it's okay.  This
18507                    // also includes the "updating the same package" case, of course.
18508                    // "updating same package" could also involve key-rotation.
18509                    final boolean sigsOk;
18510                    if (bp.sourcePackage.equals(pkg.packageName)
18511                            && (bp.packageSetting instanceof PackageSetting)
18512                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18513                                    scanFlags))) {
18514                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18515                    } else {
18516                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18517                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18518                    }
18519                    if (!sigsOk) {
18520                        // If the owning package is the system itself, we log but allow
18521                        // install to proceed; we fail the install on all other permission
18522                        // redefinitions.
18523                        if (!bp.sourcePackage.equals("android")) {
18524                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18525                                    + pkg.packageName + " attempting to redeclare permission "
18526                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18527                            res.origPermission = perm.info.name;
18528                            res.origPackage = bp.sourcePackage;
18529                            return;
18530                        } else {
18531                            Slog.w(TAG, "Package " + pkg.packageName
18532                                    + " attempting to redeclare system permission "
18533                                    + perm.info.name + "; ignoring new declaration");
18534                            pkg.permissions.remove(i);
18535                        }
18536                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18537                        // Prevent apps to change protection level to dangerous from any other
18538                        // type as this would allow a privilege escalation where an app adds a
18539                        // normal/signature permission in other app's group and later redefines
18540                        // it as dangerous leading to the group auto-grant.
18541                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18542                                == PermissionInfo.PROTECTION_DANGEROUS) {
18543                            if (bp != null && !bp.isRuntime()) {
18544                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18545                                        + "non-runtime permission " + perm.info.name
18546                                        + " to runtime; keeping old protection level");
18547                                perm.info.protectionLevel = bp.protectionLevel;
18548                            }
18549                        }
18550                    }
18551                }
18552            }
18553        }
18554
18555        if (systemApp) {
18556            if (onExternal) {
18557                // Abort update; system app can't be replaced with app on sdcard
18558                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18559                        "Cannot install updates to system apps on sdcard");
18560                return;
18561            } else if (instantApp) {
18562                // Abort update; system app can't be replaced with an instant app
18563                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18564                        "Cannot update a system app with an instant app");
18565                return;
18566            }
18567        }
18568
18569        if (args.move != null) {
18570            // We did an in-place move, so dex is ready to roll
18571            scanFlags |= SCAN_NO_DEX;
18572            scanFlags |= SCAN_MOVE;
18573
18574            synchronized (mPackages) {
18575                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18576                if (ps == null) {
18577                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18578                            "Missing settings for moved package " + pkgName);
18579                }
18580
18581                // We moved the entire application as-is, so bring over the
18582                // previously derived ABI information.
18583                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18584                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18585            }
18586
18587        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18588            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18589            scanFlags |= SCAN_NO_DEX;
18590
18591            try {
18592                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18593                    args.abiOverride : pkg.cpuAbiOverride);
18594                final boolean extractNativeLibs = !pkg.isLibrary();
18595                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18596                        extractNativeLibs, mAppLib32InstallDir);
18597            } catch (PackageManagerException pme) {
18598                Slog.e(TAG, "Error deriving application ABI", pme);
18599                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18600                return;
18601            }
18602
18603            // Shared libraries for the package need to be updated.
18604            synchronized (mPackages) {
18605                try {
18606                    updateSharedLibrariesLPr(pkg, null);
18607                } catch (PackageManagerException e) {
18608                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18609                }
18610            }
18611
18612            // dexopt can take some time to complete, so, for instant apps, we skip this
18613            // step during installation. Instead, we'll take extra time the first time the
18614            // instant app starts. It's preferred to do it this way to provide continuous
18615            // progress to the user instead of mysteriously blocking somewhere in the
18616            // middle of running an instant app. The default behaviour can be overridden
18617            // via gservices.
18618            if (!instantApp || Global.getInt(
18619                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18620                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18621                // Do not run PackageDexOptimizer through the local performDexOpt
18622                // method because `pkg` may not be in `mPackages` yet.
18623                //
18624                // Also, don't fail application installs if the dexopt step fails.
18625                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18626                        REASON_INSTALL,
18627                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18628                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18629                        null /* instructionSets */,
18630                        getOrCreateCompilerPackageStats(pkg),
18631                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18632                        dexoptOptions);
18633                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18634            }
18635
18636            // Notify BackgroundDexOptService that the package has been changed.
18637            // If this is an update of a package which used to fail to compile,
18638            // BDOS will remove it from its blacklist.
18639            // TODO: Layering violation
18640            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18641        }
18642
18643        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18644            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18645            return;
18646        }
18647
18648        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18649
18650        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18651                "installPackageLI")) {
18652            if (replace) {
18653                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18654                    // Static libs have a synthetic package name containing the version
18655                    // and cannot be updated as an update would get a new package name,
18656                    // unless this is the exact same version code which is useful for
18657                    // development.
18658                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18659                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18660                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18661                                + "static-shared libs cannot be updated");
18662                        return;
18663                    }
18664                }
18665                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18666                        installerPackageName, res, args.installReason);
18667            } else {
18668                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18669                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18670            }
18671        }
18672
18673        synchronized (mPackages) {
18674            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18675            if (ps != null) {
18676                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18677                ps.setUpdateAvailable(false /*updateAvailable*/);
18678            }
18679
18680            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18681            for (int i = 0; i < childCount; i++) {
18682                PackageParser.Package childPkg = pkg.childPackages.get(i);
18683                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18684                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18685                if (childPs != null) {
18686                    childRes.newUsers = childPs.queryInstalledUsers(
18687                            sUserManager.getUserIds(), true);
18688                }
18689            }
18690
18691            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18692                updateSequenceNumberLP(ps, res.newUsers);
18693                updateInstantAppInstallerLocked(pkgName);
18694            }
18695        }
18696    }
18697
18698    private void startIntentFilterVerifications(int userId, boolean replacing,
18699            PackageParser.Package pkg) {
18700        if (mIntentFilterVerifierComponent == null) {
18701            Slog.w(TAG, "No IntentFilter verification will not be done as "
18702                    + "there is no IntentFilterVerifier available!");
18703            return;
18704        }
18705
18706        final int verifierUid = getPackageUid(
18707                mIntentFilterVerifierComponent.getPackageName(),
18708                MATCH_DEBUG_TRIAGED_MISSING,
18709                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18710
18711        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18712        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18713        mHandler.sendMessage(msg);
18714
18715        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18716        for (int i = 0; i < childCount; i++) {
18717            PackageParser.Package childPkg = pkg.childPackages.get(i);
18718            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18719            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18720            mHandler.sendMessage(msg);
18721        }
18722    }
18723
18724    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18725            PackageParser.Package pkg) {
18726        int size = pkg.activities.size();
18727        if (size == 0) {
18728            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18729                    "No activity, so no need to verify any IntentFilter!");
18730            return;
18731        }
18732
18733        final boolean hasDomainURLs = hasDomainURLs(pkg);
18734        if (!hasDomainURLs) {
18735            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18736                    "No domain URLs, so no need to verify any IntentFilter!");
18737            return;
18738        }
18739
18740        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18741                + " if any IntentFilter from the " + size
18742                + " Activities needs verification ...");
18743
18744        int count = 0;
18745        final String packageName = pkg.packageName;
18746
18747        synchronized (mPackages) {
18748            // If this is a new install and we see that we've already run verification for this
18749            // package, we have nothing to do: it means the state was restored from backup.
18750            if (!replacing) {
18751                IntentFilterVerificationInfo ivi =
18752                        mSettings.getIntentFilterVerificationLPr(packageName);
18753                if (ivi != null) {
18754                    if (DEBUG_DOMAIN_VERIFICATION) {
18755                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18756                                + ivi.getStatusString());
18757                    }
18758                    return;
18759                }
18760            }
18761
18762            // If any filters need to be verified, then all need to be.
18763            boolean needToVerify = false;
18764            for (PackageParser.Activity a : pkg.activities) {
18765                for (ActivityIntentInfo filter : a.intents) {
18766                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18767                        if (DEBUG_DOMAIN_VERIFICATION) {
18768                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18769                        }
18770                        needToVerify = true;
18771                        break;
18772                    }
18773                }
18774            }
18775
18776            if (needToVerify) {
18777                final int verificationId = mIntentFilterVerificationToken++;
18778                for (PackageParser.Activity a : pkg.activities) {
18779                    for (ActivityIntentInfo filter : a.intents) {
18780                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18781                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18782                                    "Verification needed for IntentFilter:" + filter.toString());
18783                            mIntentFilterVerifier.addOneIntentFilterVerification(
18784                                    verifierUid, userId, verificationId, filter, packageName);
18785                            count++;
18786                        }
18787                    }
18788                }
18789            }
18790        }
18791
18792        if (count > 0) {
18793            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18794                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18795                    +  " for userId:" + userId);
18796            mIntentFilterVerifier.startVerifications(userId);
18797        } else {
18798            if (DEBUG_DOMAIN_VERIFICATION) {
18799                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18800            }
18801        }
18802    }
18803
18804    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18805        final ComponentName cn  = filter.activity.getComponentName();
18806        final String packageName = cn.getPackageName();
18807
18808        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18809                packageName);
18810        if (ivi == null) {
18811            return true;
18812        }
18813        int status = ivi.getStatus();
18814        switch (status) {
18815            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18816            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18817                return true;
18818
18819            default:
18820                // Nothing to do
18821                return false;
18822        }
18823    }
18824
18825    private static boolean isMultiArch(ApplicationInfo info) {
18826        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18827    }
18828
18829    private static boolean isExternal(PackageParser.Package pkg) {
18830        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18831    }
18832
18833    private static boolean isExternal(PackageSetting ps) {
18834        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18835    }
18836
18837    private static boolean isSystemApp(PackageParser.Package pkg) {
18838        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18839    }
18840
18841    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18842        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18843    }
18844
18845    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18846        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18847    }
18848
18849    private static boolean isSystemApp(PackageSetting ps) {
18850        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18851    }
18852
18853    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18854        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18855    }
18856
18857    private int packageFlagsToInstallFlags(PackageSetting ps) {
18858        int installFlags = 0;
18859        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18860            // This existing package was an external ASEC install when we have
18861            // the external flag without a UUID
18862            installFlags |= PackageManager.INSTALL_EXTERNAL;
18863        }
18864        if (ps.isForwardLocked()) {
18865            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18866        }
18867        return installFlags;
18868    }
18869
18870    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18871        if (isExternal(pkg)) {
18872            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18873                return StorageManager.UUID_PRIMARY_PHYSICAL;
18874            } else {
18875                return pkg.volumeUuid;
18876            }
18877        } else {
18878            return StorageManager.UUID_PRIVATE_INTERNAL;
18879        }
18880    }
18881
18882    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18883        if (isExternal(pkg)) {
18884            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18885                return mSettings.getExternalVersion();
18886            } else {
18887                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18888            }
18889        } else {
18890            return mSettings.getInternalVersion();
18891        }
18892    }
18893
18894    private void deleteTempPackageFiles() {
18895        final FilenameFilter filter = new FilenameFilter() {
18896            public boolean accept(File dir, String name) {
18897                return name.startsWith("vmdl") && name.endsWith(".tmp");
18898            }
18899        };
18900        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18901            file.delete();
18902        }
18903    }
18904
18905    @Override
18906    public void deletePackageAsUser(String packageName, int versionCode,
18907            IPackageDeleteObserver observer, int userId, int flags) {
18908        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18909                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18910    }
18911
18912    @Override
18913    public void deletePackageVersioned(VersionedPackage versionedPackage,
18914            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18915        final int callingUid = Binder.getCallingUid();
18916        mContext.enforceCallingOrSelfPermission(
18917                android.Manifest.permission.DELETE_PACKAGES, null);
18918        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18919        Preconditions.checkNotNull(versionedPackage);
18920        Preconditions.checkNotNull(observer);
18921        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18922                PackageManager.VERSION_CODE_HIGHEST,
18923                Integer.MAX_VALUE, "versionCode must be >= -1");
18924
18925        final String packageName = versionedPackage.getPackageName();
18926        final int versionCode = versionedPackage.getVersionCode();
18927        final String internalPackageName;
18928        synchronized (mPackages) {
18929            // Normalize package name to handle renamed packages and static libs
18930            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18931                    versionedPackage.getVersionCode());
18932        }
18933
18934        final int uid = Binder.getCallingUid();
18935        if (!isOrphaned(internalPackageName)
18936                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18937            try {
18938                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18939                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18940                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18941                observer.onUserActionRequired(intent);
18942            } catch (RemoteException re) {
18943            }
18944            return;
18945        }
18946        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18947        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18948        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18949            mContext.enforceCallingOrSelfPermission(
18950                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18951                    "deletePackage for user " + userId);
18952        }
18953
18954        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18955            try {
18956                observer.onPackageDeleted(packageName,
18957                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18958            } catch (RemoteException re) {
18959            }
18960            return;
18961        }
18962
18963        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18964            try {
18965                observer.onPackageDeleted(packageName,
18966                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18967            } catch (RemoteException re) {
18968            }
18969            return;
18970        }
18971
18972        if (DEBUG_REMOVE) {
18973            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18974                    + " deleteAllUsers: " + deleteAllUsers + " version="
18975                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18976                    ? "VERSION_CODE_HIGHEST" : versionCode));
18977        }
18978        // Queue up an async operation since the package deletion may take a little while.
18979        mHandler.post(new Runnable() {
18980            public void run() {
18981                mHandler.removeCallbacks(this);
18982                int returnCode;
18983                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18984                boolean doDeletePackage = true;
18985                if (ps != null) {
18986                    final boolean targetIsInstantApp =
18987                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18988                    doDeletePackage = !targetIsInstantApp
18989                            || canViewInstantApps;
18990                }
18991                if (doDeletePackage) {
18992                    if (!deleteAllUsers) {
18993                        returnCode = deletePackageX(internalPackageName, versionCode,
18994                                userId, deleteFlags);
18995                    } else {
18996                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18997                                internalPackageName, users);
18998                        // If nobody is blocking uninstall, proceed with delete for all users
18999                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19000                            returnCode = deletePackageX(internalPackageName, versionCode,
19001                                    userId, deleteFlags);
19002                        } else {
19003                            // Otherwise uninstall individually for users with blockUninstalls=false
19004                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19005                            for (int userId : users) {
19006                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19007                                    returnCode = deletePackageX(internalPackageName, versionCode,
19008                                            userId, userFlags);
19009                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19010                                        Slog.w(TAG, "Package delete failed for user " + userId
19011                                                + ", returnCode " + returnCode);
19012                                    }
19013                                }
19014                            }
19015                            // The app has only been marked uninstalled for certain users.
19016                            // We still need to report that delete was blocked
19017                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19018                        }
19019                    }
19020                } else {
19021                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19022                }
19023                try {
19024                    observer.onPackageDeleted(packageName, returnCode, null);
19025                } catch (RemoteException e) {
19026                    Log.i(TAG, "Observer no longer exists.");
19027                } //end catch
19028            } //end run
19029        });
19030    }
19031
19032    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19033        if (pkg.staticSharedLibName != null) {
19034            return pkg.manifestPackageName;
19035        }
19036        return pkg.packageName;
19037    }
19038
19039    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19040        // Handle renamed packages
19041        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19042        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19043
19044        // Is this a static library?
19045        SparseArray<SharedLibraryEntry> versionedLib =
19046                mStaticLibsByDeclaringPackage.get(packageName);
19047        if (versionedLib == null || versionedLib.size() <= 0) {
19048            return packageName;
19049        }
19050
19051        // Figure out which lib versions the caller can see
19052        SparseIntArray versionsCallerCanSee = null;
19053        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19054        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19055                && callingAppId != Process.ROOT_UID) {
19056            versionsCallerCanSee = new SparseIntArray();
19057            String libName = versionedLib.valueAt(0).info.getName();
19058            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19059            if (uidPackages != null) {
19060                for (String uidPackage : uidPackages) {
19061                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19062                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19063                    if (libIdx >= 0) {
19064                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19065                        versionsCallerCanSee.append(libVersion, libVersion);
19066                    }
19067                }
19068            }
19069        }
19070
19071        // Caller can see nothing - done
19072        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19073            return packageName;
19074        }
19075
19076        // Find the version the caller can see and the app version code
19077        SharedLibraryEntry highestVersion = null;
19078        final int versionCount = versionedLib.size();
19079        for (int i = 0; i < versionCount; i++) {
19080            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19081            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19082                    libEntry.info.getVersion()) < 0) {
19083                continue;
19084            }
19085            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19086            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19087                if (libVersionCode == versionCode) {
19088                    return libEntry.apk;
19089                }
19090            } else if (highestVersion == null) {
19091                highestVersion = libEntry;
19092            } else if (libVersionCode  > highestVersion.info
19093                    .getDeclaringPackage().getVersionCode()) {
19094                highestVersion = libEntry;
19095            }
19096        }
19097
19098        if (highestVersion != null) {
19099            return highestVersion.apk;
19100        }
19101
19102        return packageName;
19103    }
19104
19105    boolean isCallerVerifier(int callingUid) {
19106        final int callingUserId = UserHandle.getUserId(callingUid);
19107        return mRequiredVerifierPackage != null &&
19108                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19109    }
19110
19111    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19112        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19113              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19114            return true;
19115        }
19116        final int callingUserId = UserHandle.getUserId(callingUid);
19117        // If the caller installed the pkgName, then allow it to silently uninstall.
19118        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19119            return true;
19120        }
19121
19122        // Allow package verifier to silently uninstall.
19123        if (mRequiredVerifierPackage != null &&
19124                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19125            return true;
19126        }
19127
19128        // Allow package uninstaller to silently uninstall.
19129        if (mRequiredUninstallerPackage != null &&
19130                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19131            return true;
19132        }
19133
19134        // Allow storage manager to silently uninstall.
19135        if (mStorageManagerPackage != null &&
19136                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19137            return true;
19138        }
19139
19140        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19141        // uninstall for device owner provisioning.
19142        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19143                == PERMISSION_GRANTED) {
19144            return true;
19145        }
19146
19147        return false;
19148    }
19149
19150    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19151        int[] result = EMPTY_INT_ARRAY;
19152        for (int userId : userIds) {
19153            if (getBlockUninstallForUser(packageName, userId)) {
19154                result = ArrayUtils.appendInt(result, userId);
19155            }
19156        }
19157        return result;
19158    }
19159
19160    @Override
19161    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19162        final int callingUid = Binder.getCallingUid();
19163        if (getInstantAppPackageName(callingUid) != null
19164                && !isCallerSameApp(packageName, callingUid)) {
19165            return false;
19166        }
19167        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19168    }
19169
19170    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19171        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19172                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19173        try {
19174            if (dpm != null) {
19175                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19176                        /* callingUserOnly =*/ false);
19177                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19178                        : deviceOwnerComponentName.getPackageName();
19179                // Does the package contains the device owner?
19180                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19181                // this check is probably not needed, since DO should be registered as a device
19182                // admin on some user too. (Original bug for this: b/17657954)
19183                if (packageName.equals(deviceOwnerPackageName)) {
19184                    return true;
19185                }
19186                // Does it contain a device admin for any user?
19187                int[] users;
19188                if (userId == UserHandle.USER_ALL) {
19189                    users = sUserManager.getUserIds();
19190                } else {
19191                    users = new int[]{userId};
19192                }
19193                for (int i = 0; i < users.length; ++i) {
19194                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19195                        return true;
19196                    }
19197                }
19198            }
19199        } catch (RemoteException e) {
19200        }
19201        return false;
19202    }
19203
19204    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19205        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19206    }
19207
19208    /**
19209     *  This method is an internal method that could be get invoked either
19210     *  to delete an installed package or to clean up a failed installation.
19211     *  After deleting an installed package, a broadcast is sent to notify any
19212     *  listeners that the package has been removed. For cleaning up a failed
19213     *  installation, the broadcast is not necessary since the package's
19214     *  installation wouldn't have sent the initial broadcast either
19215     *  The key steps in deleting a package are
19216     *  deleting the package information in internal structures like mPackages,
19217     *  deleting the packages base directories through installd
19218     *  updating mSettings to reflect current status
19219     *  persisting settings for later use
19220     *  sending a broadcast if necessary
19221     */
19222    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19223        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19224        final boolean res;
19225
19226        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19227                ? UserHandle.USER_ALL : userId;
19228
19229        if (isPackageDeviceAdmin(packageName, removeUser)) {
19230            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19231            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19232        }
19233
19234        PackageSetting uninstalledPs = null;
19235        PackageParser.Package pkg = null;
19236
19237        // for the uninstall-updates case and restricted profiles, remember the per-
19238        // user handle installed state
19239        int[] allUsers;
19240        synchronized (mPackages) {
19241            uninstalledPs = mSettings.mPackages.get(packageName);
19242            if (uninstalledPs == null) {
19243                Slog.w(TAG, "Not removing non-existent package " + packageName);
19244                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19245            }
19246
19247            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19248                    && uninstalledPs.versionCode != versionCode) {
19249                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19250                        + uninstalledPs.versionCode + " != " + versionCode);
19251                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19252            }
19253
19254            // Static shared libs can be declared by any package, so let us not
19255            // allow removing a package if it provides a lib others depend on.
19256            pkg = mPackages.get(packageName);
19257
19258            allUsers = sUserManager.getUserIds();
19259
19260            if (pkg != null && pkg.staticSharedLibName != null) {
19261                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19262                        pkg.staticSharedLibVersion);
19263                if (libEntry != null) {
19264                    for (int currUserId : allUsers) {
19265                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19266                            continue;
19267                        }
19268                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19269                                libEntry.info, 0, currUserId);
19270                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19271                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19272                                    + " hosting lib " + libEntry.info.getName() + " version "
19273                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19274                                    + " for user " + currUserId);
19275                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19276                        }
19277                    }
19278                }
19279            }
19280
19281            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19282        }
19283
19284        final int freezeUser;
19285        if (isUpdatedSystemApp(uninstalledPs)
19286                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19287            // We're downgrading a system app, which will apply to all users, so
19288            // freeze them all during the downgrade
19289            freezeUser = UserHandle.USER_ALL;
19290        } else {
19291            freezeUser = removeUser;
19292        }
19293
19294        synchronized (mInstallLock) {
19295            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19296            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19297                    deleteFlags, "deletePackageX")) {
19298                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19299                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19300            }
19301            synchronized (mPackages) {
19302                if (res) {
19303                    if (pkg != null) {
19304                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19305                    }
19306                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19307                    updateInstantAppInstallerLocked(packageName);
19308                }
19309            }
19310        }
19311
19312        if (res) {
19313            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19314            info.sendPackageRemovedBroadcasts(killApp);
19315            info.sendSystemPackageUpdatedBroadcasts();
19316            info.sendSystemPackageAppearedBroadcasts();
19317        }
19318        // Force a gc here.
19319        Runtime.getRuntime().gc();
19320        // Delete the resources here after sending the broadcast to let
19321        // other processes clean up before deleting resources.
19322        if (info.args != null) {
19323            synchronized (mInstallLock) {
19324                info.args.doPostDeleteLI(true);
19325            }
19326        }
19327
19328        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19329    }
19330
19331    static class PackageRemovedInfo {
19332        final PackageSender packageSender;
19333        String removedPackage;
19334        String installerPackageName;
19335        int uid = -1;
19336        int removedAppId = -1;
19337        int[] origUsers;
19338        int[] removedUsers = null;
19339        int[] broadcastUsers = null;
19340        SparseArray<Integer> installReasons;
19341        boolean isRemovedPackageSystemUpdate = false;
19342        boolean isUpdate;
19343        boolean dataRemoved;
19344        boolean removedForAllUsers;
19345        boolean isStaticSharedLib;
19346        // Clean up resources deleted packages.
19347        InstallArgs args = null;
19348        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19349        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19350
19351        PackageRemovedInfo(PackageSender packageSender) {
19352            this.packageSender = packageSender;
19353        }
19354
19355        void sendPackageRemovedBroadcasts(boolean killApp) {
19356            sendPackageRemovedBroadcastInternal(killApp);
19357            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19358            for (int i = 0; i < childCount; i++) {
19359                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19360                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19361            }
19362        }
19363
19364        void sendSystemPackageUpdatedBroadcasts() {
19365            if (isRemovedPackageSystemUpdate) {
19366                sendSystemPackageUpdatedBroadcastsInternal();
19367                final int childCount = (removedChildPackages != null)
19368                        ? removedChildPackages.size() : 0;
19369                for (int i = 0; i < childCount; i++) {
19370                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19371                    if (childInfo.isRemovedPackageSystemUpdate) {
19372                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19373                    }
19374                }
19375            }
19376        }
19377
19378        void sendSystemPackageAppearedBroadcasts() {
19379            final int packageCount = (appearedChildPackages != null)
19380                    ? appearedChildPackages.size() : 0;
19381            for (int i = 0; i < packageCount; i++) {
19382                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19383                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19384                    true /*sendBootCompleted*/, false /*startReceiver*/,
19385                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19386            }
19387        }
19388
19389        private void sendSystemPackageUpdatedBroadcastsInternal() {
19390            Bundle extras = new Bundle(2);
19391            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19392            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19393            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19394                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19395            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19396                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19397            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19398                null, null, 0, removedPackage, null, null);
19399            if (installerPackageName != null) {
19400                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19401                        removedPackage, extras, 0 /*flags*/,
19402                        installerPackageName, null, null);
19403                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19404                        removedPackage, extras, 0 /*flags*/,
19405                        installerPackageName, null, null);
19406            }
19407        }
19408
19409        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19410            // Don't send static shared library removal broadcasts as these
19411            // libs are visible only the the apps that depend on them an one
19412            // cannot remove the library if it has a dependency.
19413            if (isStaticSharedLib) {
19414                return;
19415            }
19416            Bundle extras = new Bundle(2);
19417            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19418            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19419            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19420            if (isUpdate || isRemovedPackageSystemUpdate) {
19421                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19422            }
19423            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19424            if (removedPackage != null) {
19425                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19426                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19427                if (installerPackageName != null) {
19428                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19429                            removedPackage, extras, 0 /*flags*/,
19430                            installerPackageName, null, broadcastUsers);
19431                }
19432                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19433                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19434                        removedPackage, extras,
19435                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19436                        null, null, broadcastUsers);
19437                }
19438            }
19439            if (removedAppId >= 0) {
19440                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19441                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19442                    null, null, broadcastUsers);
19443            }
19444        }
19445
19446        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19447            removedUsers = userIds;
19448            if (removedUsers == null) {
19449                broadcastUsers = null;
19450                return;
19451            }
19452
19453            broadcastUsers = EMPTY_INT_ARRAY;
19454            for (int i = userIds.length - 1; i >= 0; --i) {
19455                final int userId = userIds[i];
19456                if (deletedPackageSetting.getInstantApp(userId)) {
19457                    continue;
19458                }
19459                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19460            }
19461        }
19462    }
19463
19464    /*
19465     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19466     * flag is not set, the data directory is removed as well.
19467     * make sure this flag is set for partially installed apps. If not its meaningless to
19468     * delete a partially installed application.
19469     */
19470    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19471            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19472        String packageName = ps.name;
19473        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19474        // Retrieve object to delete permissions for shared user later on
19475        final PackageParser.Package deletedPkg;
19476        final PackageSetting deletedPs;
19477        // reader
19478        synchronized (mPackages) {
19479            deletedPkg = mPackages.get(packageName);
19480            deletedPs = mSettings.mPackages.get(packageName);
19481            if (outInfo != null) {
19482                outInfo.removedPackage = packageName;
19483                outInfo.installerPackageName = ps.installerPackageName;
19484                outInfo.isStaticSharedLib = deletedPkg != null
19485                        && deletedPkg.staticSharedLibName != null;
19486                outInfo.populateUsers(deletedPs == null ? null
19487                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19488            }
19489        }
19490
19491        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19492
19493        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19494            final PackageParser.Package resolvedPkg;
19495            if (deletedPkg != null) {
19496                resolvedPkg = deletedPkg;
19497            } else {
19498                // We don't have a parsed package when it lives on an ejected
19499                // adopted storage device, so fake something together
19500                resolvedPkg = new PackageParser.Package(ps.name);
19501                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19502            }
19503            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19504                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19505            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19506            if (outInfo != null) {
19507                outInfo.dataRemoved = true;
19508            }
19509            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19510        }
19511
19512        int removedAppId = -1;
19513
19514        // writer
19515        synchronized (mPackages) {
19516            boolean installedStateChanged = false;
19517            if (deletedPs != null) {
19518                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19519                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19520                    clearDefaultBrowserIfNeeded(packageName);
19521                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19522                    removedAppId = mSettings.removePackageLPw(packageName);
19523                    if (outInfo != null) {
19524                        outInfo.removedAppId = removedAppId;
19525                    }
19526                    updatePermissionsLPw(deletedPs.name, null, 0);
19527                    if (deletedPs.sharedUser != null) {
19528                        // Remove permissions associated with package. Since runtime
19529                        // permissions are per user we have to kill the removed package
19530                        // or packages running under the shared user of the removed
19531                        // package if revoking the permissions requested only by the removed
19532                        // package is successful and this causes a change in gids.
19533                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19534                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19535                                    userId);
19536                            if (userIdToKill == UserHandle.USER_ALL
19537                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19538                                // If gids changed for this user, kill all affected packages.
19539                                mHandler.post(new Runnable() {
19540                                    @Override
19541                                    public void run() {
19542                                        // This has to happen with no lock held.
19543                                        killApplication(deletedPs.name, deletedPs.appId,
19544                                                KILL_APP_REASON_GIDS_CHANGED);
19545                                    }
19546                                });
19547                                break;
19548                            }
19549                        }
19550                    }
19551                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19552                }
19553                // make sure to preserve per-user disabled state if this removal was just
19554                // a downgrade of a system app to the factory package
19555                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19556                    if (DEBUG_REMOVE) {
19557                        Slog.d(TAG, "Propagating install state across downgrade");
19558                    }
19559                    for (int userId : allUserHandles) {
19560                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19561                        if (DEBUG_REMOVE) {
19562                            Slog.d(TAG, "    user " + userId + " => " + installed);
19563                        }
19564                        if (installed != ps.getInstalled(userId)) {
19565                            installedStateChanged = true;
19566                        }
19567                        ps.setInstalled(installed, userId);
19568                    }
19569                }
19570            }
19571            // can downgrade to reader
19572            if (writeSettings) {
19573                // Save settings now
19574                mSettings.writeLPr();
19575            }
19576            if (installedStateChanged) {
19577                mSettings.writeKernelMappingLPr(ps);
19578            }
19579        }
19580        if (removedAppId != -1) {
19581            // A user ID was deleted here. Go through all users and remove it
19582            // from KeyStore.
19583            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19584        }
19585    }
19586
19587    static boolean locationIsPrivileged(File path) {
19588        try {
19589            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19590                    .getCanonicalPath();
19591            return path.getCanonicalPath().startsWith(privilegedAppDir);
19592        } catch (IOException e) {
19593            Slog.e(TAG, "Unable to access code path " + path);
19594        }
19595        return false;
19596    }
19597
19598    /*
19599     * Tries to delete system package.
19600     */
19601    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19602            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19603            boolean writeSettings) {
19604        if (deletedPs.parentPackageName != null) {
19605            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19606            return false;
19607        }
19608
19609        final boolean applyUserRestrictions
19610                = (allUserHandles != null) && (outInfo.origUsers != null);
19611        final PackageSetting disabledPs;
19612        // Confirm if the system package has been updated
19613        // An updated system app can be deleted. This will also have to restore
19614        // the system pkg from system partition
19615        // reader
19616        synchronized (mPackages) {
19617            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19618        }
19619
19620        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19621                + " disabledPs=" + disabledPs);
19622
19623        if (disabledPs == null) {
19624            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19625            return false;
19626        } else if (DEBUG_REMOVE) {
19627            Slog.d(TAG, "Deleting system pkg from data partition");
19628        }
19629
19630        if (DEBUG_REMOVE) {
19631            if (applyUserRestrictions) {
19632                Slog.d(TAG, "Remembering install states:");
19633                for (int userId : allUserHandles) {
19634                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19635                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19636                }
19637            }
19638        }
19639
19640        // Delete the updated package
19641        outInfo.isRemovedPackageSystemUpdate = true;
19642        if (outInfo.removedChildPackages != null) {
19643            final int childCount = (deletedPs.childPackageNames != null)
19644                    ? deletedPs.childPackageNames.size() : 0;
19645            for (int i = 0; i < childCount; i++) {
19646                String childPackageName = deletedPs.childPackageNames.get(i);
19647                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19648                        .contains(childPackageName)) {
19649                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19650                            childPackageName);
19651                    if (childInfo != null) {
19652                        childInfo.isRemovedPackageSystemUpdate = true;
19653                    }
19654                }
19655            }
19656        }
19657
19658        if (disabledPs.versionCode < deletedPs.versionCode) {
19659            // Delete data for downgrades
19660            flags &= ~PackageManager.DELETE_KEEP_DATA;
19661        } else {
19662            // Preserve data by setting flag
19663            flags |= PackageManager.DELETE_KEEP_DATA;
19664        }
19665
19666        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19667                outInfo, writeSettings, disabledPs.pkg);
19668        if (!ret) {
19669            return false;
19670        }
19671
19672        // writer
19673        synchronized (mPackages) {
19674            // NOTE: The system package always needs to be enabled; even if it's for
19675            // a compressed stub. If we don't, installing the system package fails
19676            // during scan [scanning checks the disabled packages]. We will reverse
19677            // this later, after we've "installed" the stub.
19678            // Reinstate the old system package
19679            enableSystemPackageLPw(disabledPs.pkg);
19680            // Remove any native libraries from the upgraded package.
19681            removeNativeBinariesLI(deletedPs);
19682        }
19683
19684        // Install the system package
19685        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19686        try {
19687            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19688                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19689        } catch (PackageManagerException e) {
19690            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19691                    + e.getMessage());
19692            return false;
19693        } finally {
19694            if (disabledPs.pkg.isStub) {
19695                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19696            }
19697        }
19698        return true;
19699    }
19700
19701    /**
19702     * Installs a package that's already on the system partition.
19703     */
19704    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19705            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19706            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19707                    throws PackageManagerException {
19708        int parseFlags = mDefParseFlags
19709                | PackageParser.PARSE_MUST_BE_APK
19710                | PackageParser.PARSE_IS_SYSTEM
19711                | PackageParser.PARSE_IS_SYSTEM_DIR;
19712        if (isPrivileged || locationIsPrivileged(codePath)) {
19713            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19714        }
19715
19716        final PackageParser.Package newPkg =
19717                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19718
19719        try {
19720            // update shared libraries for the newly re-installed system package
19721            updateSharedLibrariesLPr(newPkg, null);
19722        } catch (PackageManagerException e) {
19723            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19724        }
19725
19726        prepareAppDataAfterInstallLIF(newPkg);
19727
19728        // writer
19729        synchronized (mPackages) {
19730            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19731
19732            // Propagate the permissions state as we do not want to drop on the floor
19733            // runtime permissions. The update permissions method below will take
19734            // care of removing obsolete permissions and grant install permissions.
19735            if (origPermissionState != null) {
19736                ps.getPermissionsState().copyFrom(origPermissionState);
19737            }
19738            updatePermissionsLPw(newPkg.packageName, newPkg,
19739                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19740
19741            final boolean applyUserRestrictions
19742                    = (allUserHandles != null) && (origUserHandles != null);
19743            if (applyUserRestrictions) {
19744                boolean installedStateChanged = false;
19745                if (DEBUG_REMOVE) {
19746                    Slog.d(TAG, "Propagating install state across reinstall");
19747                }
19748                for (int userId : allUserHandles) {
19749                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19750                    if (DEBUG_REMOVE) {
19751                        Slog.d(TAG, "    user " + userId + " => " + installed);
19752                    }
19753                    if (installed != ps.getInstalled(userId)) {
19754                        installedStateChanged = true;
19755                    }
19756                    ps.setInstalled(installed, userId);
19757
19758                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19759                }
19760                // Regardless of writeSettings we need to ensure that this restriction
19761                // state propagation is persisted
19762                mSettings.writeAllUsersPackageRestrictionsLPr();
19763                if (installedStateChanged) {
19764                    mSettings.writeKernelMappingLPr(ps);
19765                }
19766            }
19767            // can downgrade to reader here
19768            if (writeSettings) {
19769                mSettings.writeLPr();
19770            }
19771        }
19772        return newPkg;
19773    }
19774
19775    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19776            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19777            PackageRemovedInfo outInfo, boolean writeSettings,
19778            PackageParser.Package replacingPackage) {
19779        synchronized (mPackages) {
19780            if (outInfo != null) {
19781                outInfo.uid = ps.appId;
19782            }
19783
19784            if (outInfo != null && outInfo.removedChildPackages != null) {
19785                final int childCount = (ps.childPackageNames != null)
19786                        ? ps.childPackageNames.size() : 0;
19787                for (int i = 0; i < childCount; i++) {
19788                    String childPackageName = ps.childPackageNames.get(i);
19789                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19790                    if (childPs == null) {
19791                        return false;
19792                    }
19793                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19794                            childPackageName);
19795                    if (childInfo != null) {
19796                        childInfo.uid = childPs.appId;
19797                    }
19798                }
19799            }
19800        }
19801
19802        // Delete package data from internal structures and also remove data if flag is set
19803        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19804
19805        // Delete the child packages data
19806        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19807        for (int i = 0; i < childCount; i++) {
19808            PackageSetting childPs;
19809            synchronized (mPackages) {
19810                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19811            }
19812            if (childPs != null) {
19813                PackageRemovedInfo childOutInfo = (outInfo != null
19814                        && outInfo.removedChildPackages != null)
19815                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19816                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19817                        && (replacingPackage != null
19818                        && !replacingPackage.hasChildPackage(childPs.name))
19819                        ? flags & ~DELETE_KEEP_DATA : flags;
19820                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19821                        deleteFlags, writeSettings);
19822            }
19823        }
19824
19825        // Delete application code and resources only for parent packages
19826        if (ps.parentPackageName == null) {
19827            if (deleteCodeAndResources && (outInfo != null)) {
19828                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19829                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19830                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19831            }
19832        }
19833
19834        return true;
19835    }
19836
19837    @Override
19838    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19839            int userId) {
19840        mContext.enforceCallingOrSelfPermission(
19841                android.Manifest.permission.DELETE_PACKAGES, null);
19842        synchronized (mPackages) {
19843            // Cannot block uninstall of static shared libs as they are
19844            // considered a part of the using app (emulating static linking).
19845            // Also static libs are installed always on internal storage.
19846            PackageParser.Package pkg = mPackages.get(packageName);
19847            if (pkg != null && pkg.staticSharedLibName != null) {
19848                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19849                        + " providing static shared library: " + pkg.staticSharedLibName);
19850                return false;
19851            }
19852            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19853            mSettings.writePackageRestrictionsLPr(userId);
19854        }
19855        return true;
19856    }
19857
19858    @Override
19859    public boolean getBlockUninstallForUser(String packageName, int userId) {
19860        synchronized (mPackages) {
19861            final PackageSetting ps = mSettings.mPackages.get(packageName);
19862            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19863                return false;
19864            }
19865            return mSettings.getBlockUninstallLPr(userId, packageName);
19866        }
19867    }
19868
19869    @Override
19870    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19871        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19872        synchronized (mPackages) {
19873            PackageSetting ps = mSettings.mPackages.get(packageName);
19874            if (ps == null) {
19875                Log.w(TAG, "Package doesn't exist: " + packageName);
19876                return false;
19877            }
19878            if (systemUserApp) {
19879                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19880            } else {
19881                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19882            }
19883            mSettings.writeLPr();
19884        }
19885        return true;
19886    }
19887
19888    /*
19889     * This method handles package deletion in general
19890     */
19891    private boolean deletePackageLIF(String packageName, UserHandle user,
19892            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19893            PackageRemovedInfo outInfo, boolean writeSettings,
19894            PackageParser.Package replacingPackage) {
19895        if (packageName == null) {
19896            Slog.w(TAG, "Attempt to delete null packageName.");
19897            return false;
19898        }
19899
19900        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19901
19902        PackageSetting ps;
19903        synchronized (mPackages) {
19904            ps = mSettings.mPackages.get(packageName);
19905            if (ps == null) {
19906                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19907                return false;
19908            }
19909
19910            if (ps.parentPackageName != null && (!isSystemApp(ps)
19911                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19912                if (DEBUG_REMOVE) {
19913                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19914                            + ((user == null) ? UserHandle.USER_ALL : user));
19915                }
19916                final int removedUserId = (user != null) ? user.getIdentifier()
19917                        : UserHandle.USER_ALL;
19918                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19919                    return false;
19920                }
19921                markPackageUninstalledForUserLPw(ps, user);
19922                scheduleWritePackageRestrictionsLocked(user);
19923                return true;
19924            }
19925        }
19926
19927        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19928                && user.getIdentifier() != UserHandle.USER_ALL)) {
19929            // The caller is asking that the package only be deleted for a single
19930            // user.  To do this, we just mark its uninstalled state and delete
19931            // its data. If this is a system app, we only allow this to happen if
19932            // they have set the special DELETE_SYSTEM_APP which requests different
19933            // semantics than normal for uninstalling system apps.
19934            markPackageUninstalledForUserLPw(ps, user);
19935
19936            if (!isSystemApp(ps)) {
19937                // Do not uninstall the APK if an app should be cached
19938                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19939                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19940                    // Other user still have this package installed, so all
19941                    // we need to do is clear this user's data and save that
19942                    // it is uninstalled.
19943                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19944                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19945                        return false;
19946                    }
19947                    scheduleWritePackageRestrictionsLocked(user);
19948                    return true;
19949                } else {
19950                    // We need to set it back to 'installed' so the uninstall
19951                    // broadcasts will be sent correctly.
19952                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19953                    ps.setInstalled(true, user.getIdentifier());
19954                    mSettings.writeKernelMappingLPr(ps);
19955                }
19956            } else {
19957                // This is a system app, so we assume that the
19958                // other users still have this package installed, so all
19959                // we need to do is clear this user's data and save that
19960                // it is uninstalled.
19961                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19962                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19963                    return false;
19964                }
19965                scheduleWritePackageRestrictionsLocked(user);
19966                return true;
19967            }
19968        }
19969
19970        // If we are deleting a composite package for all users, keep track
19971        // of result for each child.
19972        if (ps.childPackageNames != null && outInfo != null) {
19973            synchronized (mPackages) {
19974                final int childCount = ps.childPackageNames.size();
19975                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19976                for (int i = 0; i < childCount; i++) {
19977                    String childPackageName = ps.childPackageNames.get(i);
19978                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19979                    childInfo.removedPackage = childPackageName;
19980                    childInfo.installerPackageName = ps.installerPackageName;
19981                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19982                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19983                    if (childPs != null) {
19984                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19985                    }
19986                }
19987            }
19988        }
19989
19990        boolean ret = false;
19991        if (isSystemApp(ps)) {
19992            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19993            // When an updated system application is deleted we delete the existing resources
19994            // as well and fall back to existing code in system partition
19995            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19996        } else {
19997            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19998            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19999                    outInfo, writeSettings, replacingPackage);
20000        }
20001
20002        // Take a note whether we deleted the package for all users
20003        if (outInfo != null) {
20004            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20005            if (outInfo.removedChildPackages != null) {
20006                synchronized (mPackages) {
20007                    final int childCount = outInfo.removedChildPackages.size();
20008                    for (int i = 0; i < childCount; i++) {
20009                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20010                        if (childInfo != null) {
20011                            childInfo.removedForAllUsers = mPackages.get(
20012                                    childInfo.removedPackage) == null;
20013                        }
20014                    }
20015                }
20016            }
20017            // If we uninstalled an update to a system app there may be some
20018            // child packages that appeared as they are declared in the system
20019            // app but were not declared in the update.
20020            if (isSystemApp(ps)) {
20021                synchronized (mPackages) {
20022                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20023                    final int childCount = (updatedPs.childPackageNames != null)
20024                            ? updatedPs.childPackageNames.size() : 0;
20025                    for (int i = 0; i < childCount; i++) {
20026                        String childPackageName = updatedPs.childPackageNames.get(i);
20027                        if (outInfo.removedChildPackages == null
20028                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20029                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20030                            if (childPs == null) {
20031                                continue;
20032                            }
20033                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20034                            installRes.name = childPackageName;
20035                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20036                            installRes.pkg = mPackages.get(childPackageName);
20037                            installRes.uid = childPs.pkg.applicationInfo.uid;
20038                            if (outInfo.appearedChildPackages == null) {
20039                                outInfo.appearedChildPackages = new ArrayMap<>();
20040                            }
20041                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20042                        }
20043                    }
20044                }
20045            }
20046        }
20047
20048        return ret;
20049    }
20050
20051    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20052        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20053                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20054        for (int nextUserId : userIds) {
20055            if (DEBUG_REMOVE) {
20056                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20057            }
20058            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20059                    false /*installed*/,
20060                    true /*stopped*/,
20061                    true /*notLaunched*/,
20062                    false /*hidden*/,
20063                    false /*suspended*/,
20064                    false /*instantApp*/,
20065                    false /*virtualPreload*/,
20066                    null /*lastDisableAppCaller*/,
20067                    null /*enabledComponents*/,
20068                    null /*disabledComponents*/,
20069                    ps.readUserState(nextUserId).domainVerificationStatus,
20070                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20071        }
20072        mSettings.writeKernelMappingLPr(ps);
20073    }
20074
20075    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20076            PackageRemovedInfo outInfo) {
20077        final PackageParser.Package pkg;
20078        synchronized (mPackages) {
20079            pkg = mPackages.get(ps.name);
20080        }
20081
20082        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20083                : new int[] {userId};
20084        for (int nextUserId : userIds) {
20085            if (DEBUG_REMOVE) {
20086                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20087                        + nextUserId);
20088            }
20089
20090            destroyAppDataLIF(pkg, userId,
20091                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20092            destroyAppProfilesLIF(pkg, userId);
20093            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20094            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20095            schedulePackageCleaning(ps.name, nextUserId, false);
20096            synchronized (mPackages) {
20097                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20098                    scheduleWritePackageRestrictionsLocked(nextUserId);
20099                }
20100                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20101            }
20102        }
20103
20104        if (outInfo != null) {
20105            outInfo.removedPackage = ps.name;
20106            outInfo.installerPackageName = ps.installerPackageName;
20107            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20108            outInfo.removedAppId = ps.appId;
20109            outInfo.removedUsers = userIds;
20110            outInfo.broadcastUsers = userIds;
20111        }
20112
20113        return true;
20114    }
20115
20116    private final class ClearStorageConnection implements ServiceConnection {
20117        IMediaContainerService mContainerService;
20118
20119        @Override
20120        public void onServiceConnected(ComponentName name, IBinder service) {
20121            synchronized (this) {
20122                mContainerService = IMediaContainerService.Stub
20123                        .asInterface(Binder.allowBlocking(service));
20124                notifyAll();
20125            }
20126        }
20127
20128        @Override
20129        public void onServiceDisconnected(ComponentName name) {
20130        }
20131    }
20132
20133    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20134        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20135
20136        final boolean mounted;
20137        if (Environment.isExternalStorageEmulated()) {
20138            mounted = true;
20139        } else {
20140            final String status = Environment.getExternalStorageState();
20141
20142            mounted = status.equals(Environment.MEDIA_MOUNTED)
20143                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20144        }
20145
20146        if (!mounted) {
20147            return;
20148        }
20149
20150        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20151        int[] users;
20152        if (userId == UserHandle.USER_ALL) {
20153            users = sUserManager.getUserIds();
20154        } else {
20155            users = new int[] { userId };
20156        }
20157        final ClearStorageConnection conn = new ClearStorageConnection();
20158        if (mContext.bindServiceAsUser(
20159                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20160            try {
20161                for (int curUser : users) {
20162                    long timeout = SystemClock.uptimeMillis() + 5000;
20163                    synchronized (conn) {
20164                        long now;
20165                        while (conn.mContainerService == null &&
20166                                (now = SystemClock.uptimeMillis()) < timeout) {
20167                            try {
20168                                conn.wait(timeout - now);
20169                            } catch (InterruptedException e) {
20170                            }
20171                        }
20172                    }
20173                    if (conn.mContainerService == null) {
20174                        return;
20175                    }
20176
20177                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20178                    clearDirectory(conn.mContainerService,
20179                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20180                    if (allData) {
20181                        clearDirectory(conn.mContainerService,
20182                                userEnv.buildExternalStorageAppDataDirs(packageName));
20183                        clearDirectory(conn.mContainerService,
20184                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20185                    }
20186                }
20187            } finally {
20188                mContext.unbindService(conn);
20189            }
20190        }
20191    }
20192
20193    @Override
20194    public void clearApplicationProfileData(String packageName) {
20195        enforceSystemOrRoot("Only the system can clear all profile data");
20196
20197        final PackageParser.Package pkg;
20198        synchronized (mPackages) {
20199            pkg = mPackages.get(packageName);
20200        }
20201
20202        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20203            synchronized (mInstallLock) {
20204                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20205            }
20206        }
20207    }
20208
20209    @Override
20210    public void clearApplicationUserData(final String packageName,
20211            final IPackageDataObserver observer, final int userId) {
20212        mContext.enforceCallingOrSelfPermission(
20213                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20214
20215        final int callingUid = Binder.getCallingUid();
20216        enforceCrossUserPermission(callingUid, userId,
20217                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20218
20219        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20220        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20221            return;
20222        }
20223        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20224            throw new SecurityException("Cannot clear data for a protected package: "
20225                    + packageName);
20226        }
20227        // Queue up an async operation since the package deletion may take a little while.
20228        mHandler.post(new Runnable() {
20229            public void run() {
20230                mHandler.removeCallbacks(this);
20231                final boolean succeeded;
20232                try (PackageFreezer freezer = freezePackage(packageName,
20233                        "clearApplicationUserData")) {
20234                    synchronized (mInstallLock) {
20235                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20236                    }
20237                    clearExternalStorageDataSync(packageName, userId, true);
20238                    synchronized (mPackages) {
20239                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20240                                packageName, userId);
20241                    }
20242                }
20243                if (succeeded) {
20244                    // invoke DeviceStorageMonitor's update method to clear any notifications
20245                    DeviceStorageMonitorInternal dsm = LocalServices
20246                            .getService(DeviceStorageMonitorInternal.class);
20247                    if (dsm != null) {
20248                        dsm.checkMemory();
20249                    }
20250                }
20251                if(observer != null) {
20252                    try {
20253                        observer.onRemoveCompleted(packageName, succeeded);
20254                    } catch (RemoteException e) {
20255                        Log.i(TAG, "Observer no longer exists.");
20256                    }
20257                } //end if observer
20258            } //end run
20259        });
20260    }
20261
20262    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20263        if (packageName == null) {
20264            Slog.w(TAG, "Attempt to delete null packageName.");
20265            return false;
20266        }
20267
20268        // Try finding details about the requested package
20269        PackageParser.Package pkg;
20270        synchronized (mPackages) {
20271            pkg = mPackages.get(packageName);
20272            if (pkg == null) {
20273                final PackageSetting ps = mSettings.mPackages.get(packageName);
20274                if (ps != null) {
20275                    pkg = ps.pkg;
20276                }
20277            }
20278
20279            if (pkg == null) {
20280                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20281                return false;
20282            }
20283
20284            PackageSetting ps = (PackageSetting) pkg.mExtras;
20285            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20286        }
20287
20288        clearAppDataLIF(pkg, userId,
20289                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20290
20291        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20292        removeKeystoreDataIfNeeded(userId, appId);
20293
20294        UserManagerInternal umInternal = getUserManagerInternal();
20295        final int flags;
20296        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20297            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20298        } else if (umInternal.isUserRunning(userId)) {
20299            flags = StorageManager.FLAG_STORAGE_DE;
20300        } else {
20301            flags = 0;
20302        }
20303        prepareAppDataContentsLIF(pkg, userId, flags);
20304
20305        return true;
20306    }
20307
20308    /**
20309     * Reverts user permission state changes (permissions and flags) in
20310     * all packages for a given user.
20311     *
20312     * @param userId The device user for which to do a reset.
20313     */
20314    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20315        final int packageCount = mPackages.size();
20316        for (int i = 0; i < packageCount; i++) {
20317            PackageParser.Package pkg = mPackages.valueAt(i);
20318            PackageSetting ps = (PackageSetting) pkg.mExtras;
20319            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20320        }
20321    }
20322
20323    private void resetNetworkPolicies(int userId) {
20324        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20325    }
20326
20327    /**
20328     * Reverts user permission state changes (permissions and flags).
20329     *
20330     * @param ps The package for which to reset.
20331     * @param userId The device user for which to do a reset.
20332     */
20333    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20334            final PackageSetting ps, final int userId) {
20335        if (ps.pkg == null) {
20336            return;
20337        }
20338
20339        // These are flags that can change base on user actions.
20340        final int userSettableMask = FLAG_PERMISSION_USER_SET
20341                | FLAG_PERMISSION_USER_FIXED
20342                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20343                | FLAG_PERMISSION_REVIEW_REQUIRED;
20344
20345        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20346                | FLAG_PERMISSION_POLICY_FIXED;
20347
20348        boolean writeInstallPermissions = false;
20349        boolean writeRuntimePermissions = false;
20350
20351        final int permissionCount = ps.pkg.requestedPermissions.size();
20352        for (int i = 0; i < permissionCount; i++) {
20353            String permission = ps.pkg.requestedPermissions.get(i);
20354
20355            BasePermission bp = mSettings.mPermissions.get(permission);
20356            if (bp == null) {
20357                continue;
20358            }
20359
20360            // If shared user we just reset the state to which only this app contributed.
20361            if (ps.sharedUser != null) {
20362                boolean used = false;
20363                final int packageCount = ps.sharedUser.packages.size();
20364                for (int j = 0; j < packageCount; j++) {
20365                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20366                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20367                            && pkg.pkg.requestedPermissions.contains(permission)) {
20368                        used = true;
20369                        break;
20370                    }
20371                }
20372                if (used) {
20373                    continue;
20374                }
20375            }
20376
20377            PermissionsState permissionsState = ps.getPermissionsState();
20378
20379            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20380
20381            // Always clear the user settable flags.
20382            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20383                    bp.name) != null;
20384            // If permission review is enabled and this is a legacy app, mark the
20385            // permission as requiring a review as this is the initial state.
20386            int flags = 0;
20387            if (mPermissionReviewRequired
20388                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20389                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20390            }
20391            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20392                if (hasInstallState) {
20393                    writeInstallPermissions = true;
20394                } else {
20395                    writeRuntimePermissions = true;
20396                }
20397            }
20398
20399            // Below is only runtime permission handling.
20400            if (!bp.isRuntime()) {
20401                continue;
20402            }
20403
20404            // Never clobber system or policy.
20405            if ((oldFlags & policyOrSystemFlags) != 0) {
20406                continue;
20407            }
20408
20409            // If this permission was granted by default, make sure it is.
20410            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20411                if (permissionsState.grantRuntimePermission(bp, userId)
20412                        != PERMISSION_OPERATION_FAILURE) {
20413                    writeRuntimePermissions = true;
20414                }
20415            // If permission review is enabled the permissions for a legacy apps
20416            // are represented as constantly granted runtime ones, so don't revoke.
20417            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20418                // Otherwise, reset the permission.
20419                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20420                switch (revokeResult) {
20421                    case PERMISSION_OPERATION_SUCCESS:
20422                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20423                        writeRuntimePermissions = true;
20424                        final int appId = ps.appId;
20425                        mHandler.post(new Runnable() {
20426                            @Override
20427                            public void run() {
20428                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20429                            }
20430                        });
20431                    } break;
20432                }
20433            }
20434        }
20435
20436        // Synchronously write as we are taking permissions away.
20437        if (writeRuntimePermissions) {
20438            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20439        }
20440
20441        // Synchronously write as we are taking permissions away.
20442        if (writeInstallPermissions) {
20443            mSettings.writeLPr();
20444        }
20445    }
20446
20447    /**
20448     * Remove entries from the keystore daemon. Will only remove it if the
20449     * {@code appId} is valid.
20450     */
20451    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20452        if (appId < 0) {
20453            return;
20454        }
20455
20456        final KeyStore keyStore = KeyStore.getInstance();
20457        if (keyStore != null) {
20458            if (userId == UserHandle.USER_ALL) {
20459                for (final int individual : sUserManager.getUserIds()) {
20460                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20461                }
20462            } else {
20463                keyStore.clearUid(UserHandle.getUid(userId, appId));
20464            }
20465        } else {
20466            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20467        }
20468    }
20469
20470    @Override
20471    public void deleteApplicationCacheFiles(final String packageName,
20472            final IPackageDataObserver observer) {
20473        final int userId = UserHandle.getCallingUserId();
20474        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20475    }
20476
20477    @Override
20478    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20479            final IPackageDataObserver observer) {
20480        final int callingUid = Binder.getCallingUid();
20481        mContext.enforceCallingOrSelfPermission(
20482                android.Manifest.permission.DELETE_CACHE_FILES, null);
20483        enforceCrossUserPermission(callingUid, userId,
20484                /* requireFullPermission= */ true, /* checkShell= */ false,
20485                "delete application cache files");
20486        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20487                android.Manifest.permission.ACCESS_INSTANT_APPS);
20488
20489        final PackageParser.Package pkg;
20490        synchronized (mPackages) {
20491            pkg = mPackages.get(packageName);
20492        }
20493
20494        // Queue up an async operation since the package deletion may take a little while.
20495        mHandler.post(new Runnable() {
20496            public void run() {
20497                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20498                boolean doClearData = true;
20499                if (ps != null) {
20500                    final boolean targetIsInstantApp =
20501                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20502                    doClearData = !targetIsInstantApp
20503                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20504                }
20505                if (doClearData) {
20506                    synchronized (mInstallLock) {
20507                        final int flags = StorageManager.FLAG_STORAGE_DE
20508                                | StorageManager.FLAG_STORAGE_CE;
20509                        // We're only clearing cache files, so we don't care if the
20510                        // app is unfrozen and still able to run
20511                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20512                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20513                    }
20514                    clearExternalStorageDataSync(packageName, userId, false);
20515                }
20516                if (observer != null) {
20517                    try {
20518                        observer.onRemoveCompleted(packageName, true);
20519                    } catch (RemoteException e) {
20520                        Log.i(TAG, "Observer no longer exists.");
20521                    }
20522                }
20523            }
20524        });
20525    }
20526
20527    @Override
20528    public void getPackageSizeInfo(final String packageName, int userHandle,
20529            final IPackageStatsObserver observer) {
20530        throw new UnsupportedOperationException(
20531                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20532    }
20533
20534    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20535        final PackageSetting ps;
20536        synchronized (mPackages) {
20537            ps = mSettings.mPackages.get(packageName);
20538            if (ps == null) {
20539                Slog.w(TAG, "Failed to find settings for " + packageName);
20540                return false;
20541            }
20542        }
20543
20544        final String[] packageNames = { packageName };
20545        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20546        final String[] codePaths = { ps.codePathString };
20547
20548        try {
20549            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20550                    ps.appId, ceDataInodes, codePaths, stats);
20551
20552            // For now, ignore code size of packages on system partition
20553            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20554                stats.codeSize = 0;
20555            }
20556
20557            // External clients expect these to be tracked separately
20558            stats.dataSize -= stats.cacheSize;
20559
20560        } catch (InstallerException e) {
20561            Slog.w(TAG, String.valueOf(e));
20562            return false;
20563        }
20564
20565        return true;
20566    }
20567
20568    private int getUidTargetSdkVersionLockedLPr(int uid) {
20569        Object obj = mSettings.getUserIdLPr(uid);
20570        if (obj instanceof SharedUserSetting) {
20571            final SharedUserSetting sus = (SharedUserSetting) obj;
20572            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20573            final Iterator<PackageSetting> it = sus.packages.iterator();
20574            while (it.hasNext()) {
20575                final PackageSetting ps = it.next();
20576                if (ps.pkg != null) {
20577                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20578                    if (v < vers) vers = v;
20579                }
20580            }
20581            return vers;
20582        } else if (obj instanceof PackageSetting) {
20583            final PackageSetting ps = (PackageSetting) obj;
20584            if (ps.pkg != null) {
20585                return ps.pkg.applicationInfo.targetSdkVersion;
20586            }
20587        }
20588        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20589    }
20590
20591    @Override
20592    public void addPreferredActivity(IntentFilter filter, int match,
20593            ComponentName[] set, ComponentName activity, int userId) {
20594        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20595                "Adding preferred");
20596    }
20597
20598    private void addPreferredActivityInternal(IntentFilter filter, int match,
20599            ComponentName[] set, ComponentName activity, boolean always, int userId,
20600            String opname) {
20601        // writer
20602        int callingUid = Binder.getCallingUid();
20603        enforceCrossUserPermission(callingUid, userId,
20604                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20605        if (filter.countActions() == 0) {
20606            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20607            return;
20608        }
20609        synchronized (mPackages) {
20610            if (mContext.checkCallingOrSelfPermission(
20611                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20612                    != PackageManager.PERMISSION_GRANTED) {
20613                if (getUidTargetSdkVersionLockedLPr(callingUid)
20614                        < Build.VERSION_CODES.FROYO) {
20615                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20616                            + callingUid);
20617                    return;
20618                }
20619                mContext.enforceCallingOrSelfPermission(
20620                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20621            }
20622
20623            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20624            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20625                    + userId + ":");
20626            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20627            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20628            scheduleWritePackageRestrictionsLocked(userId);
20629            postPreferredActivityChangedBroadcast(userId);
20630        }
20631    }
20632
20633    private void postPreferredActivityChangedBroadcast(int userId) {
20634        mHandler.post(() -> {
20635            final IActivityManager am = ActivityManager.getService();
20636            if (am == null) {
20637                return;
20638            }
20639
20640            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20641            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20642            try {
20643                am.broadcastIntent(null, intent, null, null,
20644                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20645                        null, false, false, userId);
20646            } catch (RemoteException e) {
20647            }
20648        });
20649    }
20650
20651    @Override
20652    public void replacePreferredActivity(IntentFilter filter, int match,
20653            ComponentName[] set, ComponentName activity, int userId) {
20654        if (filter.countActions() != 1) {
20655            throw new IllegalArgumentException(
20656                    "replacePreferredActivity expects filter to have only 1 action.");
20657        }
20658        if (filter.countDataAuthorities() != 0
20659                || filter.countDataPaths() != 0
20660                || filter.countDataSchemes() > 1
20661                || filter.countDataTypes() != 0) {
20662            throw new IllegalArgumentException(
20663                    "replacePreferredActivity expects filter to have no data authorities, " +
20664                    "paths, or types; and at most one scheme.");
20665        }
20666
20667        final int callingUid = Binder.getCallingUid();
20668        enforceCrossUserPermission(callingUid, userId,
20669                true /* requireFullPermission */, false /* checkShell */,
20670                "replace preferred activity");
20671        synchronized (mPackages) {
20672            if (mContext.checkCallingOrSelfPermission(
20673                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20674                    != PackageManager.PERMISSION_GRANTED) {
20675                if (getUidTargetSdkVersionLockedLPr(callingUid)
20676                        < Build.VERSION_CODES.FROYO) {
20677                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20678                            + Binder.getCallingUid());
20679                    return;
20680                }
20681                mContext.enforceCallingOrSelfPermission(
20682                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20683            }
20684
20685            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20686            if (pir != null) {
20687                // Get all of the existing entries that exactly match this filter.
20688                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20689                if (existing != null && existing.size() == 1) {
20690                    PreferredActivity cur = existing.get(0);
20691                    if (DEBUG_PREFERRED) {
20692                        Slog.i(TAG, "Checking replace of preferred:");
20693                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20694                        if (!cur.mPref.mAlways) {
20695                            Slog.i(TAG, "  -- CUR; not mAlways!");
20696                        } else {
20697                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20698                            Slog.i(TAG, "  -- CUR: mSet="
20699                                    + Arrays.toString(cur.mPref.mSetComponents));
20700                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20701                            Slog.i(TAG, "  -- NEW: mMatch="
20702                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20703                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20704                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20705                        }
20706                    }
20707                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20708                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20709                            && cur.mPref.sameSet(set)) {
20710                        // Setting the preferred activity to what it happens to be already
20711                        if (DEBUG_PREFERRED) {
20712                            Slog.i(TAG, "Replacing with same preferred activity "
20713                                    + cur.mPref.mShortComponent + " for user "
20714                                    + userId + ":");
20715                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20716                        }
20717                        return;
20718                    }
20719                }
20720
20721                if (existing != null) {
20722                    if (DEBUG_PREFERRED) {
20723                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20724                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20725                    }
20726                    for (int i = 0; i < existing.size(); i++) {
20727                        PreferredActivity pa = existing.get(i);
20728                        if (DEBUG_PREFERRED) {
20729                            Slog.i(TAG, "Removing existing preferred activity "
20730                                    + pa.mPref.mComponent + ":");
20731                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20732                        }
20733                        pir.removeFilter(pa);
20734                    }
20735                }
20736            }
20737            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20738                    "Replacing preferred");
20739        }
20740    }
20741
20742    @Override
20743    public void clearPackagePreferredActivities(String packageName) {
20744        final int callingUid = Binder.getCallingUid();
20745        if (getInstantAppPackageName(callingUid) != null) {
20746            return;
20747        }
20748        // writer
20749        synchronized (mPackages) {
20750            PackageParser.Package pkg = mPackages.get(packageName);
20751            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20752                if (mContext.checkCallingOrSelfPermission(
20753                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20754                        != PackageManager.PERMISSION_GRANTED) {
20755                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20756                            < Build.VERSION_CODES.FROYO) {
20757                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20758                                + callingUid);
20759                        return;
20760                    }
20761                    mContext.enforceCallingOrSelfPermission(
20762                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20763                }
20764            }
20765            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20766            if (ps != null
20767                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20768                return;
20769            }
20770            int user = UserHandle.getCallingUserId();
20771            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20772                scheduleWritePackageRestrictionsLocked(user);
20773            }
20774        }
20775    }
20776
20777    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20778    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20779        ArrayList<PreferredActivity> removed = null;
20780        boolean changed = false;
20781        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20782            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20783            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20784            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20785                continue;
20786            }
20787            Iterator<PreferredActivity> it = pir.filterIterator();
20788            while (it.hasNext()) {
20789                PreferredActivity pa = it.next();
20790                // Mark entry for removal only if it matches the package name
20791                // and the entry is of type "always".
20792                if (packageName == null ||
20793                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20794                                && pa.mPref.mAlways)) {
20795                    if (removed == null) {
20796                        removed = new ArrayList<PreferredActivity>();
20797                    }
20798                    removed.add(pa);
20799                }
20800            }
20801            if (removed != null) {
20802                for (int j=0; j<removed.size(); j++) {
20803                    PreferredActivity pa = removed.get(j);
20804                    pir.removeFilter(pa);
20805                }
20806                changed = true;
20807            }
20808        }
20809        if (changed) {
20810            postPreferredActivityChangedBroadcast(userId);
20811        }
20812        return changed;
20813    }
20814
20815    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20816    private void clearIntentFilterVerificationsLPw(int userId) {
20817        final int packageCount = mPackages.size();
20818        for (int i = 0; i < packageCount; i++) {
20819            PackageParser.Package pkg = mPackages.valueAt(i);
20820            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20821        }
20822    }
20823
20824    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20825    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20826        if (userId == UserHandle.USER_ALL) {
20827            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20828                    sUserManager.getUserIds())) {
20829                for (int oneUserId : sUserManager.getUserIds()) {
20830                    scheduleWritePackageRestrictionsLocked(oneUserId);
20831                }
20832            }
20833        } else {
20834            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20835                scheduleWritePackageRestrictionsLocked(userId);
20836            }
20837        }
20838    }
20839
20840    /** Clears state for all users, and touches intent filter verification policy */
20841    void clearDefaultBrowserIfNeeded(String packageName) {
20842        for (int oneUserId : sUserManager.getUserIds()) {
20843            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20844        }
20845    }
20846
20847    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20848        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20849        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20850            if (packageName.equals(defaultBrowserPackageName)) {
20851                setDefaultBrowserPackageName(null, userId);
20852            }
20853        }
20854    }
20855
20856    @Override
20857    public void resetApplicationPreferences(int userId) {
20858        mContext.enforceCallingOrSelfPermission(
20859                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20860        final long identity = Binder.clearCallingIdentity();
20861        // writer
20862        try {
20863            synchronized (mPackages) {
20864                clearPackagePreferredActivitiesLPw(null, userId);
20865                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20866                // TODO: We have to reset the default SMS and Phone. This requires
20867                // significant refactoring to keep all default apps in the package
20868                // manager (cleaner but more work) or have the services provide
20869                // callbacks to the package manager to request a default app reset.
20870                applyFactoryDefaultBrowserLPw(userId);
20871                clearIntentFilterVerificationsLPw(userId);
20872                primeDomainVerificationsLPw(userId);
20873                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20874                scheduleWritePackageRestrictionsLocked(userId);
20875            }
20876            resetNetworkPolicies(userId);
20877        } finally {
20878            Binder.restoreCallingIdentity(identity);
20879        }
20880    }
20881
20882    @Override
20883    public int getPreferredActivities(List<IntentFilter> outFilters,
20884            List<ComponentName> outActivities, String packageName) {
20885        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20886            return 0;
20887        }
20888        int num = 0;
20889        final int userId = UserHandle.getCallingUserId();
20890        // reader
20891        synchronized (mPackages) {
20892            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20893            if (pir != null) {
20894                final Iterator<PreferredActivity> it = pir.filterIterator();
20895                while (it.hasNext()) {
20896                    final PreferredActivity pa = it.next();
20897                    if (packageName == null
20898                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20899                                    && pa.mPref.mAlways)) {
20900                        if (outFilters != null) {
20901                            outFilters.add(new IntentFilter(pa));
20902                        }
20903                        if (outActivities != null) {
20904                            outActivities.add(pa.mPref.mComponent);
20905                        }
20906                    }
20907                }
20908            }
20909        }
20910
20911        return num;
20912    }
20913
20914    @Override
20915    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20916            int userId) {
20917        int callingUid = Binder.getCallingUid();
20918        if (callingUid != Process.SYSTEM_UID) {
20919            throw new SecurityException(
20920                    "addPersistentPreferredActivity can only be run by the system");
20921        }
20922        if (filter.countActions() == 0) {
20923            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20924            return;
20925        }
20926        synchronized (mPackages) {
20927            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20928                    ":");
20929            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20930            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20931                    new PersistentPreferredActivity(filter, activity));
20932            scheduleWritePackageRestrictionsLocked(userId);
20933            postPreferredActivityChangedBroadcast(userId);
20934        }
20935    }
20936
20937    @Override
20938    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20939        int callingUid = Binder.getCallingUid();
20940        if (callingUid != Process.SYSTEM_UID) {
20941            throw new SecurityException(
20942                    "clearPackagePersistentPreferredActivities can only be run by the system");
20943        }
20944        ArrayList<PersistentPreferredActivity> removed = null;
20945        boolean changed = false;
20946        synchronized (mPackages) {
20947            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20948                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20949                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20950                        .valueAt(i);
20951                if (userId != thisUserId) {
20952                    continue;
20953                }
20954                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20955                while (it.hasNext()) {
20956                    PersistentPreferredActivity ppa = it.next();
20957                    // Mark entry for removal only if it matches the package name.
20958                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20959                        if (removed == null) {
20960                            removed = new ArrayList<PersistentPreferredActivity>();
20961                        }
20962                        removed.add(ppa);
20963                    }
20964                }
20965                if (removed != null) {
20966                    for (int j=0; j<removed.size(); j++) {
20967                        PersistentPreferredActivity ppa = removed.get(j);
20968                        ppir.removeFilter(ppa);
20969                    }
20970                    changed = true;
20971                }
20972            }
20973
20974            if (changed) {
20975                scheduleWritePackageRestrictionsLocked(userId);
20976                postPreferredActivityChangedBroadcast(userId);
20977            }
20978        }
20979    }
20980
20981    /**
20982     * Common machinery for picking apart a restored XML blob and passing
20983     * it to a caller-supplied functor to be applied to the running system.
20984     */
20985    private void restoreFromXml(XmlPullParser parser, int userId,
20986            String expectedStartTag, BlobXmlRestorer functor)
20987            throws IOException, XmlPullParserException {
20988        int type;
20989        while ((type = parser.next()) != XmlPullParser.START_TAG
20990                && type != XmlPullParser.END_DOCUMENT) {
20991        }
20992        if (type != XmlPullParser.START_TAG) {
20993            // oops didn't find a start tag?!
20994            if (DEBUG_BACKUP) {
20995                Slog.e(TAG, "Didn't find start tag during restore");
20996            }
20997            return;
20998        }
20999Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21000        // this is supposed to be TAG_PREFERRED_BACKUP
21001        if (!expectedStartTag.equals(parser.getName())) {
21002            if (DEBUG_BACKUP) {
21003                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21004            }
21005            return;
21006        }
21007
21008        // skip interfering stuff, then we're aligned with the backing implementation
21009        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21010Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21011        functor.apply(parser, userId);
21012    }
21013
21014    private interface BlobXmlRestorer {
21015        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21016    }
21017
21018    /**
21019     * Non-Binder method, support for the backup/restore mechanism: write the
21020     * full set of preferred activities in its canonical XML format.  Returns the
21021     * XML output as a byte array, or null if there is none.
21022     */
21023    @Override
21024    public byte[] getPreferredActivityBackup(int userId) {
21025        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21026            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21027        }
21028
21029        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21030        try {
21031            final XmlSerializer serializer = new FastXmlSerializer();
21032            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21033            serializer.startDocument(null, true);
21034            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21035
21036            synchronized (mPackages) {
21037                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21038            }
21039
21040            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21041            serializer.endDocument();
21042            serializer.flush();
21043        } catch (Exception e) {
21044            if (DEBUG_BACKUP) {
21045                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21046            }
21047            return null;
21048        }
21049
21050        return dataStream.toByteArray();
21051    }
21052
21053    @Override
21054    public void restorePreferredActivities(byte[] backup, int userId) {
21055        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21056            throw new SecurityException("Only the system may call restorePreferredActivities()");
21057        }
21058
21059        try {
21060            final XmlPullParser parser = Xml.newPullParser();
21061            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21062            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21063                    new BlobXmlRestorer() {
21064                        @Override
21065                        public void apply(XmlPullParser parser, int userId)
21066                                throws XmlPullParserException, IOException {
21067                            synchronized (mPackages) {
21068                                mSettings.readPreferredActivitiesLPw(parser, userId);
21069                            }
21070                        }
21071                    } );
21072        } catch (Exception e) {
21073            if (DEBUG_BACKUP) {
21074                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21075            }
21076        }
21077    }
21078
21079    /**
21080     * Non-Binder method, support for the backup/restore mechanism: write the
21081     * default browser (etc) settings in its canonical XML format.  Returns the default
21082     * browser XML representation as a byte array, or null if there is none.
21083     */
21084    @Override
21085    public byte[] getDefaultAppsBackup(int userId) {
21086        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21087            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21088        }
21089
21090        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21091        try {
21092            final XmlSerializer serializer = new FastXmlSerializer();
21093            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21094            serializer.startDocument(null, true);
21095            serializer.startTag(null, TAG_DEFAULT_APPS);
21096
21097            synchronized (mPackages) {
21098                mSettings.writeDefaultAppsLPr(serializer, userId);
21099            }
21100
21101            serializer.endTag(null, TAG_DEFAULT_APPS);
21102            serializer.endDocument();
21103            serializer.flush();
21104        } catch (Exception e) {
21105            if (DEBUG_BACKUP) {
21106                Slog.e(TAG, "Unable to write default apps for backup", e);
21107            }
21108            return null;
21109        }
21110
21111        return dataStream.toByteArray();
21112    }
21113
21114    @Override
21115    public void restoreDefaultApps(byte[] backup, int userId) {
21116        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21117            throw new SecurityException("Only the system may call restoreDefaultApps()");
21118        }
21119
21120        try {
21121            final XmlPullParser parser = Xml.newPullParser();
21122            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21123            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21124                    new BlobXmlRestorer() {
21125                        @Override
21126                        public void apply(XmlPullParser parser, int userId)
21127                                throws XmlPullParserException, IOException {
21128                            synchronized (mPackages) {
21129                                mSettings.readDefaultAppsLPw(parser, userId);
21130                            }
21131                        }
21132                    } );
21133        } catch (Exception e) {
21134            if (DEBUG_BACKUP) {
21135                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21136            }
21137        }
21138    }
21139
21140    @Override
21141    public byte[] getIntentFilterVerificationBackup(int userId) {
21142        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21143            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21144        }
21145
21146        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21147        try {
21148            final XmlSerializer serializer = new FastXmlSerializer();
21149            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21150            serializer.startDocument(null, true);
21151            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21152
21153            synchronized (mPackages) {
21154                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21155            }
21156
21157            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21158            serializer.endDocument();
21159            serializer.flush();
21160        } catch (Exception e) {
21161            if (DEBUG_BACKUP) {
21162                Slog.e(TAG, "Unable to write default apps for backup", e);
21163            }
21164            return null;
21165        }
21166
21167        return dataStream.toByteArray();
21168    }
21169
21170    @Override
21171    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21172        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21173            throw new SecurityException("Only the system may call restorePreferredActivities()");
21174        }
21175
21176        try {
21177            final XmlPullParser parser = Xml.newPullParser();
21178            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21179            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21180                    new BlobXmlRestorer() {
21181                        @Override
21182                        public void apply(XmlPullParser parser, int userId)
21183                                throws XmlPullParserException, IOException {
21184                            synchronized (mPackages) {
21185                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21186                                mSettings.writeLPr();
21187                            }
21188                        }
21189                    } );
21190        } catch (Exception e) {
21191            if (DEBUG_BACKUP) {
21192                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21193            }
21194        }
21195    }
21196
21197    @Override
21198    public byte[] getPermissionGrantBackup(int userId) {
21199        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21200            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21201        }
21202
21203        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21204        try {
21205            final XmlSerializer serializer = new FastXmlSerializer();
21206            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21207            serializer.startDocument(null, true);
21208            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21209
21210            synchronized (mPackages) {
21211                serializeRuntimePermissionGrantsLPr(serializer, userId);
21212            }
21213
21214            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21215            serializer.endDocument();
21216            serializer.flush();
21217        } catch (Exception e) {
21218            if (DEBUG_BACKUP) {
21219                Slog.e(TAG, "Unable to write default apps for backup", e);
21220            }
21221            return null;
21222        }
21223
21224        return dataStream.toByteArray();
21225    }
21226
21227    @Override
21228    public void restorePermissionGrants(byte[] backup, int userId) {
21229        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21230            throw new SecurityException("Only the system may call restorePermissionGrants()");
21231        }
21232
21233        try {
21234            final XmlPullParser parser = Xml.newPullParser();
21235            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21236            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21237                    new BlobXmlRestorer() {
21238                        @Override
21239                        public void apply(XmlPullParser parser, int userId)
21240                                throws XmlPullParserException, IOException {
21241                            synchronized (mPackages) {
21242                                processRestoredPermissionGrantsLPr(parser, userId);
21243                            }
21244                        }
21245                    } );
21246        } catch (Exception e) {
21247            if (DEBUG_BACKUP) {
21248                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21249            }
21250        }
21251    }
21252
21253    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21254            throws IOException {
21255        serializer.startTag(null, TAG_ALL_GRANTS);
21256
21257        final int N = mSettings.mPackages.size();
21258        for (int i = 0; i < N; i++) {
21259            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21260            boolean pkgGrantsKnown = false;
21261
21262            PermissionsState packagePerms = ps.getPermissionsState();
21263
21264            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21265                final int grantFlags = state.getFlags();
21266                // only look at grants that are not system/policy fixed
21267                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21268                    final boolean isGranted = state.isGranted();
21269                    // And only back up the user-twiddled state bits
21270                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21271                        final String packageName = mSettings.mPackages.keyAt(i);
21272                        if (!pkgGrantsKnown) {
21273                            serializer.startTag(null, TAG_GRANT);
21274                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21275                            pkgGrantsKnown = true;
21276                        }
21277
21278                        final boolean userSet =
21279                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21280                        final boolean userFixed =
21281                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21282                        final boolean revoke =
21283                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21284
21285                        serializer.startTag(null, TAG_PERMISSION);
21286                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21287                        if (isGranted) {
21288                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21289                        }
21290                        if (userSet) {
21291                            serializer.attribute(null, ATTR_USER_SET, "true");
21292                        }
21293                        if (userFixed) {
21294                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21295                        }
21296                        if (revoke) {
21297                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21298                        }
21299                        serializer.endTag(null, TAG_PERMISSION);
21300                    }
21301                }
21302            }
21303
21304            if (pkgGrantsKnown) {
21305                serializer.endTag(null, TAG_GRANT);
21306            }
21307        }
21308
21309        serializer.endTag(null, TAG_ALL_GRANTS);
21310    }
21311
21312    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21313            throws XmlPullParserException, IOException {
21314        String pkgName = null;
21315        int outerDepth = parser.getDepth();
21316        int type;
21317        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21318                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21319            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21320                continue;
21321            }
21322
21323            final String tagName = parser.getName();
21324            if (tagName.equals(TAG_GRANT)) {
21325                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21326                if (DEBUG_BACKUP) {
21327                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21328                }
21329            } else if (tagName.equals(TAG_PERMISSION)) {
21330
21331                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21332                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21333
21334                int newFlagSet = 0;
21335                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21336                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21337                }
21338                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21339                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21340                }
21341                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21342                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21343                }
21344                if (DEBUG_BACKUP) {
21345                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21346                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21347                }
21348                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21349                if (ps != null) {
21350                    // Already installed so we apply the grant immediately
21351                    if (DEBUG_BACKUP) {
21352                        Slog.v(TAG, "        + already installed; applying");
21353                    }
21354                    PermissionsState perms = ps.getPermissionsState();
21355                    BasePermission bp = mSettings.mPermissions.get(permName);
21356                    if (bp != null) {
21357                        if (isGranted) {
21358                            perms.grantRuntimePermission(bp, userId);
21359                        }
21360                        if (newFlagSet != 0) {
21361                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21362                        }
21363                    }
21364                } else {
21365                    // Need to wait for post-restore install to apply the grant
21366                    if (DEBUG_BACKUP) {
21367                        Slog.v(TAG, "        - not yet installed; saving for later");
21368                    }
21369                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21370                            isGranted, newFlagSet, userId);
21371                }
21372            } else {
21373                PackageManagerService.reportSettingsProblem(Log.WARN,
21374                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21375                XmlUtils.skipCurrentTag(parser);
21376            }
21377        }
21378
21379        scheduleWriteSettingsLocked();
21380        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21381    }
21382
21383    @Override
21384    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21385            int sourceUserId, int targetUserId, int flags) {
21386        mContext.enforceCallingOrSelfPermission(
21387                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21388        int callingUid = Binder.getCallingUid();
21389        enforceOwnerRights(ownerPackage, callingUid);
21390        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21391        if (intentFilter.countActions() == 0) {
21392            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21393            return;
21394        }
21395        synchronized (mPackages) {
21396            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21397                    ownerPackage, targetUserId, flags);
21398            CrossProfileIntentResolver resolver =
21399                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21400            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21401            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21402            if (existing != null) {
21403                int size = existing.size();
21404                for (int i = 0; i < size; i++) {
21405                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21406                        return;
21407                    }
21408                }
21409            }
21410            resolver.addFilter(newFilter);
21411            scheduleWritePackageRestrictionsLocked(sourceUserId);
21412        }
21413    }
21414
21415    @Override
21416    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21417        mContext.enforceCallingOrSelfPermission(
21418                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21419        final int callingUid = Binder.getCallingUid();
21420        enforceOwnerRights(ownerPackage, callingUid);
21421        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21422        synchronized (mPackages) {
21423            CrossProfileIntentResolver resolver =
21424                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21425            ArraySet<CrossProfileIntentFilter> set =
21426                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21427            for (CrossProfileIntentFilter filter : set) {
21428                if (filter.getOwnerPackage().equals(ownerPackage)) {
21429                    resolver.removeFilter(filter);
21430                }
21431            }
21432            scheduleWritePackageRestrictionsLocked(sourceUserId);
21433        }
21434    }
21435
21436    // Enforcing that callingUid is owning pkg on userId
21437    private void enforceOwnerRights(String pkg, int callingUid) {
21438        // The system owns everything.
21439        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21440            return;
21441        }
21442        final int callingUserId = UserHandle.getUserId(callingUid);
21443        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21444        if (pi == null) {
21445            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21446                    + callingUserId);
21447        }
21448        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21449            throw new SecurityException("Calling uid " + callingUid
21450                    + " does not own package " + pkg);
21451        }
21452    }
21453
21454    @Override
21455    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21456        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21457            return null;
21458        }
21459        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21460    }
21461
21462    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21463        UserManagerService ums = UserManagerService.getInstance();
21464        if (ums != null) {
21465            final UserInfo parent = ums.getProfileParent(userId);
21466            final int launcherUid = (parent != null) ? parent.id : userId;
21467            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21468            if (launcherComponent != null) {
21469                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21470                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21471                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21472                        .setPackage(launcherComponent.getPackageName());
21473                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21474            }
21475        }
21476    }
21477
21478    /**
21479     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21480     * then reports the most likely home activity or null if there are more than one.
21481     */
21482    private ComponentName getDefaultHomeActivity(int userId) {
21483        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21484        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21485        if (cn != null) {
21486            return cn;
21487        }
21488
21489        // Find the launcher with the highest priority and return that component if there are no
21490        // other home activity with the same priority.
21491        int lastPriority = Integer.MIN_VALUE;
21492        ComponentName lastComponent = null;
21493        final int size = allHomeCandidates.size();
21494        for (int i = 0; i < size; i++) {
21495            final ResolveInfo ri = allHomeCandidates.get(i);
21496            if (ri.priority > lastPriority) {
21497                lastComponent = ri.activityInfo.getComponentName();
21498                lastPriority = ri.priority;
21499            } else if (ri.priority == lastPriority) {
21500                // Two components found with same priority.
21501                lastComponent = null;
21502            }
21503        }
21504        return lastComponent;
21505    }
21506
21507    private Intent getHomeIntent() {
21508        Intent intent = new Intent(Intent.ACTION_MAIN);
21509        intent.addCategory(Intent.CATEGORY_HOME);
21510        intent.addCategory(Intent.CATEGORY_DEFAULT);
21511        return intent;
21512    }
21513
21514    private IntentFilter getHomeFilter() {
21515        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21516        filter.addCategory(Intent.CATEGORY_HOME);
21517        filter.addCategory(Intent.CATEGORY_DEFAULT);
21518        return filter;
21519    }
21520
21521    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21522            int userId) {
21523        Intent intent  = getHomeIntent();
21524        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21525                PackageManager.GET_META_DATA, userId);
21526        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21527                true, false, false, userId);
21528
21529        allHomeCandidates.clear();
21530        if (list != null) {
21531            for (ResolveInfo ri : list) {
21532                allHomeCandidates.add(ri);
21533            }
21534        }
21535        return (preferred == null || preferred.activityInfo == null)
21536                ? null
21537                : new ComponentName(preferred.activityInfo.packageName,
21538                        preferred.activityInfo.name);
21539    }
21540
21541    @Override
21542    public void setHomeActivity(ComponentName comp, int userId) {
21543        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21544            return;
21545        }
21546        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21547        getHomeActivitiesAsUser(homeActivities, userId);
21548
21549        boolean found = false;
21550
21551        final int size = homeActivities.size();
21552        final ComponentName[] set = new ComponentName[size];
21553        for (int i = 0; i < size; i++) {
21554            final ResolveInfo candidate = homeActivities.get(i);
21555            final ActivityInfo info = candidate.activityInfo;
21556            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21557            set[i] = activityName;
21558            if (!found && activityName.equals(comp)) {
21559                found = true;
21560            }
21561        }
21562        if (!found) {
21563            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21564                    + userId);
21565        }
21566        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21567                set, comp, userId);
21568    }
21569
21570    private @Nullable String getSetupWizardPackageName() {
21571        final Intent intent = new Intent(Intent.ACTION_MAIN);
21572        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21573
21574        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21575                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21576                        | MATCH_DISABLED_COMPONENTS,
21577                UserHandle.myUserId());
21578        if (matches.size() == 1) {
21579            return matches.get(0).getComponentInfo().packageName;
21580        } else {
21581            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21582                    + ": matches=" + matches);
21583            return null;
21584        }
21585    }
21586
21587    private @Nullable String getStorageManagerPackageName() {
21588        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21589
21590        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21591                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21592                        | MATCH_DISABLED_COMPONENTS,
21593                UserHandle.myUserId());
21594        if (matches.size() == 1) {
21595            return matches.get(0).getComponentInfo().packageName;
21596        } else {
21597            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21598                    + matches.size() + ": matches=" + matches);
21599            return null;
21600        }
21601    }
21602
21603    @Override
21604    public void setApplicationEnabledSetting(String appPackageName,
21605            int newState, int flags, int userId, String callingPackage) {
21606        if (!sUserManager.exists(userId)) return;
21607        if (callingPackage == null) {
21608            callingPackage = Integer.toString(Binder.getCallingUid());
21609        }
21610        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21611    }
21612
21613    @Override
21614    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21615        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21616        synchronized (mPackages) {
21617            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21618            if (pkgSetting != null) {
21619                pkgSetting.setUpdateAvailable(updateAvailable);
21620            }
21621        }
21622    }
21623
21624    @Override
21625    public void setComponentEnabledSetting(ComponentName componentName,
21626            int newState, int flags, int userId) {
21627        if (!sUserManager.exists(userId)) return;
21628        setEnabledSetting(componentName.getPackageName(),
21629                componentName.getClassName(), newState, flags, userId, null);
21630    }
21631
21632    private void setEnabledSetting(final String packageName, String className, int newState,
21633            final int flags, int userId, String callingPackage) {
21634        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21635              || newState == COMPONENT_ENABLED_STATE_ENABLED
21636              || newState == COMPONENT_ENABLED_STATE_DISABLED
21637              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21638              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21639            throw new IllegalArgumentException("Invalid new component state: "
21640                    + newState);
21641        }
21642        PackageSetting pkgSetting;
21643        final int callingUid = Binder.getCallingUid();
21644        final int permission;
21645        if (callingUid == Process.SYSTEM_UID) {
21646            permission = PackageManager.PERMISSION_GRANTED;
21647        } else {
21648            permission = mContext.checkCallingOrSelfPermission(
21649                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21650        }
21651        enforceCrossUserPermission(callingUid, userId,
21652                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21653        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21654        boolean sendNow = false;
21655        boolean isApp = (className == null);
21656        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21657        String componentName = isApp ? packageName : className;
21658        int packageUid = -1;
21659        ArrayList<String> components;
21660
21661        // reader
21662        synchronized (mPackages) {
21663            pkgSetting = mSettings.mPackages.get(packageName);
21664            if (pkgSetting == null) {
21665                if (!isCallerInstantApp) {
21666                    if (className == null) {
21667                        throw new IllegalArgumentException("Unknown package: " + packageName);
21668                    }
21669                    throw new IllegalArgumentException(
21670                            "Unknown component: " + packageName + "/" + className);
21671                } else {
21672                    // throw SecurityException to prevent leaking package information
21673                    throw new SecurityException(
21674                            "Attempt to change component state; "
21675                            + "pid=" + Binder.getCallingPid()
21676                            + ", uid=" + callingUid
21677                            + (className == null
21678                                    ? ", package=" + packageName
21679                                    : ", component=" + packageName + "/" + className));
21680                }
21681            }
21682        }
21683
21684        // Limit who can change which apps
21685        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21686            // Don't allow apps that don't have permission to modify other apps
21687            if (!allowedByPermission
21688                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21689                throw new SecurityException(
21690                        "Attempt to change component state; "
21691                        + "pid=" + Binder.getCallingPid()
21692                        + ", uid=" + callingUid
21693                        + (className == null
21694                                ? ", package=" + packageName
21695                                : ", component=" + packageName + "/" + className));
21696            }
21697            // Don't allow changing protected packages.
21698            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21699                throw new SecurityException("Cannot disable a protected package: " + packageName);
21700            }
21701        }
21702
21703        if (callingUid == Process.SHELL_UID
21704                && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21705            // Shell can only change whole packages between ENABLED and DISABLED_USER states
21706            // unless it is a test package.
21707            int oldState = pkgSetting.getEnabled(userId);
21708            if (className == null
21709                &&
21710                (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21711                 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21712                 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21713                &&
21714                (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21715                 || newState == COMPONENT_ENABLED_STATE_DEFAULT
21716                 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21717                // ok
21718            } else {
21719                throw new SecurityException(
21720                        "Shell cannot change component state for " + packageName + "/"
21721                        + className + " to " + newState);
21722            }
21723        }
21724        if (className == null) {
21725            // We're dealing with an application/package level state change
21726            if (pkgSetting.getEnabled(userId) == newState) {
21727                // Nothing to do
21728                return;
21729            }
21730            // If we're enabling a system stub, there's a little more work to do.
21731            // Prior to enabling the package, we need to decompress the APK(s) to the
21732            // data partition and then replace the version on the system partition.
21733            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21734            final boolean isSystemStub = deletedPkg.isStub
21735                    && deletedPkg.isSystemApp();
21736            if (isSystemStub
21737                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21738                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21739                final File codePath = decompressPackage(deletedPkg);
21740                if (codePath == null) {
21741                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21742                    return;
21743                }
21744                // TODO remove direct parsing of the package object during internal cleanup
21745                // of scan package
21746                // We need to call parse directly here for no other reason than we need
21747                // the new package in order to disable the old one [we use the information
21748                // for some internal optimization to optionally create a new package setting
21749                // object on replace]. However, we can't get the package from the scan
21750                // because the scan modifies live structures and we need to remove the
21751                // old [system] package from the system before a scan can be attempted.
21752                // Once scan is indempotent we can remove this parse and use the package
21753                // object we scanned, prior to adding it to package settings.
21754                final PackageParser pp = new PackageParser();
21755                pp.setSeparateProcesses(mSeparateProcesses);
21756                pp.setDisplayMetrics(mMetrics);
21757                pp.setCallback(mPackageParserCallback);
21758                final PackageParser.Package tmpPkg;
21759                try {
21760                    final int parseFlags = mDefParseFlags
21761                            | PackageParser.PARSE_MUST_BE_APK
21762                            | PackageParser.PARSE_IS_SYSTEM
21763                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21764                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21765                } catch (PackageParserException e) {
21766                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21767                    return;
21768                }
21769                synchronized (mInstallLock) {
21770                    // Disable the stub and remove any package entries
21771                    removePackageLI(deletedPkg, true);
21772                    synchronized (mPackages) {
21773                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21774                    }
21775                    final PackageParser.Package newPkg;
21776                    try (PackageFreezer freezer =
21777                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21778                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21779                                | PackageParser.PARSE_ENFORCE_CODE;
21780                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21781                                0 /*currentTime*/, null /*user*/);
21782                        prepareAppDataAfterInstallLIF(newPkg);
21783                        synchronized (mPackages) {
21784                            try {
21785                                updateSharedLibrariesLPr(newPkg, null);
21786                            } catch (PackageManagerException e) {
21787                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21788                            }
21789                            updatePermissionsLPw(newPkg.packageName, newPkg,
21790                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21791                            mSettings.writeLPr();
21792                        }
21793                    } catch (PackageManagerException e) {
21794                        // Whoops! Something went wrong; try to roll back to the stub
21795                        Slog.w(TAG, "Failed to install compressed system package:"
21796                                + pkgSetting.name, e);
21797                        // Remove the failed install
21798                        removeCodePathLI(codePath);
21799
21800                        // Install the system package
21801                        try (PackageFreezer freezer =
21802                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21803                            synchronized (mPackages) {
21804                                // NOTE: The system package always needs to be enabled; even
21805                                // if it's for a compressed stub. If we don't, installing the
21806                                // system package fails during scan [scanning checks the disabled
21807                                // packages]. We will reverse this later, after we've "installed"
21808                                // the stub.
21809                                // This leaves us in a fragile state; the stub should never be
21810                                // enabled, so, cross your fingers and hope nothing goes wrong
21811                                // until we can disable the package later.
21812                                enableSystemPackageLPw(deletedPkg);
21813                            }
21814                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21815                                    false /*isPrivileged*/, null /*allUserHandles*/,
21816                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21817                                    true /*writeSettings*/);
21818                        } catch (PackageManagerException pme) {
21819                            Slog.w(TAG, "Failed to restore system package:"
21820                                    + deletedPkg.packageName, pme);
21821                        } finally {
21822                            synchronized (mPackages) {
21823                                mSettings.disableSystemPackageLPw(
21824                                        deletedPkg.packageName, true /*replaced*/);
21825                                mSettings.writeLPr();
21826                            }
21827                        }
21828                        return;
21829                    }
21830                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21831                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21832                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21833                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21834                            newPkg.baseCodePath, newPkg.splitCodePaths);
21835                }
21836            }
21837            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21838                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21839                // Don't care about who enables an app.
21840                callingPackage = null;
21841            }
21842            pkgSetting.setEnabled(newState, userId, callingPackage);
21843        } else {
21844            // We're dealing with a component level state change
21845            // First, verify that this is a valid class name.
21846            PackageParser.Package pkg = pkgSetting.pkg;
21847            if (pkg == null || !pkg.hasComponentClassName(className)) {
21848                if (pkg != null &&
21849                        pkg.applicationInfo.targetSdkVersion >=
21850                                Build.VERSION_CODES.JELLY_BEAN) {
21851                    throw new IllegalArgumentException("Component class " + className
21852                            + " does not exist in " + packageName);
21853                } else {
21854                    Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21855                            + className + " does not exist in " + packageName);
21856                }
21857            }
21858            switch (newState) {
21859            case COMPONENT_ENABLED_STATE_ENABLED:
21860                if (!pkgSetting.enableComponentLPw(className, userId)) {
21861                    return;
21862                }
21863                break;
21864            case COMPONENT_ENABLED_STATE_DISABLED:
21865                if (!pkgSetting.disableComponentLPw(className, userId)) {
21866                    return;
21867                }
21868                break;
21869            case COMPONENT_ENABLED_STATE_DEFAULT:
21870                if (!pkgSetting.restoreComponentLPw(className, userId)) {
21871                    return;
21872                }
21873                break;
21874            default:
21875                Slog.e(TAG, "Invalid new component state: " + newState);
21876                return;
21877            }
21878        }
21879        synchronized (mPackages) {
21880            scheduleWritePackageRestrictionsLocked(userId);
21881            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21882            final long callingId = Binder.clearCallingIdentity();
21883            try {
21884                updateInstantAppInstallerLocked(packageName);
21885            } finally {
21886                Binder.restoreCallingIdentity(callingId);
21887            }
21888            components = mPendingBroadcasts.get(userId, packageName);
21889            final boolean newPackage = components == null;
21890            if (newPackage) {
21891                components = new ArrayList<String>();
21892            }
21893            if (!components.contains(componentName)) {
21894                components.add(componentName);
21895            }
21896            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21897                sendNow = true;
21898                // Purge entry from pending broadcast list if another one exists already
21899                // since we are sending one right away.
21900                mPendingBroadcasts.remove(userId, packageName);
21901            } else {
21902                if (newPackage) {
21903                    mPendingBroadcasts.put(userId, packageName, components);
21904                }
21905                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21906                    // Schedule a message
21907                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21908                }
21909            }
21910        }
21911
21912        long callingId = Binder.clearCallingIdentity();
21913        try {
21914            if (sendNow) {
21915                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21916                sendPackageChangedBroadcast(packageName,
21917                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21918            }
21919        } finally {
21920            Binder.restoreCallingIdentity(callingId);
21921        }
21922    }
21923
21924    @Override
21925    public void flushPackageRestrictionsAsUser(int userId) {
21926        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21927            return;
21928        }
21929        if (!sUserManager.exists(userId)) {
21930            return;
21931        }
21932        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21933                false /* checkShell */, "flushPackageRestrictions");
21934        synchronized (mPackages) {
21935            mSettings.writePackageRestrictionsLPr(userId);
21936            mDirtyUsers.remove(userId);
21937            if (mDirtyUsers.isEmpty()) {
21938                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21939            }
21940        }
21941    }
21942
21943    private void sendPackageChangedBroadcast(String packageName,
21944            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21945        if (DEBUG_INSTALL)
21946            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21947                    + componentNames);
21948        Bundle extras = new Bundle(4);
21949        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21950        String nameList[] = new String[componentNames.size()];
21951        componentNames.toArray(nameList);
21952        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21953        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21954        extras.putInt(Intent.EXTRA_UID, packageUid);
21955        // If this is not reporting a change of the overall package, then only send it
21956        // to registered receivers.  We don't want to launch a swath of apps for every
21957        // little component state change.
21958        final int flags = !componentNames.contains(packageName)
21959                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21960        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21961                new int[] {UserHandle.getUserId(packageUid)});
21962    }
21963
21964    @Override
21965    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21966        if (!sUserManager.exists(userId)) return;
21967        final int callingUid = Binder.getCallingUid();
21968        if (getInstantAppPackageName(callingUid) != null) {
21969            return;
21970        }
21971        final int permission = mContext.checkCallingOrSelfPermission(
21972                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21973        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21974        enforceCrossUserPermission(callingUid, userId,
21975                true /* requireFullPermission */, true /* checkShell */, "stop package");
21976        // writer
21977        synchronized (mPackages) {
21978            final PackageSetting ps = mSettings.mPackages.get(packageName);
21979            if (!filterAppAccessLPr(ps, callingUid, userId)
21980                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21981                            allowedByPermission, callingUid, userId)) {
21982                scheduleWritePackageRestrictionsLocked(userId);
21983            }
21984        }
21985    }
21986
21987    @Override
21988    public String getInstallerPackageName(String packageName) {
21989        final int callingUid = Binder.getCallingUid();
21990        if (getInstantAppPackageName(callingUid) != null) {
21991            return null;
21992        }
21993        // reader
21994        synchronized (mPackages) {
21995            final PackageSetting ps = mSettings.mPackages.get(packageName);
21996            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21997                return null;
21998            }
21999            return mSettings.getInstallerPackageNameLPr(packageName);
22000        }
22001    }
22002
22003    public boolean isOrphaned(String packageName) {
22004        // reader
22005        synchronized (mPackages) {
22006            return mSettings.isOrphaned(packageName);
22007        }
22008    }
22009
22010    @Override
22011    public int getApplicationEnabledSetting(String packageName, int userId) {
22012        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22013        int callingUid = Binder.getCallingUid();
22014        enforceCrossUserPermission(callingUid, userId,
22015                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22016        // reader
22017        synchronized (mPackages) {
22018            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22019                return COMPONENT_ENABLED_STATE_DISABLED;
22020            }
22021            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22022        }
22023    }
22024
22025    @Override
22026    public int getComponentEnabledSetting(ComponentName component, int userId) {
22027        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22028        int callingUid = Binder.getCallingUid();
22029        enforceCrossUserPermission(callingUid, userId,
22030                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22031        synchronized (mPackages) {
22032            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22033                    component, TYPE_UNKNOWN, userId)) {
22034                return COMPONENT_ENABLED_STATE_DISABLED;
22035            }
22036            return mSettings.getComponentEnabledSettingLPr(component, userId);
22037        }
22038    }
22039
22040    @Override
22041    public void enterSafeMode() {
22042        enforceSystemOrRoot("Only the system can request entering safe mode");
22043
22044        if (!mSystemReady) {
22045            mSafeMode = true;
22046        }
22047    }
22048
22049    @Override
22050    public void systemReady() {
22051        enforceSystemOrRoot("Only the system can claim the system is ready");
22052
22053        mSystemReady = true;
22054        final ContentResolver resolver = mContext.getContentResolver();
22055        ContentObserver co = new ContentObserver(mHandler) {
22056            @Override
22057            public void onChange(boolean selfChange) {
22058                mEphemeralAppsDisabled =
22059                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22060                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22061            }
22062        };
22063        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22064                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22065                false, co, UserHandle.USER_SYSTEM);
22066        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22067                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22068        co.onChange(true);
22069
22070        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22071        // disabled after already being started.
22072        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22073                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22074
22075        // Read the compatibilty setting when the system is ready.
22076        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22077                mContext.getContentResolver(),
22078                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22079        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22080        if (DEBUG_SETTINGS) {
22081            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22082        }
22083
22084        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22085
22086        synchronized (mPackages) {
22087            // Verify that all of the preferred activity components actually
22088            // exist.  It is possible for applications to be updated and at
22089            // that point remove a previously declared activity component that
22090            // had been set as a preferred activity.  We try to clean this up
22091            // the next time we encounter that preferred activity, but it is
22092            // possible for the user flow to never be able to return to that
22093            // situation so here we do a sanity check to make sure we haven't
22094            // left any junk around.
22095            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22096            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22097                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22098                removed.clear();
22099                for (PreferredActivity pa : pir.filterSet()) {
22100                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22101                        removed.add(pa);
22102                    }
22103                }
22104                if (removed.size() > 0) {
22105                    for (int r=0; r<removed.size(); r++) {
22106                        PreferredActivity pa = removed.get(r);
22107                        Slog.w(TAG, "Removing dangling preferred activity: "
22108                                + pa.mPref.mComponent);
22109                        pir.removeFilter(pa);
22110                    }
22111                    mSettings.writePackageRestrictionsLPr(
22112                            mSettings.mPreferredActivities.keyAt(i));
22113                }
22114            }
22115
22116            for (int userId : UserManagerService.getInstance().getUserIds()) {
22117                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22118                    grantPermissionsUserIds = ArrayUtils.appendInt(
22119                            grantPermissionsUserIds, userId);
22120                }
22121            }
22122        }
22123        sUserManager.systemReady();
22124
22125        // If we upgraded grant all default permissions before kicking off.
22126        for (int userId : grantPermissionsUserIds) {
22127            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22128        }
22129
22130        // If we did not grant default permissions, we preload from this the
22131        // default permission exceptions lazily to ensure we don't hit the
22132        // disk on a new user creation.
22133        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22134            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22135        }
22136
22137        // Kick off any messages waiting for system ready
22138        if (mPostSystemReadyMessages != null) {
22139            for (Message msg : mPostSystemReadyMessages) {
22140                msg.sendToTarget();
22141            }
22142            mPostSystemReadyMessages = null;
22143        }
22144
22145        // Watch for external volumes that come and go over time
22146        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22147        storage.registerListener(mStorageListener);
22148
22149        mInstallerService.systemReady();
22150        mPackageDexOptimizer.systemReady();
22151
22152        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22153                StorageManagerInternal.class);
22154        StorageManagerInternal.addExternalStoragePolicy(
22155                new StorageManagerInternal.ExternalStorageMountPolicy() {
22156            @Override
22157            public int getMountMode(int uid, String packageName) {
22158                if (Process.isIsolated(uid)) {
22159                    return Zygote.MOUNT_EXTERNAL_NONE;
22160                }
22161                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22162                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22163                }
22164                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22165                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22166                }
22167                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22168                    return Zygote.MOUNT_EXTERNAL_READ;
22169                }
22170                return Zygote.MOUNT_EXTERNAL_WRITE;
22171            }
22172
22173            @Override
22174            public boolean hasExternalStorage(int uid, String packageName) {
22175                return true;
22176            }
22177        });
22178
22179        // Now that we're mostly running, clean up stale users and apps
22180        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22181        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22182
22183        if (mPrivappPermissionsViolations != null) {
22184            Slog.wtf(TAG,"Signature|privileged permissions not in "
22185                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22186            mPrivappPermissionsViolations = null;
22187        }
22188    }
22189
22190    public void waitForAppDataPrepared() {
22191        if (mPrepareAppDataFuture == null) {
22192            return;
22193        }
22194        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22195        mPrepareAppDataFuture = null;
22196    }
22197
22198    @Override
22199    public boolean isSafeMode() {
22200        // allow instant applications
22201        return mSafeMode;
22202    }
22203
22204    @Override
22205    public boolean hasSystemUidErrors() {
22206        // allow instant applications
22207        return mHasSystemUidErrors;
22208    }
22209
22210    static String arrayToString(int[] array) {
22211        StringBuffer buf = new StringBuffer(128);
22212        buf.append('[');
22213        if (array != null) {
22214            for (int i=0; i<array.length; i++) {
22215                if (i > 0) buf.append(", ");
22216                buf.append(array[i]);
22217            }
22218        }
22219        buf.append(']');
22220        return buf.toString();
22221    }
22222
22223    static class DumpState {
22224        public static final int DUMP_LIBS = 1 << 0;
22225        public static final int DUMP_FEATURES = 1 << 1;
22226        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22227        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22228        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22229        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22230        public static final int DUMP_PERMISSIONS = 1 << 6;
22231        public static final int DUMP_PACKAGES = 1 << 7;
22232        public static final int DUMP_SHARED_USERS = 1 << 8;
22233        public static final int DUMP_MESSAGES = 1 << 9;
22234        public static final int DUMP_PROVIDERS = 1 << 10;
22235        public static final int DUMP_VERIFIERS = 1 << 11;
22236        public static final int DUMP_PREFERRED = 1 << 12;
22237        public static final int DUMP_PREFERRED_XML = 1 << 13;
22238        public static final int DUMP_KEYSETS = 1 << 14;
22239        public static final int DUMP_VERSION = 1 << 15;
22240        public static final int DUMP_INSTALLS = 1 << 16;
22241        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22242        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22243        public static final int DUMP_FROZEN = 1 << 19;
22244        public static final int DUMP_DEXOPT = 1 << 20;
22245        public static final int DUMP_COMPILER_STATS = 1 << 21;
22246        public static final int DUMP_CHANGES = 1 << 22;
22247        public static final int DUMP_VOLUMES = 1 << 23;
22248
22249        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22250
22251        private int mTypes;
22252
22253        private int mOptions;
22254
22255        private boolean mTitlePrinted;
22256
22257        private SharedUserSetting mSharedUser;
22258
22259        public boolean isDumping(int type) {
22260            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22261                return true;
22262            }
22263
22264            return (mTypes & type) != 0;
22265        }
22266
22267        public void setDump(int type) {
22268            mTypes |= type;
22269        }
22270
22271        public boolean isOptionEnabled(int option) {
22272            return (mOptions & option) != 0;
22273        }
22274
22275        public void setOptionEnabled(int option) {
22276            mOptions |= option;
22277        }
22278
22279        public boolean onTitlePrinted() {
22280            final boolean printed = mTitlePrinted;
22281            mTitlePrinted = true;
22282            return printed;
22283        }
22284
22285        public boolean getTitlePrinted() {
22286            return mTitlePrinted;
22287        }
22288
22289        public void setTitlePrinted(boolean enabled) {
22290            mTitlePrinted = enabled;
22291        }
22292
22293        public SharedUserSetting getSharedUser() {
22294            return mSharedUser;
22295        }
22296
22297        public void setSharedUser(SharedUserSetting user) {
22298            mSharedUser = user;
22299        }
22300    }
22301
22302    @Override
22303    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22304            FileDescriptor err, String[] args, ShellCallback callback,
22305            ResultReceiver resultReceiver) {
22306        (new PackageManagerShellCommand(this)).exec(
22307                this, in, out, err, args, callback, resultReceiver);
22308    }
22309
22310    @Override
22311    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22312        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22313
22314        DumpState dumpState = new DumpState();
22315        boolean fullPreferred = false;
22316        boolean checkin = false;
22317
22318        String packageName = null;
22319        ArraySet<String> permissionNames = null;
22320
22321        int opti = 0;
22322        while (opti < args.length) {
22323            String opt = args[opti];
22324            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22325                break;
22326            }
22327            opti++;
22328
22329            if ("-a".equals(opt)) {
22330                // Right now we only know how to print all.
22331            } else if ("-h".equals(opt)) {
22332                pw.println("Package manager dump options:");
22333                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22334                pw.println("    --checkin: dump for a checkin");
22335                pw.println("    -f: print details of intent filters");
22336                pw.println("    -h: print this help");
22337                pw.println("  cmd may be one of:");
22338                pw.println("    l[ibraries]: list known shared libraries");
22339                pw.println("    f[eatures]: list device features");
22340                pw.println("    k[eysets]: print known keysets");
22341                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22342                pw.println("    perm[issions]: dump permissions");
22343                pw.println("    permission [name ...]: dump declaration and use of given permission");
22344                pw.println("    pref[erred]: print preferred package settings");
22345                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22346                pw.println("    prov[iders]: dump content providers");
22347                pw.println("    p[ackages]: dump installed packages");
22348                pw.println("    s[hared-users]: dump shared user IDs");
22349                pw.println("    m[essages]: print collected runtime messages");
22350                pw.println("    v[erifiers]: print package verifier info");
22351                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22352                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22353                pw.println("    version: print database version info");
22354                pw.println("    write: write current settings now");
22355                pw.println("    installs: details about install sessions");
22356                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22357                pw.println("    dexopt: dump dexopt state");
22358                pw.println("    compiler-stats: dump compiler statistics");
22359                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22360                pw.println("    <package.name>: info about given package");
22361                return;
22362            } else if ("--checkin".equals(opt)) {
22363                checkin = true;
22364            } else if ("-f".equals(opt)) {
22365                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22366            } else if ("--proto".equals(opt)) {
22367                dumpProto(fd);
22368                return;
22369            } else {
22370                pw.println("Unknown argument: " + opt + "; use -h for help");
22371            }
22372        }
22373
22374        // Is the caller requesting to dump a particular piece of data?
22375        if (opti < args.length) {
22376            String cmd = args[opti];
22377            opti++;
22378            // Is this a package name?
22379            if ("android".equals(cmd) || cmd.contains(".")) {
22380                packageName = cmd;
22381                // When dumping a single package, we always dump all of its
22382                // filter information since the amount of data will be reasonable.
22383                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22384            } else if ("check-permission".equals(cmd)) {
22385                if (opti >= args.length) {
22386                    pw.println("Error: check-permission missing permission argument");
22387                    return;
22388                }
22389                String perm = args[opti];
22390                opti++;
22391                if (opti >= args.length) {
22392                    pw.println("Error: check-permission missing package argument");
22393                    return;
22394                }
22395
22396                String pkg = args[opti];
22397                opti++;
22398                int user = UserHandle.getUserId(Binder.getCallingUid());
22399                if (opti < args.length) {
22400                    try {
22401                        user = Integer.parseInt(args[opti]);
22402                    } catch (NumberFormatException e) {
22403                        pw.println("Error: check-permission user argument is not a number: "
22404                                + args[opti]);
22405                        return;
22406                    }
22407                }
22408
22409                // Normalize package name to handle renamed packages and static libs
22410                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22411
22412                pw.println(checkPermission(perm, pkg, user));
22413                return;
22414            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22415                dumpState.setDump(DumpState.DUMP_LIBS);
22416            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22417                dumpState.setDump(DumpState.DUMP_FEATURES);
22418            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22419                if (opti >= args.length) {
22420                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22421                            | DumpState.DUMP_SERVICE_RESOLVERS
22422                            | DumpState.DUMP_RECEIVER_RESOLVERS
22423                            | DumpState.DUMP_CONTENT_RESOLVERS);
22424                } else {
22425                    while (opti < args.length) {
22426                        String name = args[opti];
22427                        if ("a".equals(name) || "activity".equals(name)) {
22428                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22429                        } else if ("s".equals(name) || "service".equals(name)) {
22430                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22431                        } else if ("r".equals(name) || "receiver".equals(name)) {
22432                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22433                        } else if ("c".equals(name) || "content".equals(name)) {
22434                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22435                        } else {
22436                            pw.println("Error: unknown resolver table type: " + name);
22437                            return;
22438                        }
22439                        opti++;
22440                    }
22441                }
22442            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22443                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22444            } else if ("permission".equals(cmd)) {
22445                if (opti >= args.length) {
22446                    pw.println("Error: permission requires permission name");
22447                    return;
22448                }
22449                permissionNames = new ArraySet<>();
22450                while (opti < args.length) {
22451                    permissionNames.add(args[opti]);
22452                    opti++;
22453                }
22454                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22455                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22456            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22457                dumpState.setDump(DumpState.DUMP_PREFERRED);
22458            } else if ("preferred-xml".equals(cmd)) {
22459                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22460                if (opti < args.length && "--full".equals(args[opti])) {
22461                    fullPreferred = true;
22462                    opti++;
22463                }
22464            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22465                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22466            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22467                dumpState.setDump(DumpState.DUMP_PACKAGES);
22468            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22469                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22470            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22471                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22472            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22473                dumpState.setDump(DumpState.DUMP_MESSAGES);
22474            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22475                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22476            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22477                    || "intent-filter-verifiers".equals(cmd)) {
22478                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22479            } else if ("version".equals(cmd)) {
22480                dumpState.setDump(DumpState.DUMP_VERSION);
22481            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22482                dumpState.setDump(DumpState.DUMP_KEYSETS);
22483            } else if ("installs".equals(cmd)) {
22484                dumpState.setDump(DumpState.DUMP_INSTALLS);
22485            } else if ("frozen".equals(cmd)) {
22486                dumpState.setDump(DumpState.DUMP_FROZEN);
22487            } else if ("volumes".equals(cmd)) {
22488                dumpState.setDump(DumpState.DUMP_VOLUMES);
22489            } else if ("dexopt".equals(cmd)) {
22490                dumpState.setDump(DumpState.DUMP_DEXOPT);
22491            } else if ("compiler-stats".equals(cmd)) {
22492                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22493            } else if ("changes".equals(cmd)) {
22494                dumpState.setDump(DumpState.DUMP_CHANGES);
22495            } else if ("write".equals(cmd)) {
22496                synchronized (mPackages) {
22497                    mSettings.writeLPr();
22498                    pw.println("Settings written.");
22499                    return;
22500                }
22501            }
22502        }
22503
22504        if (checkin) {
22505            pw.println("vers,1");
22506        }
22507
22508        // reader
22509        synchronized (mPackages) {
22510            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22511                if (!checkin) {
22512                    if (dumpState.onTitlePrinted())
22513                        pw.println();
22514                    pw.println("Database versions:");
22515                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22516                }
22517            }
22518
22519            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22520                if (!checkin) {
22521                    if (dumpState.onTitlePrinted())
22522                        pw.println();
22523                    pw.println("Verifiers:");
22524                    pw.print("  Required: ");
22525                    pw.print(mRequiredVerifierPackage);
22526                    pw.print(" (uid=");
22527                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22528                            UserHandle.USER_SYSTEM));
22529                    pw.println(")");
22530                } else if (mRequiredVerifierPackage != null) {
22531                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22532                    pw.print(",");
22533                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22534                            UserHandle.USER_SYSTEM));
22535                }
22536            }
22537
22538            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22539                    packageName == null) {
22540                if (mIntentFilterVerifierComponent != null) {
22541                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22542                    if (!checkin) {
22543                        if (dumpState.onTitlePrinted())
22544                            pw.println();
22545                        pw.println("Intent Filter Verifier:");
22546                        pw.print("  Using: ");
22547                        pw.print(verifierPackageName);
22548                        pw.print(" (uid=");
22549                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22550                                UserHandle.USER_SYSTEM));
22551                        pw.println(")");
22552                    } else if (verifierPackageName != null) {
22553                        pw.print("ifv,"); pw.print(verifierPackageName);
22554                        pw.print(",");
22555                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22556                                UserHandle.USER_SYSTEM));
22557                    }
22558                } else {
22559                    pw.println();
22560                    pw.println("No Intent Filter Verifier available!");
22561                }
22562            }
22563
22564            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22565                boolean printedHeader = false;
22566                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22567                while (it.hasNext()) {
22568                    String libName = it.next();
22569                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22570                    if (versionedLib == null) {
22571                        continue;
22572                    }
22573                    final int versionCount = versionedLib.size();
22574                    for (int i = 0; i < versionCount; i++) {
22575                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22576                        if (!checkin) {
22577                            if (!printedHeader) {
22578                                if (dumpState.onTitlePrinted())
22579                                    pw.println();
22580                                pw.println("Libraries:");
22581                                printedHeader = true;
22582                            }
22583                            pw.print("  ");
22584                        } else {
22585                            pw.print("lib,");
22586                        }
22587                        pw.print(libEntry.info.getName());
22588                        if (libEntry.info.isStatic()) {
22589                            pw.print(" version=" + libEntry.info.getVersion());
22590                        }
22591                        if (!checkin) {
22592                            pw.print(" -> ");
22593                        }
22594                        if (libEntry.path != null) {
22595                            pw.print(" (jar) ");
22596                            pw.print(libEntry.path);
22597                        } else {
22598                            pw.print(" (apk) ");
22599                            pw.print(libEntry.apk);
22600                        }
22601                        pw.println();
22602                    }
22603                }
22604            }
22605
22606            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22607                if (dumpState.onTitlePrinted())
22608                    pw.println();
22609                if (!checkin) {
22610                    pw.println("Features:");
22611                }
22612
22613                synchronized (mAvailableFeatures) {
22614                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22615                        if (checkin) {
22616                            pw.print("feat,");
22617                            pw.print(feat.name);
22618                            pw.print(",");
22619                            pw.println(feat.version);
22620                        } else {
22621                            pw.print("  ");
22622                            pw.print(feat.name);
22623                            if (feat.version > 0) {
22624                                pw.print(" version=");
22625                                pw.print(feat.version);
22626                            }
22627                            pw.println();
22628                        }
22629                    }
22630                }
22631            }
22632
22633            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22634                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22635                        : "Activity Resolver Table:", "  ", packageName,
22636                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22637                    dumpState.setTitlePrinted(true);
22638                }
22639            }
22640            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22641                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22642                        : "Receiver Resolver Table:", "  ", packageName,
22643                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22644                    dumpState.setTitlePrinted(true);
22645                }
22646            }
22647            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22648                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22649                        : "Service Resolver Table:", "  ", packageName,
22650                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22651                    dumpState.setTitlePrinted(true);
22652                }
22653            }
22654            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22655                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22656                        : "Provider Resolver Table:", "  ", packageName,
22657                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22658                    dumpState.setTitlePrinted(true);
22659                }
22660            }
22661
22662            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22663                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22664                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22665                    int user = mSettings.mPreferredActivities.keyAt(i);
22666                    if (pir.dump(pw,
22667                            dumpState.getTitlePrinted()
22668                                ? "\nPreferred Activities User " + user + ":"
22669                                : "Preferred Activities User " + user + ":", "  ",
22670                            packageName, true, false)) {
22671                        dumpState.setTitlePrinted(true);
22672                    }
22673                }
22674            }
22675
22676            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22677                pw.flush();
22678                FileOutputStream fout = new FileOutputStream(fd);
22679                BufferedOutputStream str = new BufferedOutputStream(fout);
22680                XmlSerializer serializer = new FastXmlSerializer();
22681                try {
22682                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22683                    serializer.startDocument(null, true);
22684                    serializer.setFeature(
22685                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22686                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22687                    serializer.endDocument();
22688                    serializer.flush();
22689                } catch (IllegalArgumentException e) {
22690                    pw.println("Failed writing: " + e);
22691                } catch (IllegalStateException e) {
22692                    pw.println("Failed writing: " + e);
22693                } catch (IOException e) {
22694                    pw.println("Failed writing: " + e);
22695                }
22696            }
22697
22698            if (!checkin
22699                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22700                    && packageName == null) {
22701                pw.println();
22702                int count = mSettings.mPackages.size();
22703                if (count == 0) {
22704                    pw.println("No applications!");
22705                    pw.println();
22706                } else {
22707                    final String prefix = "  ";
22708                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22709                    if (allPackageSettings.size() == 0) {
22710                        pw.println("No domain preferred apps!");
22711                        pw.println();
22712                    } else {
22713                        pw.println("App verification status:");
22714                        pw.println();
22715                        count = 0;
22716                        for (PackageSetting ps : allPackageSettings) {
22717                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22718                            if (ivi == null || ivi.getPackageName() == null) continue;
22719                            pw.println(prefix + "Package: " + ivi.getPackageName());
22720                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22721                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22722                            pw.println();
22723                            count++;
22724                        }
22725                        if (count == 0) {
22726                            pw.println(prefix + "No app verification established.");
22727                            pw.println();
22728                        }
22729                        for (int userId : sUserManager.getUserIds()) {
22730                            pw.println("App linkages for user " + userId + ":");
22731                            pw.println();
22732                            count = 0;
22733                            for (PackageSetting ps : allPackageSettings) {
22734                                final long status = ps.getDomainVerificationStatusForUser(userId);
22735                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22736                                        && !DEBUG_DOMAIN_VERIFICATION) {
22737                                    continue;
22738                                }
22739                                pw.println(prefix + "Package: " + ps.name);
22740                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22741                                String statusStr = IntentFilterVerificationInfo.
22742                                        getStatusStringFromValue(status);
22743                                pw.println(prefix + "Status:  " + statusStr);
22744                                pw.println();
22745                                count++;
22746                            }
22747                            if (count == 0) {
22748                                pw.println(prefix + "No configured app linkages.");
22749                                pw.println();
22750                            }
22751                        }
22752                    }
22753                }
22754            }
22755
22756            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22757                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22758                if (packageName == null && permissionNames == null) {
22759                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22760                        if (iperm == 0) {
22761                            if (dumpState.onTitlePrinted())
22762                                pw.println();
22763                            pw.println("AppOp Permissions:");
22764                        }
22765                        pw.print("  AppOp Permission ");
22766                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22767                        pw.println(":");
22768                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22769                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22770                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22771                        }
22772                    }
22773                }
22774            }
22775
22776            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22777                boolean printedSomething = false;
22778                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22779                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22780                        continue;
22781                    }
22782                    if (!printedSomething) {
22783                        if (dumpState.onTitlePrinted())
22784                            pw.println();
22785                        pw.println("Registered ContentProviders:");
22786                        printedSomething = true;
22787                    }
22788                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22789                    pw.print("    "); pw.println(p.toString());
22790                }
22791                printedSomething = false;
22792                for (Map.Entry<String, PackageParser.Provider> entry :
22793                        mProvidersByAuthority.entrySet()) {
22794                    PackageParser.Provider p = entry.getValue();
22795                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22796                        continue;
22797                    }
22798                    if (!printedSomething) {
22799                        if (dumpState.onTitlePrinted())
22800                            pw.println();
22801                        pw.println("ContentProvider Authorities:");
22802                        printedSomething = true;
22803                    }
22804                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22805                    pw.print("    "); pw.println(p.toString());
22806                    if (p.info != null && p.info.applicationInfo != null) {
22807                        final String appInfo = p.info.applicationInfo.toString();
22808                        pw.print("      applicationInfo="); pw.println(appInfo);
22809                    }
22810                }
22811            }
22812
22813            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22814                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22815            }
22816
22817            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22818                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22819            }
22820
22821            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22822                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22823            }
22824
22825            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22826                if (dumpState.onTitlePrinted()) pw.println();
22827                pw.println("Package Changes:");
22828                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22829                final int K = mChangedPackages.size();
22830                for (int i = 0; i < K; i++) {
22831                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22832                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22833                    final int N = changes.size();
22834                    if (N == 0) {
22835                        pw.print("    "); pw.println("No packages changed");
22836                    } else {
22837                        for (int j = 0; j < N; j++) {
22838                            final String pkgName = changes.valueAt(j);
22839                            final int sequenceNumber = changes.keyAt(j);
22840                            pw.print("    ");
22841                            pw.print("seq=");
22842                            pw.print(sequenceNumber);
22843                            pw.print(", package=");
22844                            pw.println(pkgName);
22845                        }
22846                    }
22847                }
22848            }
22849
22850            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22851                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22852            }
22853
22854            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22855                // XXX should handle packageName != null by dumping only install data that
22856                // the given package is involved with.
22857                if (dumpState.onTitlePrinted()) pw.println();
22858
22859                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22860                ipw.println();
22861                ipw.println("Frozen packages:");
22862                ipw.increaseIndent();
22863                if (mFrozenPackages.size() == 0) {
22864                    ipw.println("(none)");
22865                } else {
22866                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22867                        ipw.println(mFrozenPackages.valueAt(i));
22868                    }
22869                }
22870                ipw.decreaseIndent();
22871            }
22872
22873            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22874                if (dumpState.onTitlePrinted()) pw.println();
22875
22876                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22877                ipw.println();
22878                ipw.println("Loaded volumes:");
22879                ipw.increaseIndent();
22880                if (mLoadedVolumes.size() == 0) {
22881                    ipw.println("(none)");
22882                } else {
22883                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22884                        ipw.println(mLoadedVolumes.valueAt(i));
22885                    }
22886                }
22887                ipw.decreaseIndent();
22888            }
22889
22890            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22891                if (dumpState.onTitlePrinted()) pw.println();
22892                dumpDexoptStateLPr(pw, packageName);
22893            }
22894
22895            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22896                if (dumpState.onTitlePrinted()) pw.println();
22897                dumpCompilerStatsLPr(pw, packageName);
22898            }
22899
22900            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22901                if (dumpState.onTitlePrinted()) pw.println();
22902                mSettings.dumpReadMessagesLPr(pw, dumpState);
22903
22904                pw.println();
22905                pw.println("Package warning messages:");
22906                BufferedReader in = null;
22907                String line = null;
22908                try {
22909                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22910                    while ((line = in.readLine()) != null) {
22911                        if (line.contains("ignored: updated version")) continue;
22912                        pw.println(line);
22913                    }
22914                } catch (IOException ignored) {
22915                } finally {
22916                    IoUtils.closeQuietly(in);
22917                }
22918            }
22919
22920            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22921                BufferedReader in = null;
22922                String line = null;
22923                try {
22924                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22925                    while ((line = in.readLine()) != null) {
22926                        if (line.contains("ignored: updated version")) continue;
22927                        pw.print("msg,");
22928                        pw.println(line);
22929                    }
22930                } catch (IOException ignored) {
22931                } finally {
22932                    IoUtils.closeQuietly(in);
22933                }
22934            }
22935        }
22936
22937        // PackageInstaller should be called outside of mPackages lock
22938        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22939            // XXX should handle packageName != null by dumping only install data that
22940            // the given package is involved with.
22941            if (dumpState.onTitlePrinted()) pw.println();
22942            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22943        }
22944    }
22945
22946    private void dumpProto(FileDescriptor fd) {
22947        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22948
22949        synchronized (mPackages) {
22950            final long requiredVerifierPackageToken =
22951                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22952            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22953            proto.write(
22954                    PackageServiceDumpProto.PackageShortProto.UID,
22955                    getPackageUid(
22956                            mRequiredVerifierPackage,
22957                            MATCH_DEBUG_TRIAGED_MISSING,
22958                            UserHandle.USER_SYSTEM));
22959            proto.end(requiredVerifierPackageToken);
22960
22961            if (mIntentFilterVerifierComponent != null) {
22962                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22963                final long verifierPackageToken =
22964                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22965                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22966                proto.write(
22967                        PackageServiceDumpProto.PackageShortProto.UID,
22968                        getPackageUid(
22969                                verifierPackageName,
22970                                MATCH_DEBUG_TRIAGED_MISSING,
22971                                UserHandle.USER_SYSTEM));
22972                proto.end(verifierPackageToken);
22973            }
22974
22975            dumpSharedLibrariesProto(proto);
22976            dumpFeaturesProto(proto);
22977            mSettings.dumpPackagesProto(proto);
22978            mSettings.dumpSharedUsersProto(proto);
22979            dumpMessagesProto(proto);
22980        }
22981        proto.flush();
22982    }
22983
22984    private void dumpMessagesProto(ProtoOutputStream proto) {
22985        BufferedReader in = null;
22986        String line = null;
22987        try {
22988            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22989            while ((line = in.readLine()) != null) {
22990                if (line.contains("ignored: updated version")) continue;
22991                proto.write(PackageServiceDumpProto.MESSAGES, line);
22992            }
22993        } catch (IOException ignored) {
22994        } finally {
22995            IoUtils.closeQuietly(in);
22996        }
22997    }
22998
22999    private void dumpFeaturesProto(ProtoOutputStream proto) {
23000        synchronized (mAvailableFeatures) {
23001            final int count = mAvailableFeatures.size();
23002            for (int i = 0; i < count; i++) {
23003                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23004                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23005                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23006                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23007                proto.end(featureToken);
23008            }
23009        }
23010    }
23011
23012    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23013        final int count = mSharedLibraries.size();
23014        for (int i = 0; i < count; i++) {
23015            final String libName = mSharedLibraries.keyAt(i);
23016            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23017            if (versionedLib == null) {
23018                continue;
23019            }
23020            final int versionCount = versionedLib.size();
23021            for (int j = 0; j < versionCount; j++) {
23022                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23023                final long sharedLibraryToken =
23024                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23025                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23026                final boolean isJar = (libEntry.path != null);
23027                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23028                if (isJar) {
23029                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23030                } else {
23031                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23032                }
23033                proto.end(sharedLibraryToken);
23034            }
23035        }
23036    }
23037
23038    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23039        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23040        ipw.println();
23041        ipw.println("Dexopt state:");
23042        ipw.increaseIndent();
23043        Collection<PackageParser.Package> packages = null;
23044        if (packageName != null) {
23045            PackageParser.Package targetPackage = mPackages.get(packageName);
23046            if (targetPackage != null) {
23047                packages = Collections.singletonList(targetPackage);
23048            } else {
23049                ipw.println("Unable to find package: " + packageName);
23050                return;
23051            }
23052        } else {
23053            packages = mPackages.values();
23054        }
23055
23056        for (PackageParser.Package pkg : packages) {
23057            ipw.println("[" + pkg.packageName + "]");
23058            ipw.increaseIndent();
23059            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23060                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23061            ipw.decreaseIndent();
23062        }
23063    }
23064
23065    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23066        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23067        ipw.println();
23068        ipw.println("Compiler stats:");
23069        ipw.increaseIndent();
23070        Collection<PackageParser.Package> packages = null;
23071        if (packageName != null) {
23072            PackageParser.Package targetPackage = mPackages.get(packageName);
23073            if (targetPackage != null) {
23074                packages = Collections.singletonList(targetPackage);
23075            } else {
23076                ipw.println("Unable to find package: " + packageName);
23077                return;
23078            }
23079        } else {
23080            packages = mPackages.values();
23081        }
23082
23083        for (PackageParser.Package pkg : packages) {
23084            ipw.println("[" + pkg.packageName + "]");
23085            ipw.increaseIndent();
23086
23087            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23088            if (stats == null) {
23089                ipw.println("(No recorded stats)");
23090            } else {
23091                stats.dump(ipw);
23092            }
23093            ipw.decreaseIndent();
23094        }
23095    }
23096
23097    private String dumpDomainString(String packageName) {
23098        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23099                .getList();
23100        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23101
23102        ArraySet<String> result = new ArraySet<>();
23103        if (iviList.size() > 0) {
23104            for (IntentFilterVerificationInfo ivi : iviList) {
23105                for (String host : ivi.getDomains()) {
23106                    result.add(host);
23107                }
23108            }
23109        }
23110        if (filters != null && filters.size() > 0) {
23111            for (IntentFilter filter : filters) {
23112                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23113                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23114                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23115                    result.addAll(filter.getHostsList());
23116                }
23117            }
23118        }
23119
23120        StringBuilder sb = new StringBuilder(result.size() * 16);
23121        for (String domain : result) {
23122            if (sb.length() > 0) sb.append(" ");
23123            sb.append(domain);
23124        }
23125        return sb.toString();
23126    }
23127
23128    // ------- apps on sdcard specific code -------
23129    static final boolean DEBUG_SD_INSTALL = false;
23130
23131    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23132
23133    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23134
23135    private boolean mMediaMounted = false;
23136
23137    static String getEncryptKey() {
23138        try {
23139            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23140                    SD_ENCRYPTION_KEYSTORE_NAME);
23141            if (sdEncKey == null) {
23142                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23143                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23144                if (sdEncKey == null) {
23145                    Slog.e(TAG, "Failed to create encryption keys");
23146                    return null;
23147                }
23148            }
23149            return sdEncKey;
23150        } catch (NoSuchAlgorithmException nsae) {
23151            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23152            return null;
23153        } catch (IOException ioe) {
23154            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23155            return null;
23156        }
23157    }
23158
23159    /*
23160     * Update media status on PackageManager.
23161     */
23162    @Override
23163    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23164        enforceSystemOrRoot("Media status can only be updated by the system");
23165        // reader; this apparently protects mMediaMounted, but should probably
23166        // be a different lock in that case.
23167        synchronized (mPackages) {
23168            Log.i(TAG, "Updating external media status from "
23169                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23170                    + (mediaStatus ? "mounted" : "unmounted"));
23171            if (DEBUG_SD_INSTALL)
23172                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23173                        + ", mMediaMounted=" + mMediaMounted);
23174            if (mediaStatus == mMediaMounted) {
23175                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23176                        : 0, -1);
23177                mHandler.sendMessage(msg);
23178                return;
23179            }
23180            mMediaMounted = mediaStatus;
23181        }
23182        // Queue up an async operation since the package installation may take a
23183        // little while.
23184        mHandler.post(new Runnable() {
23185            public void run() {
23186                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23187            }
23188        });
23189    }
23190
23191    /**
23192     * Called by StorageManagerService when the initial ASECs to scan are available.
23193     * Should block until all the ASEC containers are finished being scanned.
23194     */
23195    public void scanAvailableAsecs() {
23196        updateExternalMediaStatusInner(true, false, false);
23197    }
23198
23199    /*
23200     * Collect information of applications on external media, map them against
23201     * existing containers and update information based on current mount status.
23202     * Please note that we always have to report status if reportStatus has been
23203     * set to true especially when unloading packages.
23204     */
23205    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23206            boolean externalStorage) {
23207        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23208        int[] uidArr = EmptyArray.INT;
23209
23210        final String[] list = PackageHelper.getSecureContainerList();
23211        if (ArrayUtils.isEmpty(list)) {
23212            Log.i(TAG, "No secure containers found");
23213        } else {
23214            // Process list of secure containers and categorize them
23215            // as active or stale based on their package internal state.
23216
23217            // reader
23218            synchronized (mPackages) {
23219                for (String cid : list) {
23220                    // Leave stages untouched for now; installer service owns them
23221                    if (PackageInstallerService.isStageName(cid)) continue;
23222
23223                    if (DEBUG_SD_INSTALL)
23224                        Log.i(TAG, "Processing container " + cid);
23225                    String pkgName = getAsecPackageName(cid);
23226                    if (pkgName == null) {
23227                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23228                        continue;
23229                    }
23230                    if (DEBUG_SD_INSTALL)
23231                        Log.i(TAG, "Looking for pkg : " + pkgName);
23232
23233                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23234                    if (ps == null) {
23235                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23236                        continue;
23237                    }
23238
23239                    /*
23240                     * Skip packages that are not external if we're unmounting
23241                     * external storage.
23242                     */
23243                    if (externalStorage && !isMounted && !isExternal(ps)) {
23244                        continue;
23245                    }
23246
23247                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23248                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23249                    // The package status is changed only if the code path
23250                    // matches between settings and the container id.
23251                    if (ps.codePathString != null
23252                            && ps.codePathString.startsWith(args.getCodePath())) {
23253                        if (DEBUG_SD_INSTALL) {
23254                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23255                                    + " at code path: " + ps.codePathString);
23256                        }
23257
23258                        // We do have a valid package installed on sdcard
23259                        processCids.put(args, ps.codePathString);
23260                        final int uid = ps.appId;
23261                        if (uid != -1) {
23262                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23263                        }
23264                    } else {
23265                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23266                                + ps.codePathString);
23267                    }
23268                }
23269            }
23270
23271            Arrays.sort(uidArr);
23272        }
23273
23274        // Process packages with valid entries.
23275        if (isMounted) {
23276            if (DEBUG_SD_INSTALL)
23277                Log.i(TAG, "Loading packages");
23278            loadMediaPackages(processCids, uidArr, externalStorage);
23279            startCleaningPackages();
23280            mInstallerService.onSecureContainersAvailable();
23281        } else {
23282            if (DEBUG_SD_INSTALL)
23283                Log.i(TAG, "Unloading packages");
23284            unloadMediaPackages(processCids, uidArr, reportStatus);
23285        }
23286    }
23287
23288    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23289            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23290        final int size = infos.size();
23291        final String[] packageNames = new String[size];
23292        final int[] packageUids = new int[size];
23293        for (int i = 0; i < size; i++) {
23294            final ApplicationInfo info = infos.get(i);
23295            packageNames[i] = info.packageName;
23296            packageUids[i] = info.uid;
23297        }
23298        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23299                finishedReceiver);
23300    }
23301
23302    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23303            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23304        sendResourcesChangedBroadcast(mediaStatus, replacing,
23305                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23306    }
23307
23308    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23309            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23310        int size = pkgList.length;
23311        if (size > 0) {
23312            // Send broadcasts here
23313            Bundle extras = new Bundle();
23314            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23315            if (uidArr != null) {
23316                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23317            }
23318            if (replacing) {
23319                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23320            }
23321            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23322                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23323            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23324        }
23325    }
23326
23327   /*
23328     * Look at potentially valid container ids from processCids If package
23329     * information doesn't match the one on record or package scanning fails,
23330     * the cid is added to list of removeCids. We currently don't delete stale
23331     * containers.
23332     */
23333    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23334            boolean externalStorage) {
23335        ArrayList<String> pkgList = new ArrayList<String>();
23336        Set<AsecInstallArgs> keys = processCids.keySet();
23337
23338        for (AsecInstallArgs args : keys) {
23339            String codePath = processCids.get(args);
23340            if (DEBUG_SD_INSTALL)
23341                Log.i(TAG, "Loading container : " + args.cid);
23342            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23343            try {
23344                // Make sure there are no container errors first.
23345                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23346                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23347                            + " when installing from sdcard");
23348                    continue;
23349                }
23350                // Check code path here.
23351                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23352                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23353                            + " does not match one in settings " + codePath);
23354                    continue;
23355                }
23356                // Parse package
23357                int parseFlags = mDefParseFlags;
23358                if (args.isExternalAsec()) {
23359                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23360                }
23361                if (args.isFwdLocked()) {
23362                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23363                }
23364
23365                synchronized (mInstallLock) {
23366                    PackageParser.Package pkg = null;
23367                    try {
23368                        // Sadly we don't know the package name yet to freeze it
23369                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23370                                SCAN_IGNORE_FROZEN, 0, null);
23371                    } catch (PackageManagerException e) {
23372                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23373                    }
23374                    // Scan the package
23375                    if (pkg != null) {
23376                        /*
23377                         * TODO why is the lock being held? doPostInstall is
23378                         * called in other places without the lock. This needs
23379                         * to be straightened out.
23380                         */
23381                        // writer
23382                        synchronized (mPackages) {
23383                            retCode = PackageManager.INSTALL_SUCCEEDED;
23384                            pkgList.add(pkg.packageName);
23385                            // Post process args
23386                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23387                                    pkg.applicationInfo.uid);
23388                        }
23389                    } else {
23390                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23391                    }
23392                }
23393
23394            } finally {
23395                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23396                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23397                }
23398            }
23399        }
23400        // writer
23401        synchronized (mPackages) {
23402            // If the platform SDK has changed since the last time we booted,
23403            // we need to re-grant app permission to catch any new ones that
23404            // appear. This is really a hack, and means that apps can in some
23405            // cases get permissions that the user didn't initially explicitly
23406            // allow... it would be nice to have some better way to handle
23407            // this situation.
23408            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23409                    : mSettings.getInternalVersion();
23410            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23411                    : StorageManager.UUID_PRIVATE_INTERNAL;
23412
23413            int updateFlags = UPDATE_PERMISSIONS_ALL;
23414            if (ver.sdkVersion != mSdkVersion) {
23415                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23416                        + mSdkVersion + "; regranting permissions for external");
23417                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23418            }
23419            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23420
23421            // Yay, everything is now upgraded
23422            ver.forceCurrent();
23423
23424            // can downgrade to reader
23425            // Persist settings
23426            mSettings.writeLPr();
23427        }
23428        // Send a broadcast to let everyone know we are done processing
23429        if (pkgList.size() > 0) {
23430            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23431        }
23432    }
23433
23434   /*
23435     * Utility method to unload a list of specified containers
23436     */
23437    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23438        // Just unmount all valid containers.
23439        for (AsecInstallArgs arg : cidArgs) {
23440            synchronized (mInstallLock) {
23441                arg.doPostDeleteLI(false);
23442           }
23443       }
23444   }
23445
23446    /*
23447     * Unload packages mounted on external media. This involves deleting package
23448     * data from internal structures, sending broadcasts about disabled packages,
23449     * gc'ing to free up references, unmounting all secure containers
23450     * corresponding to packages on external media, and posting a
23451     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23452     * that we always have to post this message if status has been requested no
23453     * matter what.
23454     */
23455    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23456            final boolean reportStatus) {
23457        if (DEBUG_SD_INSTALL)
23458            Log.i(TAG, "unloading media packages");
23459        ArrayList<String> pkgList = new ArrayList<String>();
23460        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23461        final Set<AsecInstallArgs> keys = processCids.keySet();
23462        for (AsecInstallArgs args : keys) {
23463            String pkgName = args.getPackageName();
23464            if (DEBUG_SD_INSTALL)
23465                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23466            // Delete package internally
23467            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23468            synchronized (mInstallLock) {
23469                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23470                final boolean res;
23471                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23472                        "unloadMediaPackages")) {
23473                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23474                            null);
23475                }
23476                if (res) {
23477                    pkgList.add(pkgName);
23478                } else {
23479                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23480                    failedList.add(args);
23481                }
23482            }
23483        }
23484
23485        // reader
23486        synchronized (mPackages) {
23487            // We didn't update the settings after removing each package;
23488            // write them now for all packages.
23489            mSettings.writeLPr();
23490        }
23491
23492        // We have to absolutely send UPDATED_MEDIA_STATUS only
23493        // after confirming that all the receivers processed the ordered
23494        // broadcast when packages get disabled, force a gc to clean things up.
23495        // and unload all the containers.
23496        if (pkgList.size() > 0) {
23497            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23498                    new IIntentReceiver.Stub() {
23499                public void performReceive(Intent intent, int resultCode, String data,
23500                        Bundle extras, boolean ordered, boolean sticky,
23501                        int sendingUser) throws RemoteException {
23502                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23503                            reportStatus ? 1 : 0, 1, keys);
23504                    mHandler.sendMessage(msg);
23505                }
23506            });
23507        } else {
23508            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23509                    keys);
23510            mHandler.sendMessage(msg);
23511        }
23512    }
23513
23514    private void loadPrivatePackages(final VolumeInfo vol) {
23515        mHandler.post(new Runnable() {
23516            @Override
23517            public void run() {
23518                loadPrivatePackagesInner(vol);
23519            }
23520        });
23521    }
23522
23523    private void loadPrivatePackagesInner(VolumeInfo vol) {
23524        final String volumeUuid = vol.fsUuid;
23525        if (TextUtils.isEmpty(volumeUuid)) {
23526            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23527            return;
23528        }
23529
23530        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23531        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23532        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23533
23534        final VersionInfo ver;
23535        final List<PackageSetting> packages;
23536        synchronized (mPackages) {
23537            ver = mSettings.findOrCreateVersion(volumeUuid);
23538            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23539        }
23540
23541        for (PackageSetting ps : packages) {
23542            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23543            synchronized (mInstallLock) {
23544                final PackageParser.Package pkg;
23545                try {
23546                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23547                    loaded.add(pkg.applicationInfo);
23548
23549                } catch (PackageManagerException e) {
23550                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23551                }
23552
23553                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23554                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23555                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23556                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23557                }
23558            }
23559        }
23560
23561        // Reconcile app data for all started/unlocked users
23562        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23563        final UserManager um = mContext.getSystemService(UserManager.class);
23564        UserManagerInternal umInternal = getUserManagerInternal();
23565        for (UserInfo user : um.getUsers()) {
23566            final int flags;
23567            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23568                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23569            } else if (umInternal.isUserRunning(user.id)) {
23570                flags = StorageManager.FLAG_STORAGE_DE;
23571            } else {
23572                continue;
23573            }
23574
23575            try {
23576                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23577                synchronized (mInstallLock) {
23578                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23579                }
23580            } catch (IllegalStateException e) {
23581                // Device was probably ejected, and we'll process that event momentarily
23582                Slog.w(TAG, "Failed to prepare storage: " + e);
23583            }
23584        }
23585
23586        synchronized (mPackages) {
23587            int updateFlags = UPDATE_PERMISSIONS_ALL;
23588            if (ver.sdkVersion != mSdkVersion) {
23589                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23590                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23591                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23592            }
23593            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23594
23595            // Yay, everything is now upgraded
23596            ver.forceCurrent();
23597
23598            mSettings.writeLPr();
23599        }
23600
23601        for (PackageFreezer freezer : freezers) {
23602            freezer.close();
23603        }
23604
23605        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23606        sendResourcesChangedBroadcast(true, false, loaded, null);
23607        mLoadedVolumes.add(vol.getId());
23608    }
23609
23610    private void unloadPrivatePackages(final VolumeInfo vol) {
23611        mHandler.post(new Runnable() {
23612            @Override
23613            public void run() {
23614                unloadPrivatePackagesInner(vol);
23615            }
23616        });
23617    }
23618
23619    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23620        final String volumeUuid = vol.fsUuid;
23621        if (TextUtils.isEmpty(volumeUuid)) {
23622            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23623            return;
23624        }
23625
23626        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23627        synchronized (mInstallLock) {
23628        synchronized (mPackages) {
23629            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23630            for (PackageSetting ps : packages) {
23631                if (ps.pkg == null) continue;
23632
23633                final ApplicationInfo info = ps.pkg.applicationInfo;
23634                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23635                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23636
23637                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23638                        "unloadPrivatePackagesInner")) {
23639                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23640                            false, null)) {
23641                        unloaded.add(info);
23642                    } else {
23643                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23644                    }
23645                }
23646
23647                // Try very hard to release any references to this package
23648                // so we don't risk the system server being killed due to
23649                // open FDs
23650                AttributeCache.instance().removePackage(ps.name);
23651            }
23652
23653            mSettings.writeLPr();
23654        }
23655        }
23656
23657        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23658        sendResourcesChangedBroadcast(false, false, unloaded, null);
23659        mLoadedVolumes.remove(vol.getId());
23660
23661        // Try very hard to release any references to this path so we don't risk
23662        // the system server being killed due to open FDs
23663        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23664
23665        for (int i = 0; i < 3; i++) {
23666            System.gc();
23667            System.runFinalization();
23668        }
23669    }
23670
23671    private void assertPackageKnown(String volumeUuid, String packageName)
23672            throws PackageManagerException {
23673        synchronized (mPackages) {
23674            // Normalize package name to handle renamed packages
23675            packageName = normalizePackageNameLPr(packageName);
23676
23677            final PackageSetting ps = mSettings.mPackages.get(packageName);
23678            if (ps == null) {
23679                throw new PackageManagerException("Package " + packageName + " is unknown");
23680            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23681                throw new PackageManagerException(
23682                        "Package " + packageName + " found on unknown volume " + volumeUuid
23683                                + "; expected volume " + ps.volumeUuid);
23684            }
23685        }
23686    }
23687
23688    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23689            throws PackageManagerException {
23690        synchronized (mPackages) {
23691            // Normalize package name to handle renamed packages
23692            packageName = normalizePackageNameLPr(packageName);
23693
23694            final PackageSetting ps = mSettings.mPackages.get(packageName);
23695            if (ps == null) {
23696                throw new PackageManagerException("Package " + packageName + " is unknown");
23697            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23698                throw new PackageManagerException(
23699                        "Package " + packageName + " found on unknown volume " + volumeUuid
23700                                + "; expected volume " + ps.volumeUuid);
23701            } else if (!ps.getInstalled(userId)) {
23702                throw new PackageManagerException(
23703                        "Package " + packageName + " not installed for user " + userId);
23704            }
23705        }
23706    }
23707
23708    private List<String> collectAbsoluteCodePaths() {
23709        synchronized (mPackages) {
23710            List<String> codePaths = new ArrayList<>();
23711            final int packageCount = mSettings.mPackages.size();
23712            for (int i = 0; i < packageCount; i++) {
23713                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23714                codePaths.add(ps.codePath.getAbsolutePath());
23715            }
23716            return codePaths;
23717        }
23718    }
23719
23720    /**
23721     * Examine all apps present on given mounted volume, and destroy apps that
23722     * aren't expected, either due to uninstallation or reinstallation on
23723     * another volume.
23724     */
23725    private void reconcileApps(String volumeUuid) {
23726        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23727        List<File> filesToDelete = null;
23728
23729        final File[] files = FileUtils.listFilesOrEmpty(
23730                Environment.getDataAppDirectory(volumeUuid));
23731        for (File file : files) {
23732            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23733                    && !PackageInstallerService.isStageName(file.getName());
23734            if (!isPackage) {
23735                // Ignore entries which are not packages
23736                continue;
23737            }
23738
23739            String absolutePath = file.getAbsolutePath();
23740
23741            boolean pathValid = false;
23742            final int absoluteCodePathCount = absoluteCodePaths.size();
23743            for (int i = 0; i < absoluteCodePathCount; i++) {
23744                String absoluteCodePath = absoluteCodePaths.get(i);
23745                if (absolutePath.startsWith(absoluteCodePath)) {
23746                    pathValid = true;
23747                    break;
23748                }
23749            }
23750
23751            if (!pathValid) {
23752                if (filesToDelete == null) {
23753                    filesToDelete = new ArrayList<>();
23754                }
23755                filesToDelete.add(file);
23756            }
23757        }
23758
23759        if (filesToDelete != null) {
23760            final int fileToDeleteCount = filesToDelete.size();
23761            for (int i = 0; i < fileToDeleteCount; i++) {
23762                File fileToDelete = filesToDelete.get(i);
23763                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23764                synchronized (mInstallLock) {
23765                    removeCodePathLI(fileToDelete);
23766                }
23767            }
23768        }
23769    }
23770
23771    /**
23772     * Reconcile all app data for the given user.
23773     * <p>
23774     * Verifies that directories exist and that ownership and labeling is
23775     * correct for all installed apps on all mounted volumes.
23776     */
23777    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23778        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23779        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23780            final String volumeUuid = vol.getFsUuid();
23781            synchronized (mInstallLock) {
23782                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23783            }
23784        }
23785    }
23786
23787    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23788            boolean migrateAppData) {
23789        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23790    }
23791
23792    /**
23793     * Reconcile all app data on given mounted volume.
23794     * <p>
23795     * Destroys app data that isn't expected, either due to uninstallation or
23796     * reinstallation on another volume.
23797     * <p>
23798     * Verifies that directories exist and that ownership and labeling is
23799     * correct for all installed apps.
23800     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23801     */
23802    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23803            boolean migrateAppData, boolean onlyCoreApps) {
23804        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23805                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23806        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23807
23808        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23809        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23810
23811        // First look for stale data that doesn't belong, and check if things
23812        // have changed since we did our last restorecon
23813        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23814            if (StorageManager.isFileEncryptedNativeOrEmulated()
23815                    && !StorageManager.isUserKeyUnlocked(userId)) {
23816                throw new RuntimeException(
23817                        "Yikes, someone asked us to reconcile CE storage while " + userId
23818                                + " was still locked; this would have caused massive data loss!");
23819            }
23820
23821            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23822            for (File file : files) {
23823                final String packageName = file.getName();
23824                try {
23825                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23826                } catch (PackageManagerException e) {
23827                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23828                    try {
23829                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23830                                StorageManager.FLAG_STORAGE_CE, 0);
23831                    } catch (InstallerException e2) {
23832                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23833                    }
23834                }
23835            }
23836        }
23837        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23838            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23839            for (File file : files) {
23840                final String packageName = file.getName();
23841                try {
23842                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23843                } catch (PackageManagerException e) {
23844                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23845                    try {
23846                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23847                                StorageManager.FLAG_STORAGE_DE, 0);
23848                    } catch (InstallerException e2) {
23849                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23850                    }
23851                }
23852            }
23853        }
23854
23855        // Ensure that data directories are ready to roll for all packages
23856        // installed for this volume and user
23857        final List<PackageSetting> packages;
23858        synchronized (mPackages) {
23859            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23860        }
23861        int preparedCount = 0;
23862        for (PackageSetting ps : packages) {
23863            final String packageName = ps.name;
23864            if (ps.pkg == null) {
23865                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23866                // TODO: might be due to legacy ASEC apps; we should circle back
23867                // and reconcile again once they're scanned
23868                continue;
23869            }
23870            // Skip non-core apps if requested
23871            if (onlyCoreApps && !ps.pkg.coreApp) {
23872                result.add(packageName);
23873                continue;
23874            }
23875
23876            if (ps.getInstalled(userId)) {
23877                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23878                preparedCount++;
23879            }
23880        }
23881
23882        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23883        return result;
23884    }
23885
23886    /**
23887     * Prepare app data for the given app just after it was installed or
23888     * upgraded. This method carefully only touches users that it's installed
23889     * for, and it forces a restorecon to handle any seinfo changes.
23890     * <p>
23891     * Verifies that directories exist and that ownership and labeling is
23892     * correct for all installed apps. If there is an ownership mismatch, it
23893     * will try recovering system apps by wiping data; third-party app data is
23894     * left intact.
23895     * <p>
23896     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23897     */
23898    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23899        final PackageSetting ps;
23900        synchronized (mPackages) {
23901            ps = mSettings.mPackages.get(pkg.packageName);
23902            mSettings.writeKernelMappingLPr(ps);
23903        }
23904
23905        final UserManager um = mContext.getSystemService(UserManager.class);
23906        UserManagerInternal umInternal = getUserManagerInternal();
23907        for (UserInfo user : um.getUsers()) {
23908            final int flags;
23909            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23910                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23911            } else if (umInternal.isUserRunning(user.id)) {
23912                flags = StorageManager.FLAG_STORAGE_DE;
23913            } else {
23914                continue;
23915            }
23916
23917            if (ps.getInstalled(user.id)) {
23918                // TODO: when user data is locked, mark that we're still dirty
23919                prepareAppDataLIF(pkg, user.id, flags);
23920            }
23921        }
23922    }
23923
23924    /**
23925     * Prepare app data for the given app.
23926     * <p>
23927     * Verifies that directories exist and that ownership and labeling is
23928     * correct for all installed apps. If there is an ownership mismatch, this
23929     * will try recovering system apps by wiping data; third-party app data is
23930     * left intact.
23931     */
23932    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23933        if (pkg == null) {
23934            Slog.wtf(TAG, "Package was null!", new Throwable());
23935            return;
23936        }
23937        prepareAppDataLeafLIF(pkg, userId, flags);
23938        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23939        for (int i = 0; i < childCount; i++) {
23940            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23941        }
23942    }
23943
23944    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23945            boolean maybeMigrateAppData) {
23946        prepareAppDataLIF(pkg, userId, flags);
23947
23948        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23949            // We may have just shuffled around app data directories, so
23950            // prepare them one more time
23951            prepareAppDataLIF(pkg, userId, flags);
23952        }
23953    }
23954
23955    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23956        if (DEBUG_APP_DATA) {
23957            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23958                    + Integer.toHexString(flags));
23959        }
23960
23961        final String volumeUuid = pkg.volumeUuid;
23962        final String packageName = pkg.packageName;
23963        final ApplicationInfo app = pkg.applicationInfo;
23964        final int appId = UserHandle.getAppId(app.uid);
23965
23966        Preconditions.checkNotNull(app.seInfo);
23967
23968        long ceDataInode = -1;
23969        try {
23970            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23971                    appId, app.seInfo, app.targetSdkVersion);
23972        } catch (InstallerException e) {
23973            if (app.isSystemApp()) {
23974                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23975                        + ", but trying to recover: " + e);
23976                destroyAppDataLeafLIF(pkg, userId, flags);
23977                try {
23978                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23979                            appId, app.seInfo, app.targetSdkVersion);
23980                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23981                } catch (InstallerException e2) {
23982                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23983                }
23984            } else {
23985                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23986            }
23987        }
23988
23989        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23990            // TODO: mark this structure as dirty so we persist it!
23991            synchronized (mPackages) {
23992                final PackageSetting ps = mSettings.mPackages.get(packageName);
23993                if (ps != null) {
23994                    ps.setCeDataInode(ceDataInode, userId);
23995                }
23996            }
23997        }
23998
23999        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24000    }
24001
24002    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24003        if (pkg == null) {
24004            Slog.wtf(TAG, "Package was null!", new Throwable());
24005            return;
24006        }
24007        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24008        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24009        for (int i = 0; i < childCount; i++) {
24010            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24011        }
24012    }
24013
24014    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24015        final String volumeUuid = pkg.volumeUuid;
24016        final String packageName = pkg.packageName;
24017        final ApplicationInfo app = pkg.applicationInfo;
24018
24019        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24020            // Create a native library symlink only if we have native libraries
24021            // and if the native libraries are 32 bit libraries. We do not provide
24022            // this symlink for 64 bit libraries.
24023            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24024                final String nativeLibPath = app.nativeLibraryDir;
24025                try {
24026                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24027                            nativeLibPath, userId);
24028                } catch (InstallerException e) {
24029                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24030                }
24031            }
24032        }
24033    }
24034
24035    /**
24036     * For system apps on non-FBE devices, this method migrates any existing
24037     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24038     * requested by the app.
24039     */
24040    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24041        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24042                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24043            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24044                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24045            try {
24046                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24047                        storageTarget);
24048            } catch (InstallerException e) {
24049                logCriticalInfo(Log.WARN,
24050                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24051            }
24052            return true;
24053        } else {
24054            return false;
24055        }
24056    }
24057
24058    public PackageFreezer freezePackage(String packageName, String killReason) {
24059        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24060    }
24061
24062    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24063        return new PackageFreezer(packageName, userId, killReason);
24064    }
24065
24066    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24067            String killReason) {
24068        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24069    }
24070
24071    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24072            String killReason) {
24073        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24074            return new PackageFreezer();
24075        } else {
24076            return freezePackage(packageName, userId, killReason);
24077        }
24078    }
24079
24080    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24081            String killReason) {
24082        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24083    }
24084
24085    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24086            String killReason) {
24087        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24088            return new PackageFreezer();
24089        } else {
24090            return freezePackage(packageName, userId, killReason);
24091        }
24092    }
24093
24094    /**
24095     * Class that freezes and kills the given package upon creation, and
24096     * unfreezes it upon closing. This is typically used when doing surgery on
24097     * app code/data to prevent the app from running while you're working.
24098     */
24099    private class PackageFreezer implements AutoCloseable {
24100        private final String mPackageName;
24101        private final PackageFreezer[] mChildren;
24102
24103        private final boolean mWeFroze;
24104
24105        private final AtomicBoolean mClosed = new AtomicBoolean();
24106        private final CloseGuard mCloseGuard = CloseGuard.get();
24107
24108        /**
24109         * Create and return a stub freezer that doesn't actually do anything,
24110         * typically used when someone requested
24111         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24112         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24113         */
24114        public PackageFreezer() {
24115            mPackageName = null;
24116            mChildren = null;
24117            mWeFroze = false;
24118            mCloseGuard.open("close");
24119        }
24120
24121        public PackageFreezer(String packageName, int userId, String killReason) {
24122            synchronized (mPackages) {
24123                mPackageName = packageName;
24124                mWeFroze = mFrozenPackages.add(mPackageName);
24125
24126                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24127                if (ps != null) {
24128                    killApplication(ps.name, ps.appId, userId, killReason);
24129                }
24130
24131                final PackageParser.Package p = mPackages.get(packageName);
24132                if (p != null && p.childPackages != null) {
24133                    final int N = p.childPackages.size();
24134                    mChildren = new PackageFreezer[N];
24135                    for (int i = 0; i < N; i++) {
24136                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24137                                userId, killReason);
24138                    }
24139                } else {
24140                    mChildren = null;
24141                }
24142            }
24143            mCloseGuard.open("close");
24144        }
24145
24146        @Override
24147        protected void finalize() throws Throwable {
24148            try {
24149                if (mCloseGuard != null) {
24150                    mCloseGuard.warnIfOpen();
24151                }
24152
24153                close();
24154            } finally {
24155                super.finalize();
24156            }
24157        }
24158
24159        @Override
24160        public void close() {
24161            mCloseGuard.close();
24162            if (mClosed.compareAndSet(false, true)) {
24163                synchronized (mPackages) {
24164                    if (mWeFroze) {
24165                        mFrozenPackages.remove(mPackageName);
24166                    }
24167
24168                    if (mChildren != null) {
24169                        for (PackageFreezer freezer : mChildren) {
24170                            freezer.close();
24171                        }
24172                    }
24173                }
24174            }
24175        }
24176    }
24177
24178    /**
24179     * Verify that given package is currently frozen.
24180     */
24181    private void checkPackageFrozen(String packageName) {
24182        synchronized (mPackages) {
24183            if (!mFrozenPackages.contains(packageName)) {
24184                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24185            }
24186        }
24187    }
24188
24189    @Override
24190    public int movePackage(final String packageName, final String volumeUuid) {
24191        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24192
24193        final int callingUid = Binder.getCallingUid();
24194        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24195        final int moveId = mNextMoveId.getAndIncrement();
24196        mHandler.post(new Runnable() {
24197            @Override
24198            public void run() {
24199                try {
24200                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24201                } catch (PackageManagerException e) {
24202                    Slog.w(TAG, "Failed to move " + packageName, e);
24203                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24204                }
24205            }
24206        });
24207        return moveId;
24208    }
24209
24210    private void movePackageInternal(final String packageName, final String volumeUuid,
24211            final int moveId, final int callingUid, UserHandle user)
24212                    throws PackageManagerException {
24213        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24214        final PackageManager pm = mContext.getPackageManager();
24215
24216        final boolean currentAsec;
24217        final String currentVolumeUuid;
24218        final File codeFile;
24219        final String installerPackageName;
24220        final String packageAbiOverride;
24221        final int appId;
24222        final String seinfo;
24223        final String label;
24224        final int targetSdkVersion;
24225        final PackageFreezer freezer;
24226        final int[] installedUserIds;
24227
24228        // reader
24229        synchronized (mPackages) {
24230            final PackageParser.Package pkg = mPackages.get(packageName);
24231            final PackageSetting ps = mSettings.mPackages.get(packageName);
24232            if (pkg == null
24233                    || ps == null
24234                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24235                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24236            }
24237            if (pkg.applicationInfo.isSystemApp()) {
24238                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24239                        "Cannot move system application");
24240            }
24241
24242            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24243            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24244                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24245            if (isInternalStorage && !allow3rdPartyOnInternal) {
24246                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24247                        "3rd party apps are not allowed on internal storage");
24248            }
24249
24250            if (pkg.applicationInfo.isExternalAsec()) {
24251                currentAsec = true;
24252                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24253            } else if (pkg.applicationInfo.isForwardLocked()) {
24254                currentAsec = true;
24255                currentVolumeUuid = "forward_locked";
24256            } else {
24257                currentAsec = false;
24258                currentVolumeUuid = ps.volumeUuid;
24259
24260                final File probe = new File(pkg.codePath);
24261                final File probeOat = new File(probe, "oat");
24262                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24263                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24264                            "Move only supported for modern cluster style installs");
24265                }
24266            }
24267
24268            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24269                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24270                        "Package already moved to " + volumeUuid);
24271            }
24272            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24273                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24274                        "Device admin cannot be moved");
24275            }
24276
24277            if (mFrozenPackages.contains(packageName)) {
24278                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24279                        "Failed to move already frozen package");
24280            }
24281
24282            codeFile = new File(pkg.codePath);
24283            installerPackageName = ps.installerPackageName;
24284            packageAbiOverride = ps.cpuAbiOverrideString;
24285            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24286            seinfo = pkg.applicationInfo.seInfo;
24287            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24288            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24289            freezer = freezePackage(packageName, "movePackageInternal");
24290            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24291        }
24292
24293        final Bundle extras = new Bundle();
24294        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24295        extras.putString(Intent.EXTRA_TITLE, label);
24296        mMoveCallbacks.notifyCreated(moveId, extras);
24297
24298        int installFlags;
24299        final boolean moveCompleteApp;
24300        final File measurePath;
24301
24302        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24303            installFlags = INSTALL_INTERNAL;
24304            moveCompleteApp = !currentAsec;
24305            measurePath = Environment.getDataAppDirectory(volumeUuid);
24306        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24307            installFlags = INSTALL_EXTERNAL;
24308            moveCompleteApp = false;
24309            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24310        } else {
24311            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24312            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24313                    || !volume.isMountedWritable()) {
24314                freezer.close();
24315                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24316                        "Move location not mounted private volume");
24317            }
24318
24319            Preconditions.checkState(!currentAsec);
24320
24321            installFlags = INSTALL_INTERNAL;
24322            moveCompleteApp = true;
24323            measurePath = Environment.getDataAppDirectory(volumeUuid);
24324        }
24325
24326        // If we're moving app data around, we need all the users unlocked
24327        if (moveCompleteApp) {
24328            for (int userId : installedUserIds) {
24329                if (StorageManager.isFileEncryptedNativeOrEmulated()
24330                        && !StorageManager.isUserKeyUnlocked(userId)) {
24331                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24332                            "User " + userId + " must be unlocked");
24333                }
24334            }
24335        }
24336
24337        final PackageStats stats = new PackageStats(null, -1);
24338        synchronized (mInstaller) {
24339            for (int userId : installedUserIds) {
24340                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24341                    freezer.close();
24342                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24343                            "Failed to measure package size");
24344                }
24345            }
24346        }
24347
24348        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24349                + stats.dataSize);
24350
24351        final long startFreeBytes = measurePath.getUsableSpace();
24352        final long sizeBytes;
24353        if (moveCompleteApp) {
24354            sizeBytes = stats.codeSize + stats.dataSize;
24355        } else {
24356            sizeBytes = stats.codeSize;
24357        }
24358
24359        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24360            freezer.close();
24361            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24362                    "Not enough free space to move");
24363        }
24364
24365        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24366
24367        final CountDownLatch installedLatch = new CountDownLatch(1);
24368        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24369            @Override
24370            public void onUserActionRequired(Intent intent) throws RemoteException {
24371                throw new IllegalStateException();
24372            }
24373
24374            @Override
24375            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24376                    Bundle extras) throws RemoteException {
24377                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24378                        + PackageManager.installStatusToString(returnCode, msg));
24379
24380                installedLatch.countDown();
24381                freezer.close();
24382
24383                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24384                switch (status) {
24385                    case PackageInstaller.STATUS_SUCCESS:
24386                        mMoveCallbacks.notifyStatusChanged(moveId,
24387                                PackageManager.MOVE_SUCCEEDED);
24388                        break;
24389                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24390                        mMoveCallbacks.notifyStatusChanged(moveId,
24391                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24392                        break;
24393                    default:
24394                        mMoveCallbacks.notifyStatusChanged(moveId,
24395                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24396                        break;
24397                }
24398            }
24399        };
24400
24401        final MoveInfo move;
24402        if (moveCompleteApp) {
24403            // Kick off a thread to report progress estimates
24404            new Thread() {
24405                @Override
24406                public void run() {
24407                    while (true) {
24408                        try {
24409                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24410                                break;
24411                            }
24412                        } catch (InterruptedException ignored) {
24413                        }
24414
24415                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24416                        final int progress = 10 + (int) MathUtils.constrain(
24417                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24418                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24419                    }
24420                }
24421            }.start();
24422
24423            final String dataAppName = codeFile.getName();
24424            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24425                    dataAppName, appId, seinfo, targetSdkVersion);
24426        } else {
24427            move = null;
24428        }
24429
24430        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24431
24432        final Message msg = mHandler.obtainMessage(INIT_COPY);
24433        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24434        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24435                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24436                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24437                PackageManager.INSTALL_REASON_UNKNOWN);
24438        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24439        msg.obj = params;
24440
24441        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24442                System.identityHashCode(msg.obj));
24443        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24444                System.identityHashCode(msg.obj));
24445
24446        mHandler.sendMessage(msg);
24447    }
24448
24449    @Override
24450    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24451        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24452
24453        final int realMoveId = mNextMoveId.getAndIncrement();
24454        final Bundle extras = new Bundle();
24455        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24456        mMoveCallbacks.notifyCreated(realMoveId, extras);
24457
24458        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24459            @Override
24460            public void onCreated(int moveId, Bundle extras) {
24461                // Ignored
24462            }
24463
24464            @Override
24465            public void onStatusChanged(int moveId, int status, long estMillis) {
24466                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24467            }
24468        };
24469
24470        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24471        storage.setPrimaryStorageUuid(volumeUuid, callback);
24472        return realMoveId;
24473    }
24474
24475    @Override
24476    public int getMoveStatus(int moveId) {
24477        mContext.enforceCallingOrSelfPermission(
24478                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24479        return mMoveCallbacks.mLastStatus.get(moveId);
24480    }
24481
24482    @Override
24483    public void registerMoveCallback(IPackageMoveObserver callback) {
24484        mContext.enforceCallingOrSelfPermission(
24485                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24486        mMoveCallbacks.register(callback);
24487    }
24488
24489    @Override
24490    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24491        mContext.enforceCallingOrSelfPermission(
24492                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24493        mMoveCallbacks.unregister(callback);
24494    }
24495
24496    @Override
24497    public boolean setInstallLocation(int loc) {
24498        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24499                null);
24500        if (getInstallLocation() == loc) {
24501            return true;
24502        }
24503        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24504                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24505            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24506                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24507            return true;
24508        }
24509        return false;
24510   }
24511
24512    @Override
24513    public int getInstallLocation() {
24514        // allow instant app access
24515        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24516                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24517                PackageHelper.APP_INSTALL_AUTO);
24518    }
24519
24520    /** Called by UserManagerService */
24521    void cleanUpUser(UserManagerService userManager, int userHandle) {
24522        synchronized (mPackages) {
24523            mDirtyUsers.remove(userHandle);
24524            mUserNeedsBadging.delete(userHandle);
24525            mSettings.removeUserLPw(userHandle);
24526            mPendingBroadcasts.remove(userHandle);
24527            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24528            removeUnusedPackagesLPw(userManager, userHandle);
24529        }
24530    }
24531
24532    /**
24533     * We're removing userHandle and would like to remove any downloaded packages
24534     * that are no longer in use by any other user.
24535     * @param userHandle the user being removed
24536     */
24537    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24538        final boolean DEBUG_CLEAN_APKS = false;
24539        int [] users = userManager.getUserIds();
24540        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24541        while (psit.hasNext()) {
24542            PackageSetting ps = psit.next();
24543            if (ps.pkg == null) {
24544                continue;
24545            }
24546            final String packageName = ps.pkg.packageName;
24547            // Skip over if system app
24548            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24549                continue;
24550            }
24551            if (DEBUG_CLEAN_APKS) {
24552                Slog.i(TAG, "Checking package " + packageName);
24553            }
24554            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24555            if (keep) {
24556                if (DEBUG_CLEAN_APKS) {
24557                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24558                }
24559            } else {
24560                for (int i = 0; i < users.length; i++) {
24561                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24562                        keep = true;
24563                        if (DEBUG_CLEAN_APKS) {
24564                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24565                                    + users[i]);
24566                        }
24567                        break;
24568                    }
24569                }
24570            }
24571            if (!keep) {
24572                if (DEBUG_CLEAN_APKS) {
24573                    Slog.i(TAG, "  Removing package " + packageName);
24574                }
24575                mHandler.post(new Runnable() {
24576                    public void run() {
24577                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24578                                userHandle, 0);
24579                    } //end run
24580                });
24581            }
24582        }
24583    }
24584
24585    /** Called by UserManagerService */
24586    void createNewUser(int userId, String[] disallowedPackages) {
24587        synchronized (mInstallLock) {
24588            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24589        }
24590        synchronized (mPackages) {
24591            scheduleWritePackageRestrictionsLocked(userId);
24592            scheduleWritePackageListLocked(userId);
24593            applyFactoryDefaultBrowserLPw(userId);
24594            primeDomainVerificationsLPw(userId);
24595        }
24596    }
24597
24598    void onNewUserCreated(final int userId) {
24599        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24600        // If permission review for legacy apps is required, we represent
24601        // dagerous permissions for such apps as always granted runtime
24602        // permissions to keep per user flag state whether review is needed.
24603        // Hence, if a new user is added we have to propagate dangerous
24604        // permission grants for these legacy apps.
24605        if (mPermissionReviewRequired) {
24606            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24607                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24608        }
24609    }
24610
24611    @Override
24612    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24613        mContext.enforceCallingOrSelfPermission(
24614                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24615                "Only package verification agents can read the verifier device identity");
24616
24617        synchronized (mPackages) {
24618            return mSettings.getVerifierDeviceIdentityLPw();
24619        }
24620    }
24621
24622    @Override
24623    public void setPermissionEnforced(String permission, boolean enforced) {
24624        // TODO: Now that we no longer change GID for storage, this should to away.
24625        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24626                "setPermissionEnforced");
24627        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24628            synchronized (mPackages) {
24629                if (mSettings.mReadExternalStorageEnforced == null
24630                        || mSettings.mReadExternalStorageEnforced != enforced) {
24631                    mSettings.mReadExternalStorageEnforced = enforced;
24632                    mSettings.writeLPr();
24633                }
24634            }
24635            // kill any non-foreground processes so we restart them and
24636            // grant/revoke the GID.
24637            final IActivityManager am = ActivityManager.getService();
24638            if (am != null) {
24639                final long token = Binder.clearCallingIdentity();
24640                try {
24641                    am.killProcessesBelowForeground("setPermissionEnforcement");
24642                } catch (RemoteException e) {
24643                } finally {
24644                    Binder.restoreCallingIdentity(token);
24645                }
24646            }
24647        } else {
24648            throw new IllegalArgumentException("No selective enforcement for " + permission);
24649        }
24650    }
24651
24652    @Override
24653    @Deprecated
24654    public boolean isPermissionEnforced(String permission) {
24655        // allow instant applications
24656        return true;
24657    }
24658
24659    @Override
24660    public boolean isStorageLow() {
24661        // allow instant applications
24662        final long token = Binder.clearCallingIdentity();
24663        try {
24664            final DeviceStorageMonitorInternal
24665                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24666            if (dsm != null) {
24667                return dsm.isMemoryLow();
24668            } else {
24669                return false;
24670            }
24671        } finally {
24672            Binder.restoreCallingIdentity(token);
24673        }
24674    }
24675
24676    @Override
24677    public IPackageInstaller getPackageInstaller() {
24678        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24679            return null;
24680        }
24681        return mInstallerService;
24682    }
24683
24684    private boolean userNeedsBadging(int userId) {
24685        int index = mUserNeedsBadging.indexOfKey(userId);
24686        if (index < 0) {
24687            final UserInfo userInfo;
24688            final long token = Binder.clearCallingIdentity();
24689            try {
24690                userInfo = sUserManager.getUserInfo(userId);
24691            } finally {
24692                Binder.restoreCallingIdentity(token);
24693            }
24694            final boolean b;
24695            if (userInfo != null && userInfo.isManagedProfile()) {
24696                b = true;
24697            } else {
24698                b = false;
24699            }
24700            mUserNeedsBadging.put(userId, b);
24701            return b;
24702        }
24703        return mUserNeedsBadging.valueAt(index);
24704    }
24705
24706    @Override
24707    public KeySet getKeySetByAlias(String packageName, String alias) {
24708        if (packageName == null || alias == null) {
24709            return null;
24710        }
24711        synchronized(mPackages) {
24712            final PackageParser.Package pkg = mPackages.get(packageName);
24713            if (pkg == null) {
24714                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24715                throw new IllegalArgumentException("Unknown package: " + packageName);
24716            }
24717            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24718            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24719                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24720                throw new IllegalArgumentException("Unknown package: " + packageName);
24721            }
24722            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24723            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24724        }
24725    }
24726
24727    @Override
24728    public KeySet getSigningKeySet(String packageName) {
24729        if (packageName == null) {
24730            return null;
24731        }
24732        synchronized(mPackages) {
24733            final int callingUid = Binder.getCallingUid();
24734            final int callingUserId = UserHandle.getUserId(callingUid);
24735            final PackageParser.Package pkg = mPackages.get(packageName);
24736            if (pkg == null) {
24737                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24738                throw new IllegalArgumentException("Unknown package: " + packageName);
24739            }
24740            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24741            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24742                // filter and pretend the package doesn't exist
24743                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24744                        + ", uid:" + callingUid);
24745                throw new IllegalArgumentException("Unknown package: " + packageName);
24746            }
24747            if (pkg.applicationInfo.uid != callingUid
24748                    && Process.SYSTEM_UID != callingUid) {
24749                throw new SecurityException("May not access signing KeySet of other apps.");
24750            }
24751            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24752            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24753        }
24754    }
24755
24756    @Override
24757    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24758        final int callingUid = Binder.getCallingUid();
24759        if (getInstantAppPackageName(callingUid) != null) {
24760            return false;
24761        }
24762        if (packageName == null || ks == null) {
24763            return false;
24764        }
24765        synchronized(mPackages) {
24766            final PackageParser.Package pkg = mPackages.get(packageName);
24767            if (pkg == null
24768                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24769                            UserHandle.getUserId(callingUid))) {
24770                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24771                throw new IllegalArgumentException("Unknown package: " + packageName);
24772            }
24773            IBinder ksh = ks.getToken();
24774            if (ksh instanceof KeySetHandle) {
24775                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24776                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24777            }
24778            return false;
24779        }
24780    }
24781
24782    @Override
24783    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24784        final int callingUid = Binder.getCallingUid();
24785        if (getInstantAppPackageName(callingUid) != null) {
24786            return false;
24787        }
24788        if (packageName == null || ks == null) {
24789            return false;
24790        }
24791        synchronized(mPackages) {
24792            final PackageParser.Package pkg = mPackages.get(packageName);
24793            if (pkg == null
24794                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24795                            UserHandle.getUserId(callingUid))) {
24796                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24797                throw new IllegalArgumentException("Unknown package: " + packageName);
24798            }
24799            IBinder ksh = ks.getToken();
24800            if (ksh instanceof KeySetHandle) {
24801                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24802                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24803            }
24804            return false;
24805        }
24806    }
24807
24808    private void deletePackageIfUnusedLPr(final String packageName) {
24809        PackageSetting ps = mSettings.mPackages.get(packageName);
24810        if (ps == null) {
24811            return;
24812        }
24813        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24814            // TODO Implement atomic delete if package is unused
24815            // It is currently possible that the package will be deleted even if it is installed
24816            // after this method returns.
24817            mHandler.post(new Runnable() {
24818                public void run() {
24819                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24820                            0, PackageManager.DELETE_ALL_USERS);
24821                }
24822            });
24823        }
24824    }
24825
24826    /**
24827     * Check and throw if the given before/after packages would be considered a
24828     * downgrade.
24829     */
24830    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24831            throws PackageManagerException {
24832        if (after.versionCode < before.mVersionCode) {
24833            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24834                    "Update version code " + after.versionCode + " is older than current "
24835                    + before.mVersionCode);
24836        } else if (after.versionCode == before.mVersionCode) {
24837            if (after.baseRevisionCode < before.baseRevisionCode) {
24838                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24839                        "Update base revision code " + after.baseRevisionCode
24840                        + " is older than current " + before.baseRevisionCode);
24841            }
24842
24843            if (!ArrayUtils.isEmpty(after.splitNames)) {
24844                for (int i = 0; i < after.splitNames.length; i++) {
24845                    final String splitName = after.splitNames[i];
24846                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24847                    if (j != -1) {
24848                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24849                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24850                                    "Update split " + splitName + " revision code "
24851                                    + after.splitRevisionCodes[i] + " is older than current "
24852                                    + before.splitRevisionCodes[j]);
24853                        }
24854                    }
24855                }
24856            }
24857        }
24858    }
24859
24860    private static class MoveCallbacks extends Handler {
24861        private static final int MSG_CREATED = 1;
24862        private static final int MSG_STATUS_CHANGED = 2;
24863
24864        private final RemoteCallbackList<IPackageMoveObserver>
24865                mCallbacks = new RemoteCallbackList<>();
24866
24867        private final SparseIntArray mLastStatus = new SparseIntArray();
24868
24869        public MoveCallbacks(Looper looper) {
24870            super(looper);
24871        }
24872
24873        public void register(IPackageMoveObserver callback) {
24874            mCallbacks.register(callback);
24875        }
24876
24877        public void unregister(IPackageMoveObserver callback) {
24878            mCallbacks.unregister(callback);
24879        }
24880
24881        @Override
24882        public void handleMessage(Message msg) {
24883            final SomeArgs args = (SomeArgs) msg.obj;
24884            final int n = mCallbacks.beginBroadcast();
24885            for (int i = 0; i < n; i++) {
24886                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24887                try {
24888                    invokeCallback(callback, msg.what, args);
24889                } catch (RemoteException ignored) {
24890                }
24891            }
24892            mCallbacks.finishBroadcast();
24893            args.recycle();
24894        }
24895
24896        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24897                throws RemoteException {
24898            switch (what) {
24899                case MSG_CREATED: {
24900                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24901                    break;
24902                }
24903                case MSG_STATUS_CHANGED: {
24904                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24905                    break;
24906                }
24907            }
24908        }
24909
24910        private void notifyCreated(int moveId, Bundle extras) {
24911            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24912
24913            final SomeArgs args = SomeArgs.obtain();
24914            args.argi1 = moveId;
24915            args.arg2 = extras;
24916            obtainMessage(MSG_CREATED, args).sendToTarget();
24917        }
24918
24919        private void notifyStatusChanged(int moveId, int status) {
24920            notifyStatusChanged(moveId, status, -1);
24921        }
24922
24923        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24924            Slog.v(TAG, "Move " + moveId + " status " + status);
24925
24926            final SomeArgs args = SomeArgs.obtain();
24927            args.argi1 = moveId;
24928            args.argi2 = status;
24929            args.arg3 = estMillis;
24930            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24931
24932            synchronized (mLastStatus) {
24933                mLastStatus.put(moveId, status);
24934            }
24935        }
24936    }
24937
24938    private final static class OnPermissionChangeListeners extends Handler {
24939        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24940
24941        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24942                new RemoteCallbackList<>();
24943
24944        public OnPermissionChangeListeners(Looper looper) {
24945            super(looper);
24946        }
24947
24948        @Override
24949        public void handleMessage(Message msg) {
24950            switch (msg.what) {
24951                case MSG_ON_PERMISSIONS_CHANGED: {
24952                    final int uid = msg.arg1;
24953                    handleOnPermissionsChanged(uid);
24954                } break;
24955            }
24956        }
24957
24958        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24959            mPermissionListeners.register(listener);
24960
24961        }
24962
24963        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24964            mPermissionListeners.unregister(listener);
24965        }
24966
24967        public void onPermissionsChanged(int uid) {
24968            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24969                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24970            }
24971        }
24972
24973        private void handleOnPermissionsChanged(int uid) {
24974            final int count = mPermissionListeners.beginBroadcast();
24975            try {
24976                for (int i = 0; i < count; i++) {
24977                    IOnPermissionsChangeListener callback = mPermissionListeners
24978                            .getBroadcastItem(i);
24979                    try {
24980                        callback.onPermissionsChanged(uid);
24981                    } catch (RemoteException e) {
24982                        Log.e(TAG, "Permission listener is dead", e);
24983                    }
24984                }
24985            } finally {
24986                mPermissionListeners.finishBroadcast();
24987            }
24988        }
24989    }
24990
24991    private class PackageManagerNative extends IPackageManagerNative.Stub {
24992        @Override
24993        public String[] getNamesForUids(int[] uids) throws RemoteException {
24994            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24995            // massage results so they can be parsed by the native binder
24996            for (int i = results.length - 1; i >= 0; --i) {
24997                if (results[i] == null) {
24998                    results[i] = "";
24999                }
25000            }
25001            return results;
25002        }
25003    }
25004
25005    private class PackageManagerInternalImpl extends PackageManagerInternal {
25006        @Override
25007        public void setLocationPackagesProvider(PackagesProvider provider) {
25008            synchronized (mPackages) {
25009                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25010            }
25011        }
25012
25013        @Override
25014        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25015            synchronized (mPackages) {
25016                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25017            }
25018        }
25019
25020        @Override
25021        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25022            synchronized (mPackages) {
25023                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25024            }
25025        }
25026
25027        @Override
25028        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25029            synchronized (mPackages) {
25030                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25031            }
25032        }
25033
25034        @Override
25035        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25036            synchronized (mPackages) {
25037                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25038            }
25039        }
25040
25041        @Override
25042        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25043            synchronized (mPackages) {
25044                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25045            }
25046        }
25047
25048        @Override
25049        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25050            synchronized (mPackages) {
25051                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25052                        packageName, userId);
25053            }
25054        }
25055
25056        @Override
25057        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25058            synchronized (mPackages) {
25059                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25060                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25061                        packageName, userId);
25062            }
25063        }
25064
25065        @Override
25066        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25067            synchronized (mPackages) {
25068                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25069                        packageName, userId);
25070            }
25071        }
25072
25073        @Override
25074        public void setKeepUninstalledPackages(final List<String> packageList) {
25075            Preconditions.checkNotNull(packageList);
25076            List<String> removedFromList = null;
25077            synchronized (mPackages) {
25078                if (mKeepUninstalledPackages != null) {
25079                    final int packagesCount = mKeepUninstalledPackages.size();
25080                    for (int i = 0; i < packagesCount; i++) {
25081                        String oldPackage = mKeepUninstalledPackages.get(i);
25082                        if (packageList != null && packageList.contains(oldPackage)) {
25083                            continue;
25084                        }
25085                        if (removedFromList == null) {
25086                            removedFromList = new ArrayList<>();
25087                        }
25088                        removedFromList.add(oldPackage);
25089                    }
25090                }
25091                mKeepUninstalledPackages = new ArrayList<>(packageList);
25092                if (removedFromList != null) {
25093                    final int removedCount = removedFromList.size();
25094                    for (int i = 0; i < removedCount; i++) {
25095                        deletePackageIfUnusedLPr(removedFromList.get(i));
25096                    }
25097                }
25098            }
25099        }
25100
25101        @Override
25102        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25103            synchronized (mPackages) {
25104                // If we do not support permission review, done.
25105                if (!mPermissionReviewRequired) {
25106                    return false;
25107                }
25108
25109                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25110                if (packageSetting == null) {
25111                    return false;
25112                }
25113
25114                // Permission review applies only to apps not supporting the new permission model.
25115                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25116                    return false;
25117                }
25118
25119                // Legacy apps have the permission and get user consent on launch.
25120                PermissionsState permissionsState = packageSetting.getPermissionsState();
25121                return permissionsState.isPermissionReviewRequired(userId);
25122            }
25123        }
25124
25125        @Override
25126        public PackageInfo getPackageInfo(
25127                String packageName, int flags, int filterCallingUid, int userId) {
25128            return PackageManagerService.this
25129                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25130                            flags, filterCallingUid, userId);
25131        }
25132
25133        @Override
25134        public ApplicationInfo getApplicationInfo(
25135                String packageName, int flags, int filterCallingUid, int userId) {
25136            return PackageManagerService.this
25137                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25138        }
25139
25140        @Override
25141        public ActivityInfo getActivityInfo(
25142                ComponentName component, int flags, int filterCallingUid, int userId) {
25143            return PackageManagerService.this
25144                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25145        }
25146
25147        @Override
25148        public List<ResolveInfo> queryIntentActivities(
25149                Intent intent, int flags, int filterCallingUid, int userId) {
25150            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25151            return PackageManagerService.this
25152                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25153                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25154        }
25155
25156        @Override
25157        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25158                int userId) {
25159            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25160        }
25161
25162        @Override
25163        public void setDeviceAndProfileOwnerPackages(
25164                int deviceOwnerUserId, String deviceOwnerPackage,
25165                SparseArray<String> profileOwnerPackages) {
25166            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25167                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25168        }
25169
25170        @Override
25171        public boolean isPackageDataProtected(int userId, String packageName) {
25172            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25173        }
25174
25175        @Override
25176        public boolean isPackageEphemeral(int userId, String packageName) {
25177            synchronized (mPackages) {
25178                final PackageSetting ps = mSettings.mPackages.get(packageName);
25179                return ps != null ? ps.getInstantApp(userId) : false;
25180            }
25181        }
25182
25183        @Override
25184        public boolean wasPackageEverLaunched(String packageName, int userId) {
25185            synchronized (mPackages) {
25186                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25187            }
25188        }
25189
25190        @Override
25191        public void grantRuntimePermission(String packageName, String name, int userId,
25192                boolean overridePolicy) {
25193            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25194                    overridePolicy);
25195        }
25196
25197        @Override
25198        public void revokeRuntimePermission(String packageName, String name, int userId,
25199                boolean overridePolicy) {
25200            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25201                    overridePolicy);
25202        }
25203
25204        @Override
25205        public String getNameForUid(int uid) {
25206            return PackageManagerService.this.getNameForUid(uid);
25207        }
25208
25209        @Override
25210        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25211                Intent origIntent, String resolvedType, String callingPackage,
25212                Bundle verificationBundle, int userId) {
25213            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25214                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25215                    userId);
25216        }
25217
25218        @Override
25219        public void grantEphemeralAccess(int userId, Intent intent,
25220                int targetAppId, int ephemeralAppId) {
25221            synchronized (mPackages) {
25222                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25223                        targetAppId, ephemeralAppId);
25224            }
25225        }
25226
25227        @Override
25228        public boolean isInstantAppInstallerComponent(ComponentName component) {
25229            synchronized (mPackages) {
25230                return mInstantAppInstallerActivity != null
25231                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25232            }
25233        }
25234
25235        @Override
25236        public void pruneInstantApps() {
25237            mInstantAppRegistry.pruneInstantApps();
25238        }
25239
25240        @Override
25241        public String getSetupWizardPackageName() {
25242            return mSetupWizardPackage;
25243        }
25244
25245        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25246            if (policy != null) {
25247                mExternalSourcesPolicy = policy;
25248            }
25249        }
25250
25251        @Override
25252        public boolean isPackagePersistent(String packageName) {
25253            synchronized (mPackages) {
25254                PackageParser.Package pkg = mPackages.get(packageName);
25255                return pkg != null
25256                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25257                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25258                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25259                        : false;
25260            }
25261        }
25262
25263        @Override
25264        public List<PackageInfo> getOverlayPackages(int userId) {
25265            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25266            synchronized (mPackages) {
25267                for (PackageParser.Package p : mPackages.values()) {
25268                    if (p.mOverlayTarget != null) {
25269                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25270                        if (pkg != null) {
25271                            overlayPackages.add(pkg);
25272                        }
25273                    }
25274                }
25275            }
25276            return overlayPackages;
25277        }
25278
25279        @Override
25280        public List<String> getTargetPackageNames(int userId) {
25281            List<String> targetPackages = new ArrayList<>();
25282            synchronized (mPackages) {
25283                for (PackageParser.Package p : mPackages.values()) {
25284                    if (p.mOverlayTarget == null) {
25285                        targetPackages.add(p.packageName);
25286                    }
25287                }
25288            }
25289            return targetPackages;
25290        }
25291
25292        @Override
25293        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25294                @Nullable List<String> overlayPackageNames) {
25295            synchronized (mPackages) {
25296                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25297                    Slog.e(TAG, "failed to find package " + targetPackageName);
25298                    return false;
25299                }
25300                ArrayList<String> overlayPaths = null;
25301                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25302                    final int N = overlayPackageNames.size();
25303                    overlayPaths = new ArrayList<>(N);
25304                    for (int i = 0; i < N; i++) {
25305                        final String packageName = overlayPackageNames.get(i);
25306                        final PackageParser.Package pkg = mPackages.get(packageName);
25307                        if (pkg == null) {
25308                            Slog.e(TAG, "failed to find package " + packageName);
25309                            return false;
25310                        }
25311                        overlayPaths.add(pkg.baseCodePath);
25312                    }
25313                }
25314
25315                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25316                ps.setOverlayPaths(overlayPaths, userId);
25317                return true;
25318            }
25319        }
25320
25321        @Override
25322        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25323                int flags, int userId) {
25324            return resolveIntentInternal(
25325                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25326        }
25327
25328        @Override
25329        public ResolveInfo resolveService(Intent intent, String resolvedType,
25330                int flags, int userId, int callingUid) {
25331            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25332        }
25333
25334        @Override
25335        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25336            synchronized (mPackages) {
25337                mIsolatedOwners.put(isolatedUid, ownerUid);
25338            }
25339        }
25340
25341        @Override
25342        public void removeIsolatedUid(int isolatedUid) {
25343            synchronized (mPackages) {
25344                mIsolatedOwners.delete(isolatedUid);
25345            }
25346        }
25347
25348        @Override
25349        public int getUidTargetSdkVersion(int uid) {
25350            synchronized (mPackages) {
25351                return getUidTargetSdkVersionLockedLPr(uid);
25352            }
25353        }
25354
25355        @Override
25356        public boolean canAccessInstantApps(int callingUid, int userId) {
25357            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25358        }
25359    }
25360
25361    @Override
25362    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25363        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25364        synchronized (mPackages) {
25365            final long identity = Binder.clearCallingIdentity();
25366            try {
25367                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25368                        packageNames, userId);
25369            } finally {
25370                Binder.restoreCallingIdentity(identity);
25371            }
25372        }
25373    }
25374
25375    @Override
25376    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25377        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25378        synchronized (mPackages) {
25379            final long identity = Binder.clearCallingIdentity();
25380            try {
25381                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25382                        packageNames, userId);
25383            } finally {
25384                Binder.restoreCallingIdentity(identity);
25385            }
25386        }
25387    }
25388
25389    private static void enforceSystemOrPhoneCaller(String tag) {
25390        int callingUid = Binder.getCallingUid();
25391        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25392            throw new SecurityException(
25393                    "Cannot call " + tag + " from UID " + callingUid);
25394        }
25395    }
25396
25397    boolean isHistoricalPackageUsageAvailable() {
25398        return mPackageUsage.isHistoricalPackageUsageAvailable();
25399    }
25400
25401    /**
25402     * Return a <b>copy</b> of the collection of packages known to the package manager.
25403     * @return A copy of the values of mPackages.
25404     */
25405    Collection<PackageParser.Package> getPackages() {
25406        synchronized (mPackages) {
25407            return new ArrayList<>(mPackages.values());
25408        }
25409    }
25410
25411    /**
25412     * Logs process start information (including base APK hash) to the security log.
25413     * @hide
25414     */
25415    @Override
25416    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25417            String apkFile, int pid) {
25418        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25419            return;
25420        }
25421        if (!SecurityLog.isLoggingEnabled()) {
25422            return;
25423        }
25424        Bundle data = new Bundle();
25425        data.putLong("startTimestamp", System.currentTimeMillis());
25426        data.putString("processName", processName);
25427        data.putInt("uid", uid);
25428        data.putString("seinfo", seinfo);
25429        data.putString("apkFile", apkFile);
25430        data.putInt("pid", pid);
25431        Message msg = mProcessLoggingHandler.obtainMessage(
25432                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25433        msg.setData(data);
25434        mProcessLoggingHandler.sendMessage(msg);
25435    }
25436
25437    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25438        return mCompilerStats.getPackageStats(pkgName);
25439    }
25440
25441    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25442        return getOrCreateCompilerPackageStats(pkg.packageName);
25443    }
25444
25445    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25446        return mCompilerStats.getOrCreatePackageStats(pkgName);
25447    }
25448
25449    public void deleteCompilerPackageStats(String pkgName) {
25450        mCompilerStats.deletePackageStats(pkgName);
25451    }
25452
25453    @Override
25454    public int getInstallReason(String packageName, int userId) {
25455        final int callingUid = Binder.getCallingUid();
25456        enforceCrossUserPermission(callingUid, userId,
25457                true /* requireFullPermission */, false /* checkShell */,
25458                "get install reason");
25459        synchronized (mPackages) {
25460            final PackageSetting ps = mSettings.mPackages.get(packageName);
25461            if (filterAppAccessLPr(ps, callingUid, userId)) {
25462                return PackageManager.INSTALL_REASON_UNKNOWN;
25463            }
25464            if (ps != null) {
25465                return ps.getInstallReason(userId);
25466            }
25467        }
25468        return PackageManager.INSTALL_REASON_UNKNOWN;
25469    }
25470
25471    @Override
25472    public boolean canRequestPackageInstalls(String packageName, int userId) {
25473        return canRequestPackageInstallsInternal(packageName, 0, userId,
25474                true /* throwIfPermNotDeclared*/);
25475    }
25476
25477    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25478            boolean throwIfPermNotDeclared) {
25479        int callingUid = Binder.getCallingUid();
25480        int uid = getPackageUid(packageName, 0, userId);
25481        if (callingUid != uid && callingUid != Process.ROOT_UID
25482                && callingUid != Process.SYSTEM_UID) {
25483            throw new SecurityException(
25484                    "Caller uid " + callingUid + " does not own package " + packageName);
25485        }
25486        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25487        if (info == null) {
25488            return false;
25489        }
25490        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25491            return false;
25492        }
25493        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25494        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25495        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25496            if (throwIfPermNotDeclared) {
25497                throw new SecurityException("Need to declare " + appOpPermission
25498                        + " to call this api");
25499            } else {
25500                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25501                return false;
25502            }
25503        }
25504        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25505            return false;
25506        }
25507        if (mExternalSourcesPolicy != null) {
25508            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25509            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25510                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25511            }
25512        }
25513        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25514    }
25515
25516    @Override
25517    public ComponentName getInstantAppResolverSettingsComponent() {
25518        return mInstantAppResolverSettingsComponent;
25519    }
25520
25521    @Override
25522    public ComponentName getInstantAppInstallerComponent() {
25523        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25524            return null;
25525        }
25526        return mInstantAppInstallerActivity == null
25527                ? null : mInstantAppInstallerActivity.getComponentName();
25528    }
25529
25530    @Override
25531    public String getInstantAppAndroidId(String packageName, int userId) {
25532        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25533                "getInstantAppAndroidId");
25534        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25535                true /* requireFullPermission */, false /* checkShell */,
25536                "getInstantAppAndroidId");
25537        // Make sure the target is an Instant App.
25538        if (!isInstantApp(packageName, userId)) {
25539            return null;
25540        }
25541        synchronized (mPackages) {
25542            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25543        }
25544    }
25545
25546    boolean canHaveOatDir(String packageName) {
25547        synchronized (mPackages) {
25548            PackageParser.Package p = mPackages.get(packageName);
25549            if (p == null) {
25550                return false;
25551            }
25552            return p.canHaveOatDir();
25553        }
25554    }
25555
25556    private String getOatDir(PackageParser.Package pkg) {
25557        if (!pkg.canHaveOatDir()) {
25558            return null;
25559        }
25560        File codePath = new File(pkg.codePath);
25561        if (codePath.isDirectory()) {
25562            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25563        }
25564        return null;
25565    }
25566
25567    void deleteOatArtifactsOfPackage(String packageName) {
25568        final String[] instructionSets;
25569        final List<String> codePaths;
25570        final String oatDir;
25571        final PackageParser.Package pkg;
25572        synchronized (mPackages) {
25573            pkg = mPackages.get(packageName);
25574        }
25575        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25576        codePaths = pkg.getAllCodePaths();
25577        oatDir = getOatDir(pkg);
25578
25579        for (String codePath : codePaths) {
25580            for (String isa : instructionSets) {
25581                try {
25582                    mInstaller.deleteOdex(codePath, isa, oatDir);
25583                } catch (InstallerException e) {
25584                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25585                }
25586            }
25587        }
25588    }
25589
25590    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25591        Set<String> unusedPackages = new HashSet<>();
25592        long currentTimeInMillis = System.currentTimeMillis();
25593        synchronized (mPackages) {
25594            for (PackageParser.Package pkg : mPackages.values()) {
25595                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25596                if (ps == null) {
25597                    continue;
25598                }
25599                PackageDexUsage.PackageUseInfo packageUseInfo =
25600                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25601                if (PackageManagerServiceUtils
25602                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25603                                downgradeTimeThresholdMillis, packageUseInfo,
25604                                pkg.getLatestPackageUseTimeInMills(),
25605                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25606                    unusedPackages.add(pkg.packageName);
25607                }
25608            }
25609        }
25610        return unusedPackages;
25611    }
25612}
25613
25614interface PackageSender {
25615    void sendPackageBroadcast(final String action, final String pkg,
25616        final Bundle extras, final int flags, final String targetPkg,
25617        final IIntentReceiver finishedReceiver, final int[] userIds);
25618    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25619        boolean includeStopped, int appId, int... userIds);
25620}
25621