PackageManagerService.java revision 747613f1fce72792a0e39395ea63bee483052169
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.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.storage.DeviceStorageMonitorInternal;
287
288import dalvik.system.CloseGuard;
289import dalvik.system.DexFile;
290import dalvik.system.VMRuntime;
291
292import libcore.io.IoUtils;
293import libcore.util.EmptyArray;
294
295import org.xmlpull.v1.XmlPullParser;
296import org.xmlpull.v1.XmlPullParserException;
297import org.xmlpull.v1.XmlSerializer;
298
299import java.io.BufferedOutputStream;
300import java.io.BufferedReader;
301import java.io.ByteArrayInputStream;
302import java.io.ByteArrayOutputStream;
303import java.io.File;
304import java.io.FileDescriptor;
305import java.io.FileInputStream;
306import java.io.FileOutputStream;
307import java.io.FileReader;
308import java.io.FilenameFilter;
309import java.io.IOException;
310import java.io.PrintWriter;
311import java.lang.annotation.Retention;
312import java.lang.annotation.RetentionPolicy;
313import java.nio.charset.StandardCharsets;
314import java.security.DigestInputStream;
315import java.security.MessageDigest;
316import java.security.NoSuchAlgorithmException;
317import java.security.PublicKey;
318import java.security.SecureRandom;
319import java.security.cert.Certificate;
320import java.security.cert.CertificateEncodingException;
321import java.security.cert.CertificateException;
322import java.text.SimpleDateFormat;
323import java.util.ArrayList;
324import java.util.Arrays;
325import java.util.Collection;
326import java.util.Collections;
327import java.util.Comparator;
328import java.util.Date;
329import java.util.HashMap;
330import java.util.HashSet;
331import java.util.Iterator;
332import java.util.List;
333import java.util.Map;
334import java.util.Objects;
335import java.util.Set;
336import java.util.concurrent.CountDownLatch;
337import java.util.concurrent.Future;
338import java.util.concurrent.TimeUnit;
339import java.util.concurrent.atomic.AtomicBoolean;
340import java.util.concurrent.atomic.AtomicInteger;
341
342/**
343 * Keep track of all those APKs everywhere.
344 * <p>
345 * Internally there are two important locks:
346 * <ul>
347 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
348 * and other related state. It is a fine-grained lock that should only be held
349 * momentarily, as it's one of the most contended locks in the system.
350 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
351 * operations typically involve heavy lifting of application data on disk. Since
352 * {@code installd} is single-threaded, and it's operations can often be slow,
353 * this lock should never be acquired while already holding {@link #mPackages}.
354 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
355 * holding {@link #mInstallLock}.
356 * </ul>
357 * Many internal methods rely on the caller to hold the appropriate locks, and
358 * this contract is expressed through method name suffixes:
359 * <ul>
360 * <li>fooLI(): the caller must hold {@link #mInstallLock}
361 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
362 * being modified must be frozen
363 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
364 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
365 * </ul>
366 * <p>
367 * Because this class is very central to the platform's security; please run all
368 * CTS and unit tests whenever making modifications:
369 *
370 * <pre>
371 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
372 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
373 * </pre>
374 */
375public class PackageManagerService extends IPackageManager.Stub
376        implements PackageSender {
377    static final String TAG = "PackageManager";
378    static final boolean DEBUG_SETTINGS = false;
379    static final boolean DEBUG_PREFERRED = false;
380    static final boolean DEBUG_UPGRADE = false;
381    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
382    private static final boolean DEBUG_BACKUP = false;
383    private static final boolean DEBUG_INSTALL = false;
384    private static final boolean DEBUG_REMOVE = false;
385    private static final boolean DEBUG_BROADCASTS = false;
386    private static final boolean DEBUG_SHOW_INFO = false;
387    private static final boolean DEBUG_PACKAGE_INFO = false;
388    private static final boolean DEBUG_INTENT_MATCHING = false;
389    private static final boolean DEBUG_PACKAGE_SCANNING = false;
390    private static final boolean DEBUG_VERIFY = false;
391    private static final boolean DEBUG_FILTERS = false;
392    private static final boolean DEBUG_PERMISSIONS = false;
393    private static final boolean DEBUG_SHARED_LIBRARIES = false;
394
395    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
396    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
397    // user, but by default initialize to this.
398    public static final boolean DEBUG_DEXOPT = false;
399
400    private static final boolean DEBUG_ABI_SELECTION = false;
401    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
402    private static final boolean DEBUG_TRIAGED_MISSING = false;
403    private static final boolean DEBUG_APP_DATA = false;
404
405    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
406    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
407
408    private static final boolean HIDE_EPHEMERAL_APIS = false;
409
410    private static final boolean ENABLE_FREE_CACHE_V2 =
411            SystemProperties.getBoolean("fw.free_cache_v2", true);
412
413    private static final int RADIO_UID = Process.PHONE_UID;
414    private static final int LOG_UID = Process.LOG_UID;
415    private static final int NFC_UID = Process.NFC_UID;
416    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
417    private static final int SHELL_UID = Process.SHELL_UID;
418
419    // Cap the size of permission trees that 3rd party apps can define
420    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
421
422    // Suffix used during package installation when copying/moving
423    // package apks to install directory.
424    private static final String INSTALL_PACKAGE_SUFFIX = "-";
425
426    static final int SCAN_NO_DEX = 1<<1;
427    static final int SCAN_FORCE_DEX = 1<<2;
428    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
429    static final int SCAN_NEW_INSTALL = 1<<4;
430    static final int SCAN_UPDATE_TIME = 1<<5;
431    static final int SCAN_BOOTING = 1<<6;
432    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
433    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
434    static final int SCAN_REPLACING = 1<<9;
435    static final int SCAN_REQUIRE_KNOWN = 1<<10;
436    static final int SCAN_MOVE = 1<<11;
437    static final int SCAN_INITIAL = 1<<12;
438    static final int SCAN_CHECK_ONLY = 1<<13;
439    static final int SCAN_DONT_KILL_APP = 1<<14;
440    static final int SCAN_IGNORE_FROZEN = 1<<15;
441    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
442    static final int SCAN_AS_INSTANT_APP = 1<<17;
443    static final int SCAN_AS_FULL_APP = 1<<18;
444    /** Should not be with the scan flags */
445    static final int FLAGS_REMOVE_CHATTY = 1<<31;
446
447    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
448
449    private static final int[] EMPTY_INT_ARRAY = new int[0];
450
451    private static final int TYPE_UNKNOWN = 0;
452    private static final int TYPE_ACTIVITY = 1;
453    private static final int TYPE_RECEIVER = 2;
454    private static final int TYPE_SERVICE = 3;
455    private static final int TYPE_PROVIDER = 4;
456    @IntDef(prefix = { "TYPE_" }, value = {
457            TYPE_UNKNOWN,
458            TYPE_ACTIVITY,
459            TYPE_RECEIVER,
460            TYPE_SERVICE,
461            TYPE_PROVIDER,
462    })
463    @Retention(RetentionPolicy.SOURCE)
464    public @interface ComponentType {}
465
466    /**
467     * Timeout (in milliseconds) after which the watchdog should declare that
468     * our handler thread is wedged.  The usual default for such things is one
469     * minute but we sometimes do very lengthy I/O operations on this thread,
470     * such as installing multi-gigabyte applications, so ours needs to be longer.
471     */
472    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
473
474    /**
475     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
476     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
477     * settings entry if available, otherwise we use the hardcoded default.  If it's been
478     * more than this long since the last fstrim, we force one during the boot sequence.
479     *
480     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
481     * one gets run at the next available charging+idle time.  This final mandatory
482     * no-fstrim check kicks in only of the other scheduling criteria is never met.
483     */
484    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
485
486    /**
487     * Whether verification is enabled by default.
488     */
489    private static final boolean DEFAULT_VERIFY_ENABLE = true;
490
491    /**
492     * The default maximum time to wait for the verification agent to return in
493     * milliseconds.
494     */
495    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
496
497    /**
498     * The default response for package verification timeout.
499     *
500     * This can be either PackageManager.VERIFICATION_ALLOW or
501     * PackageManager.VERIFICATION_REJECT.
502     */
503    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
504
505    static final String PLATFORM_PACKAGE_NAME = "android";
506
507    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
508
509    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
510            DEFAULT_CONTAINER_PACKAGE,
511            "com.android.defcontainer.DefaultContainerService");
512
513    private static final String KILL_APP_REASON_GIDS_CHANGED =
514            "permission grant or revoke changed gids";
515
516    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
517            "permissions revoked";
518
519    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
520
521    private static final String PACKAGE_SCHEME = "package";
522
523    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
524
525    /** Permission grant: not grant the permission. */
526    private static final int GRANT_DENIED = 1;
527
528    /** Permission grant: grant the permission as an install permission. */
529    private static final int GRANT_INSTALL = 2;
530
531    /** Permission grant: grant the permission as a runtime one. */
532    private static final int GRANT_RUNTIME = 3;
533
534    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
535    private static final int GRANT_UPGRADE = 4;
536
537    /** Canonical intent used to identify what counts as a "web browser" app */
538    private static final Intent sBrowserIntent;
539    static {
540        sBrowserIntent = new Intent();
541        sBrowserIntent.setAction(Intent.ACTION_VIEW);
542        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
543        sBrowserIntent.setData(Uri.parse("http:"));
544    }
545
546    /**
547     * The set of all protected actions [i.e. those actions for which a high priority
548     * intent filter is disallowed].
549     */
550    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
551    static {
552        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
555        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
556    }
557
558    // Compilation reasons.
559    public static final int REASON_FIRST_BOOT = 0;
560    public static final int REASON_BOOT = 1;
561    public static final int REASON_INSTALL = 2;
562    public static final int REASON_BACKGROUND_DEXOPT = 3;
563    public static final int REASON_AB_OTA = 4;
564
565    public static final int REASON_LAST = REASON_AB_OTA;
566
567    /** All dangerous permission names in the same order as the events in MetricsEvent */
568    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
569            Manifest.permission.READ_CALENDAR,
570            Manifest.permission.WRITE_CALENDAR,
571            Manifest.permission.CAMERA,
572            Manifest.permission.READ_CONTACTS,
573            Manifest.permission.WRITE_CONTACTS,
574            Manifest.permission.GET_ACCOUNTS,
575            Manifest.permission.ACCESS_FINE_LOCATION,
576            Manifest.permission.ACCESS_COARSE_LOCATION,
577            Manifest.permission.RECORD_AUDIO,
578            Manifest.permission.READ_PHONE_STATE,
579            Manifest.permission.CALL_PHONE,
580            Manifest.permission.READ_CALL_LOG,
581            Manifest.permission.WRITE_CALL_LOG,
582            Manifest.permission.ADD_VOICEMAIL,
583            Manifest.permission.USE_SIP,
584            Manifest.permission.PROCESS_OUTGOING_CALLS,
585            Manifest.permission.READ_CELL_BROADCASTS,
586            Manifest.permission.BODY_SENSORS,
587            Manifest.permission.SEND_SMS,
588            Manifest.permission.RECEIVE_SMS,
589            Manifest.permission.READ_SMS,
590            Manifest.permission.RECEIVE_WAP_PUSH,
591            Manifest.permission.RECEIVE_MMS,
592            Manifest.permission.READ_EXTERNAL_STORAGE,
593            Manifest.permission.WRITE_EXTERNAL_STORAGE,
594            Manifest.permission.READ_PHONE_NUMBERS,
595            Manifest.permission.ANSWER_PHONE_CALLS);
596
597
598    /**
599     * Version number for the package parser cache. Increment this whenever the format or
600     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
601     */
602    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
603
604    /**
605     * Whether the package parser cache is enabled.
606     */
607    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
608
609    final ServiceThread mHandlerThread;
610
611    final PackageHandler mHandler;
612
613    private final ProcessLoggingHandler mProcessLoggingHandler;
614
615    /**
616     * Messages for {@link #mHandler} that need to wait for system ready before
617     * being dispatched.
618     */
619    private ArrayList<Message> mPostSystemReadyMessages;
620
621    final int mSdkVersion = Build.VERSION.SDK_INT;
622
623    final Context mContext;
624    final boolean mFactoryTest;
625    final boolean mOnlyCore;
626    final DisplayMetrics mMetrics;
627    final int mDefParseFlags;
628    final String[] mSeparateProcesses;
629    final boolean mIsUpgrade;
630    final boolean mIsPreNUpgrade;
631    final boolean mIsPreNMR1Upgrade;
632
633    // Have we told the Activity Manager to whitelist the default container service by uid yet?
634    @GuardedBy("mPackages")
635    boolean mDefaultContainerWhitelisted = false;
636
637    @GuardedBy("mPackages")
638    private boolean mDexOptDialogShown;
639
640    /** The location for ASEC container files on internal storage. */
641    final String mAsecInternalPath;
642
643    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
644    // LOCK HELD.  Can be called with mInstallLock held.
645    @GuardedBy("mInstallLock")
646    final Installer mInstaller;
647
648    /** Directory where installed third-party apps stored */
649    final File mAppInstallDir;
650
651    /**
652     * Directory to which applications installed internally have their
653     * 32 bit native libraries copied.
654     */
655    private File mAppLib32InstallDir;
656
657    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
658    // apps.
659    final File mDrmAppPrivateInstallDir;
660
661    // ----------------------------------------------------------------
662
663    // Lock for state used when installing and doing other long running
664    // operations.  Methods that must be called with this lock held have
665    // the suffix "LI".
666    final Object mInstallLock = new Object();
667
668    // ----------------------------------------------------------------
669
670    // Keys are String (package name), values are Package.  This also serves
671    // as the lock for the global state.  Methods that must be called with
672    // this lock held have the prefix "LP".
673    @GuardedBy("mPackages")
674    final ArrayMap<String, PackageParser.Package> mPackages =
675            new ArrayMap<String, PackageParser.Package>();
676
677    final ArrayMap<String, Set<String>> mKnownCodebase =
678            new ArrayMap<String, Set<String>>();
679
680    // Keys are isolated uids and values are the uid of the application
681    // that created the isolated proccess.
682    @GuardedBy("mPackages")
683    final SparseIntArray mIsolatedOwners = new SparseIntArray();
684
685    /**
686     * Tracks new system packages [received in an OTA] that we expect to
687     * find updated user-installed versions. Keys are package name, values
688     * are package location.
689     */
690    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
691    /**
692     * Tracks high priority intent filters for protected actions. During boot, certain
693     * filter actions are protected and should never be allowed to have a high priority
694     * intent filter for them. However, there is one, and only one exception -- the
695     * setup wizard. It must be able to define a high priority intent filter for these
696     * actions to ensure there are no escapes from the wizard. We need to delay processing
697     * of these during boot as we need to look at all of the system packages in order
698     * to know which component is the setup wizard.
699     */
700    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
701    /**
702     * Whether or not processing protected filters should be deferred.
703     */
704    private boolean mDeferProtectedFilters = true;
705
706    /**
707     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
708     */
709    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
710    /**
711     * Whether or not system app permissions should be promoted from install to runtime.
712     */
713    boolean mPromoteSystemApps;
714
715    @GuardedBy("mPackages")
716    final Settings mSettings;
717
718    /**
719     * Set of package names that are currently "frozen", which means active
720     * surgery is being done on the code/data for that package. The platform
721     * will refuse to launch frozen packages to avoid race conditions.
722     *
723     * @see PackageFreezer
724     */
725    @GuardedBy("mPackages")
726    final ArraySet<String> mFrozenPackages = new ArraySet<>();
727
728    final ProtectedPackages mProtectedPackages;
729
730    @GuardedBy("mLoadedVolumes")
731    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
732
733    boolean mFirstBoot;
734
735    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
736
737    // System configuration read by SystemConfig.
738    final int[] mGlobalGids;
739    final SparseArray<ArraySet<String>> mSystemPermissions;
740    @GuardedBy("mAvailableFeatures")
741    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
742
743    // If mac_permissions.xml was found for seinfo labeling.
744    boolean mFoundPolicyFile;
745
746    private final InstantAppRegistry mInstantAppRegistry;
747
748    @GuardedBy("mPackages")
749    int mChangedPackagesSequenceNumber;
750    /**
751     * List of changed [installed, removed or updated] packages.
752     * mapping from user id -> sequence number -> package name
753     */
754    @GuardedBy("mPackages")
755    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
756    /**
757     * The sequence number of the last change to a package.
758     * mapping from user id -> package name -> sequence number
759     */
760    @GuardedBy("mPackages")
761    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
762
763    class PackageParserCallback implements PackageParser.Callback {
764        @Override public final boolean hasFeature(String feature) {
765            return PackageManagerService.this.hasSystemFeature(feature, 0);
766        }
767
768        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
769                Collection<PackageParser.Package> allPackages, String targetPackageName) {
770            List<PackageParser.Package> overlayPackages = null;
771            for (PackageParser.Package p : allPackages) {
772                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
773                    if (overlayPackages == null) {
774                        overlayPackages = new ArrayList<PackageParser.Package>();
775                    }
776                    overlayPackages.add(p);
777                }
778            }
779            if (overlayPackages != null) {
780                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
781                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
782                        return p1.mOverlayPriority - p2.mOverlayPriority;
783                    }
784                };
785                Collections.sort(overlayPackages, cmp);
786            }
787            return overlayPackages;
788        }
789
790        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
791                String targetPackageName, String targetPath) {
792            if ("android".equals(targetPackageName)) {
793                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
794                // native AssetManager.
795                return null;
796            }
797            List<PackageParser.Package> overlayPackages =
798                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
799            if (overlayPackages == null || overlayPackages.isEmpty()) {
800                return null;
801            }
802            List<String> overlayPathList = null;
803            for (PackageParser.Package overlayPackage : overlayPackages) {
804                if (targetPath == null) {
805                    if (overlayPathList == null) {
806                        overlayPathList = new ArrayList<String>();
807                    }
808                    overlayPathList.add(overlayPackage.baseCodePath);
809                    continue;
810                }
811
812                try {
813                    // Creates idmaps for system to parse correctly the Android manifest of the
814                    // target package.
815                    //
816                    // OverlayManagerService will update each of them with a correct gid from its
817                    // target package app id.
818                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
819                            UserHandle.getSharedAppGid(
820                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                } catch (InstallerException e) {
826                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
827                            overlayPackage.baseCodePath);
828                }
829            }
830            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
831        }
832
833        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
834            synchronized (mPackages) {
835                return getStaticOverlayPathsLocked(
836                        mPackages.values(), targetPackageName, targetPath);
837            }
838        }
839
840        @Override public final String[] getOverlayApks(String targetPackageName) {
841            return getStaticOverlayPaths(targetPackageName, null);
842        }
843
844        @Override public final String[] getOverlayPaths(String targetPackageName,
845                String targetPath) {
846            return getStaticOverlayPaths(targetPackageName, targetPath);
847        }
848    };
849
850    class ParallelPackageParserCallback extends PackageParserCallback {
851        List<PackageParser.Package> mOverlayPackages = null;
852
853        void findStaticOverlayPackages() {
854            synchronized (mPackages) {
855                for (PackageParser.Package p : mPackages.values()) {
856                    if (p.mIsStaticOverlay) {
857                        if (mOverlayPackages == null) {
858                            mOverlayPackages = new ArrayList<PackageParser.Package>();
859                        }
860                        mOverlayPackages.add(p);
861                    }
862                }
863            }
864        }
865
866        @Override
867        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
868            // We can trust mOverlayPackages without holding mPackages because package uninstall
869            // can't happen while running parallel parsing.
870            // Moreover holding mPackages on each parsing thread causes dead-lock.
871            return mOverlayPackages == null ? null :
872                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
873        }
874    }
875
876    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
877    final ParallelPackageParserCallback mParallelPackageParserCallback =
878            new ParallelPackageParserCallback();
879
880    public static final class SharedLibraryEntry {
881        public final @Nullable String path;
882        public final @Nullable String apk;
883        public final @NonNull SharedLibraryInfo info;
884
885        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
886                String declaringPackageName, int declaringPackageVersionCode) {
887            path = _path;
888            apk = _apk;
889            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
890                    declaringPackageName, declaringPackageVersionCode), null);
891        }
892    }
893
894    // Currently known shared libraries.
895    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
896    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
897            new ArrayMap<>();
898
899    // All available activities, for your resolving pleasure.
900    final ActivityIntentResolver mActivities =
901            new ActivityIntentResolver();
902
903    // All available receivers, for your resolving pleasure.
904    final ActivityIntentResolver mReceivers =
905            new ActivityIntentResolver();
906
907    // All available services, for your resolving pleasure.
908    final ServiceIntentResolver mServices = new ServiceIntentResolver();
909
910    // All available providers, for your resolving pleasure.
911    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
912
913    // Mapping from provider base names (first directory in content URI codePath)
914    // to the provider information.
915    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
916            new ArrayMap<String, PackageParser.Provider>();
917
918    // Mapping from instrumentation class names to info about them.
919    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
920            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
921
922    // Mapping from permission names to info about them.
923    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
924            new ArrayMap<String, PackageParser.PermissionGroup>();
925
926    // Packages whose data we have transfered into another package, thus
927    // should no longer exist.
928    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
929
930    // Broadcast actions that are only available to the system.
931    @GuardedBy("mProtectedBroadcasts")
932    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
933
934    /** List of packages waiting for verification. */
935    final SparseArray<PackageVerificationState> mPendingVerification
936            = new SparseArray<PackageVerificationState>();
937
938    /** Set of packages associated with each app op permission. */
939    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
940
941    final PackageInstallerService mInstallerService;
942
943    private final PackageDexOptimizer mPackageDexOptimizer;
944    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
945    // is used by other apps).
946    private final DexManager mDexManager;
947
948    private AtomicInteger mNextMoveId = new AtomicInteger();
949    private final MoveCallbacks mMoveCallbacks;
950
951    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
952
953    // Cache of users who need badging.
954    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
955
956    /** Token for keys in mPendingVerification. */
957    private int mPendingVerificationToken = 0;
958
959    volatile boolean mSystemReady;
960    volatile boolean mSafeMode;
961    volatile boolean mHasSystemUidErrors;
962    private volatile boolean mEphemeralAppsDisabled;
963
964    ApplicationInfo mAndroidApplication;
965    final ActivityInfo mResolveActivity = new ActivityInfo();
966    final ResolveInfo mResolveInfo = new ResolveInfo();
967    ComponentName mResolveComponentName;
968    PackageParser.Package mPlatformPackage;
969    ComponentName mCustomResolverComponentName;
970
971    boolean mResolverReplaced = false;
972
973    private final @Nullable ComponentName mIntentFilterVerifierComponent;
974    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
975
976    private int mIntentFilterVerificationToken = 0;
977
978    /** The service connection to the ephemeral resolver */
979    final EphemeralResolverConnection mInstantAppResolverConnection;
980    /** Component used to show resolver settings for Instant Apps */
981    final ComponentName mInstantAppResolverSettingsComponent;
982
983    /** Activity used to install instant applications */
984    ActivityInfo mInstantAppInstallerActivity;
985    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
986
987    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
988            = new SparseArray<IntentFilterVerificationState>();
989
990    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
991
992    // List of packages names to keep cached, even if they are uninstalled for all users
993    private List<String> mKeepUninstalledPackages;
994
995    private UserManagerInternal mUserManagerInternal;
996
997    private DeviceIdleController.LocalService mDeviceIdleController;
998
999    private File mCacheDir;
1000
1001    private ArraySet<String> mPrivappPermissionsViolations;
1002
1003    private Future<?> mPrepareAppDataFuture;
1004
1005    private static class IFVerificationParams {
1006        PackageParser.Package pkg;
1007        boolean replacing;
1008        int userId;
1009        int verifierUid;
1010
1011        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1012                int _userId, int _verifierUid) {
1013            pkg = _pkg;
1014            replacing = _replacing;
1015            userId = _userId;
1016            replacing = _replacing;
1017            verifierUid = _verifierUid;
1018        }
1019    }
1020
1021    private interface IntentFilterVerifier<T extends IntentFilter> {
1022        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1023                                               T filter, String packageName);
1024        void startVerifications(int userId);
1025        void receiveVerificationResponse(int verificationId);
1026    }
1027
1028    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1029        private Context mContext;
1030        private ComponentName mIntentFilterVerifierComponent;
1031        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1032
1033        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1034            mContext = context;
1035            mIntentFilterVerifierComponent = verifierComponent;
1036        }
1037
1038        private String getDefaultScheme() {
1039            return IntentFilter.SCHEME_HTTPS;
1040        }
1041
1042        @Override
1043        public void startVerifications(int userId) {
1044            // Launch verifications requests
1045            int count = mCurrentIntentFilterVerifications.size();
1046            for (int n=0; n<count; n++) {
1047                int verificationId = mCurrentIntentFilterVerifications.get(n);
1048                final IntentFilterVerificationState ivs =
1049                        mIntentFilterVerificationStates.get(verificationId);
1050
1051                String packageName = ivs.getPackageName();
1052
1053                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1054                final int filterCount = filters.size();
1055                ArraySet<String> domainsSet = new ArraySet<>();
1056                for (int m=0; m<filterCount; m++) {
1057                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1058                    domainsSet.addAll(filter.getHostsList());
1059                }
1060                synchronized (mPackages) {
1061                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1062                            packageName, domainsSet) != null) {
1063                        scheduleWriteSettingsLocked();
1064                    }
1065                }
1066                sendVerificationRequest(verificationId, ivs);
1067            }
1068            mCurrentIntentFilterVerifications.clear();
1069        }
1070
1071        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1072            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1075                    verificationId);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1078                    getDefaultScheme());
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1081                    ivs.getHostsString());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1084                    ivs.getPackageName());
1085            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1086            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1087
1088            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1089            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1090                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1091                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1092
1093            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1094            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1095                    "Sending IntentFilter verification broadcast");
1096        }
1097
1098        public void receiveVerificationResponse(int verificationId) {
1099            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1100
1101            final boolean verified = ivs.isVerified();
1102
1103            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1104            final int count = filters.size();
1105            if (DEBUG_DOMAIN_VERIFICATION) {
1106                Slog.i(TAG, "Received verification response " + verificationId
1107                        + " for " + count + " filters, verified=" + verified);
1108            }
1109            for (int n=0; n<count; n++) {
1110                PackageParser.ActivityIntentInfo filter = filters.get(n);
1111                filter.setVerified(verified);
1112
1113                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1114                        + " verified with result:" + verified + " and hosts:"
1115                        + ivs.getHostsString());
1116            }
1117
1118            mIntentFilterVerificationStates.remove(verificationId);
1119
1120            final String packageName = ivs.getPackageName();
1121            IntentFilterVerificationInfo ivi = null;
1122
1123            synchronized (mPackages) {
1124                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1125            }
1126            if (ivi == null) {
1127                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1128                        + verificationId + " packageName:" + packageName);
1129                return;
1130            }
1131            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1132                    "Updating IntentFilterVerificationInfo for package " + packageName
1133                            +" verificationId:" + verificationId);
1134
1135            synchronized (mPackages) {
1136                if (verified) {
1137                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1138                } else {
1139                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1140                }
1141                scheduleWriteSettingsLocked();
1142
1143                final int userId = ivs.getUserId();
1144                if (userId != UserHandle.USER_ALL) {
1145                    final int userStatus =
1146                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1147
1148                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1149                    boolean needUpdate = false;
1150
1151                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1152                    // already been set by the User thru the Disambiguation dialog
1153                    switch (userStatus) {
1154                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1155                            if (verified) {
1156                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1157                            } else {
1158                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1159                            }
1160                            needUpdate = true;
1161                            break;
1162
1163                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1164                            if (verified) {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1166                                needUpdate = true;
1167                            }
1168                            break;
1169
1170                        default:
1171                            // Nothing to do
1172                    }
1173
1174                    if (needUpdate) {
1175                        mSettings.updateIntentFilterVerificationStatusLPw(
1176                                packageName, updatedStatus, userId);
1177                        scheduleWritePackageRestrictionsLocked(userId);
1178                    }
1179                }
1180            }
1181        }
1182
1183        @Override
1184        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1185                    ActivityIntentInfo filter, String packageName) {
1186            if (!hasValidDomains(filter)) {
1187                return false;
1188            }
1189            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1190            if (ivs == null) {
1191                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1192                        packageName);
1193            }
1194            if (DEBUG_DOMAIN_VERIFICATION) {
1195                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1196            }
1197            ivs.addFilter(filter);
1198            return true;
1199        }
1200
1201        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1202                int userId, int verificationId, String packageName) {
1203            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1204                    verifierUid, userId, packageName);
1205            ivs.setPendingState();
1206            synchronized (mPackages) {
1207                mIntentFilterVerificationStates.append(verificationId, ivs);
1208                mCurrentIntentFilterVerifications.add(verificationId);
1209            }
1210            return ivs;
1211        }
1212    }
1213
1214    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1215        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1216                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1217                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1218    }
1219
1220    // Set of pending broadcasts for aggregating enable/disable of components.
1221    static class PendingPackageBroadcasts {
1222        // for each user id, a map of <package name -> components within that package>
1223        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1224
1225        public PendingPackageBroadcasts() {
1226            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1227        }
1228
1229        public ArrayList<String> get(int userId, String packageName) {
1230            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231            return packages.get(packageName);
1232        }
1233
1234        public void put(int userId, String packageName, ArrayList<String> components) {
1235            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1236            packages.put(packageName, components);
1237        }
1238
1239        public void remove(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1241            if (packages != null) {
1242                packages.remove(packageName);
1243            }
1244        }
1245
1246        public void remove(int userId) {
1247            mUidMap.remove(userId);
1248        }
1249
1250        public int userIdCount() {
1251            return mUidMap.size();
1252        }
1253
1254        public int userIdAt(int n) {
1255            return mUidMap.keyAt(n);
1256        }
1257
1258        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1259            return mUidMap.get(userId);
1260        }
1261
1262        public int size() {
1263            // total number of pending broadcast entries across all userIds
1264            int num = 0;
1265            for (int i = 0; i< mUidMap.size(); i++) {
1266                num += mUidMap.valueAt(i).size();
1267            }
1268            return num;
1269        }
1270
1271        public void clear() {
1272            mUidMap.clear();
1273        }
1274
1275        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1276            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1277            if (map == null) {
1278                map = new ArrayMap<String, ArrayList<String>>();
1279                mUidMap.put(userId, map);
1280            }
1281            return map;
1282        }
1283    }
1284    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1285
1286    // Service Connection to remote media container service to copy
1287    // package uri's from external media onto secure containers
1288    // or internal storage.
1289    private IMediaContainerService mContainerService = null;
1290
1291    static final int SEND_PENDING_BROADCAST = 1;
1292    static final int MCS_BOUND = 3;
1293    static final int END_COPY = 4;
1294    static final int INIT_COPY = 5;
1295    static final int MCS_UNBIND = 6;
1296    static final int START_CLEANING_PACKAGE = 7;
1297    static final int FIND_INSTALL_LOC = 8;
1298    static final int POST_INSTALL = 9;
1299    static final int MCS_RECONNECT = 10;
1300    static final int MCS_GIVE_UP = 11;
1301    static final int UPDATED_MEDIA_STATUS = 12;
1302    static final int WRITE_SETTINGS = 13;
1303    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1304    static final int PACKAGE_VERIFIED = 15;
1305    static final int CHECK_PENDING_VERIFICATION = 16;
1306    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1307    static final int INTENT_FILTER_VERIFIED = 18;
1308    static final int WRITE_PACKAGE_LIST = 19;
1309    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1310
1311    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1312
1313    // Delay time in millisecs
1314    static final int BROADCAST_DELAY = 10 * 1000;
1315
1316    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1317            2 * 60 * 60 * 1000L; /* two hours */
1318
1319    static UserManagerService sUserManager;
1320
1321    // Stores a list of users whose package restrictions file needs to be updated
1322    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1323
1324    final private DefaultContainerConnection mDefContainerConn =
1325            new DefaultContainerConnection();
1326    class DefaultContainerConnection implements ServiceConnection {
1327        public void onServiceConnected(ComponentName name, IBinder service) {
1328            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1329            final IMediaContainerService imcs = IMediaContainerService.Stub
1330                    .asInterface(Binder.allowBlocking(service));
1331            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1332        }
1333
1334        public void onServiceDisconnected(ComponentName name) {
1335            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1336        }
1337    }
1338
1339    // Recordkeeping of restore-after-install operations that are currently in flight
1340    // between the Package Manager and the Backup Manager
1341    static class PostInstallData {
1342        public InstallArgs args;
1343        public PackageInstalledInfo res;
1344
1345        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1346            args = _a;
1347            res = _r;
1348        }
1349    }
1350
1351    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1352    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1353
1354    // XML tags for backup/restore of various bits of state
1355    private static final String TAG_PREFERRED_BACKUP = "pa";
1356    private static final String TAG_DEFAULT_APPS = "da";
1357    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1358
1359    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1360    private static final String TAG_ALL_GRANTS = "rt-grants";
1361    private static final String TAG_GRANT = "grant";
1362    private static final String ATTR_PACKAGE_NAME = "pkg";
1363
1364    private static final String TAG_PERMISSION = "perm";
1365    private static final String ATTR_PERMISSION_NAME = "name";
1366    private static final String ATTR_IS_GRANTED = "g";
1367    private static final String ATTR_USER_SET = "set";
1368    private static final String ATTR_USER_FIXED = "fixed";
1369    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1370
1371    // System/policy permission grants are not backed up
1372    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1373            FLAG_PERMISSION_POLICY_FIXED
1374            | FLAG_PERMISSION_SYSTEM_FIXED
1375            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1376
1377    // And we back up these user-adjusted states
1378    private static final int USER_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_USER_SET
1380            | FLAG_PERMISSION_USER_FIXED
1381            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1382
1383    final @Nullable String mRequiredVerifierPackage;
1384    final @NonNull String mRequiredInstallerPackage;
1385    final @NonNull String mRequiredUninstallerPackage;
1386    final @Nullable String mSetupWizardPackage;
1387    final @Nullable String mStorageManagerPackage;
1388    final @NonNull String mServicesSystemSharedLibraryPackageName;
1389    final @NonNull String mSharedSystemSharedLibraryPackageName;
1390
1391    final boolean mPermissionReviewRequired;
1392
1393    private final PackageUsage mPackageUsage = new PackageUsage();
1394    private final CompilerStats mCompilerStats = new CompilerStats();
1395
1396    class PackageHandler extends Handler {
1397        private boolean mBound = false;
1398        final ArrayList<HandlerParams> mPendingInstalls =
1399            new ArrayList<HandlerParams>();
1400
1401        private boolean connectToService() {
1402            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1403                    " DefaultContainerService");
1404            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1405            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1407                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1408                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409                mBound = true;
1410                return true;
1411            }
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413            return false;
1414        }
1415
1416        private void disconnectService() {
1417            mContainerService = null;
1418            mBound = false;
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            mContext.unbindService(mDefContainerConn);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422        }
1423
1424        PackageHandler(Looper looper) {
1425            super(looper);
1426        }
1427
1428        public void handleMessage(Message msg) {
1429            try {
1430                doHandleMessage(msg);
1431            } finally {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            }
1434        }
1435
1436        void doHandleMessage(Message msg) {
1437            switch (msg.what) {
1438                case INIT_COPY: {
1439                    HandlerParams params = (HandlerParams) msg.obj;
1440                    int idx = mPendingInstalls.size();
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1442                    // If a bind was already initiated we dont really
1443                    // need to do anything. The pending install
1444                    // will be processed later on.
1445                    if (!mBound) {
1446                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1447                                System.identityHashCode(mHandler));
1448                        // If this is the only one pending we might
1449                        // have to bind to the service again.
1450                        if (!connectToService()) {
1451                            Slog.e(TAG, "Failed to bind to media container service");
1452                            params.serviceError();
1453                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                    System.identityHashCode(mHandler));
1455                            if (params.traceMethod != null) {
1456                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1457                                        params.traceCookie);
1458                            }
1459                            return;
1460                        } else {
1461                            // Once we bind to the service, the first
1462                            // pending request will be processed.
1463                            mPendingInstalls.add(idx, params);
1464                        }
1465                    } else {
1466                        mPendingInstalls.add(idx, params);
1467                        // Already bound to the service. Just make
1468                        // sure we trigger off processing the first request.
1469                        if (idx == 0) {
1470                            mHandler.sendEmptyMessage(MCS_BOUND);
1471                        }
1472                    }
1473                    break;
1474                }
1475                case MCS_BOUND: {
1476                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1477                    if (msg.obj != null) {
1478                        mContainerService = (IMediaContainerService) msg.obj;
1479                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1480                                System.identityHashCode(mHandler));
1481                    }
1482                    if (mContainerService == null) {
1483                        if (!mBound) {
1484                            // Something seriously wrong since we are not bound and we are not
1485                            // waiting for connection. Bail out.
1486                            Slog.e(TAG, "Cannot bind to media container service");
1487                            for (HandlerParams params : mPendingInstalls) {
1488                                // Indicate service bind error
1489                                params.serviceError();
1490                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1491                                        System.identityHashCode(params));
1492                                if (params.traceMethod != null) {
1493                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1494                                            params.traceMethod, params.traceCookie);
1495                                }
1496                                return;
1497                            }
1498                            mPendingInstalls.clear();
1499                        } else {
1500                            Slog.w(TAG, "Waiting to connect to media container service");
1501                        }
1502                    } else if (mPendingInstalls.size() > 0) {
1503                        HandlerParams params = mPendingInstalls.get(0);
1504                        if (params != null) {
1505                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                                    System.identityHashCode(params));
1507                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1508                            if (params.startCopy()) {
1509                                // We are done...  look for more work or to
1510                                // go idle.
1511                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                        "Checking for more work or unbind...");
1513                                // Delete pending install
1514                                if (mPendingInstalls.size() > 0) {
1515                                    mPendingInstalls.remove(0);
1516                                }
1517                                if (mPendingInstalls.size() == 0) {
1518                                    if (mBound) {
1519                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1520                                                "Posting delayed MCS_UNBIND");
1521                                        removeMessages(MCS_UNBIND);
1522                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1523                                        // Unbind after a little delay, to avoid
1524                                        // continual thrashing.
1525                                        sendMessageDelayed(ubmsg, 10000);
1526                                    }
1527                                } else {
1528                                    // There are more pending requests in queue.
1529                                    // Just post MCS_BOUND message to trigger processing
1530                                    // of next pending install.
1531                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                            "Posting MCS_BOUND for next work");
1533                                    mHandler.sendEmptyMessage(MCS_BOUND);
1534                                }
1535                            }
1536                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1537                        }
1538                    } else {
1539                        // Should never happen ideally.
1540                        Slog.w(TAG, "Empty queue");
1541                    }
1542                    break;
1543                }
1544                case MCS_RECONNECT: {
1545                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1546                    if (mPendingInstalls.size() > 0) {
1547                        if (mBound) {
1548                            disconnectService();
1549                        }
1550                        if (!connectToService()) {
1551                            Slog.e(TAG, "Failed to bind to media container service");
1552                            for (HandlerParams params : mPendingInstalls) {
1553                                // Indicate service bind error
1554                                params.serviceError();
1555                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1556                                        System.identityHashCode(params));
1557                            }
1558                            mPendingInstalls.clear();
1559                        }
1560                    }
1561                    break;
1562                }
1563                case MCS_UNBIND: {
1564                    // If there is no actual work left, then time to unbind.
1565                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1566
1567                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1568                        if (mBound) {
1569                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1570
1571                            disconnectService();
1572                        }
1573                    } else if (mPendingInstalls.size() > 0) {
1574                        // There are more pending requests in queue.
1575                        // Just post MCS_BOUND message to trigger processing
1576                        // of next pending install.
1577                        mHandler.sendEmptyMessage(MCS_BOUND);
1578                    }
1579
1580                    break;
1581                }
1582                case MCS_GIVE_UP: {
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1584                    HandlerParams params = mPendingInstalls.remove(0);
1585                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                            System.identityHashCode(params));
1587                    break;
1588                }
1589                case SEND_PENDING_BROADCAST: {
1590                    String packages[];
1591                    ArrayList<String> components[];
1592                    int size = 0;
1593                    int uids[];
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        if (mPendingBroadcasts == null) {
1597                            return;
1598                        }
1599                        size = mPendingBroadcasts.size();
1600                        if (size <= 0) {
1601                            // Nothing to be done. Just return
1602                            return;
1603                        }
1604                        packages = new String[size];
1605                        components = new ArrayList[size];
1606                        uids = new int[size];
1607                        int i = 0;  // filling out the above arrays
1608
1609                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1610                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1611                            Iterator<Map.Entry<String, ArrayList<String>>> it
1612                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1613                                            .entrySet().iterator();
1614                            while (it.hasNext() && i < size) {
1615                                Map.Entry<String, ArrayList<String>> ent = it.next();
1616                                packages[i] = ent.getKey();
1617                                components[i] = ent.getValue();
1618                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1619                                uids[i] = (ps != null)
1620                                        ? UserHandle.getUid(packageUserId, ps.appId)
1621                                        : -1;
1622                                i++;
1623                            }
1624                        }
1625                        size = i;
1626                        mPendingBroadcasts.clear();
1627                    }
1628                    // Send broadcasts
1629                    for (int i = 0; i < size; i++) {
1630                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1631                    }
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1633                    break;
1634                }
1635                case START_CLEANING_PACKAGE: {
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1637                    final String packageName = (String)msg.obj;
1638                    final int userId = msg.arg1;
1639                    final boolean andCode = msg.arg2 != 0;
1640                    synchronized (mPackages) {
1641                        if (userId == UserHandle.USER_ALL) {
1642                            int[] users = sUserManager.getUserIds();
1643                            for (int user : users) {
1644                                mSettings.addPackageToCleanLPw(
1645                                        new PackageCleanItem(user, packageName, andCode));
1646                            }
1647                        } else {
1648                            mSettings.addPackageToCleanLPw(
1649                                    new PackageCleanItem(userId, packageName, andCode));
1650                        }
1651                    }
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1653                    startCleaningPackages();
1654                } break;
1655                case POST_INSTALL: {
1656                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1657
1658                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1659                    final boolean didRestore = (msg.arg2 != 0);
1660                    mRunningInstalls.delete(msg.arg1);
1661
1662                    if (data != null) {
1663                        InstallArgs args = data.args;
1664                        PackageInstalledInfo parentRes = data.res;
1665
1666                        final boolean grantPermissions = (args.installFlags
1667                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1668                        final boolean killApp = (args.installFlags
1669                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1670                        final String[] grantedPermissions = args.installGrantPermissions;
1671
1672                        // Handle the parent package
1673                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1674                                grantedPermissions, didRestore, args.installerPackageName,
1675                                args.observer);
1676
1677                        // Handle the child packages
1678                        final int childCount = (parentRes.addedChildPackages != null)
1679                                ? parentRes.addedChildPackages.size() : 0;
1680                        for (int i = 0; i < childCount; i++) {
1681                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1682                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1683                                    grantedPermissions, false, args.installerPackageName,
1684                                    args.observer);
1685                        }
1686
1687                        // Log tracing if needed
1688                        if (args.traceMethod != null) {
1689                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1690                                    args.traceCookie);
1691                        }
1692                    } else {
1693                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1694                    }
1695
1696                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1697                } break;
1698                case UPDATED_MEDIA_STATUS: {
1699                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1700                    boolean reportStatus = msg.arg1 == 1;
1701                    boolean doGc = msg.arg2 == 1;
1702                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1703                    if (doGc) {
1704                        // Force a gc to clear up stale containers.
1705                        Runtime.getRuntime().gc();
1706                    }
1707                    if (msg.obj != null) {
1708                        @SuppressWarnings("unchecked")
1709                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1710                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1711                        // Unload containers
1712                        unloadAllContainers(args);
1713                    }
1714                    if (reportStatus) {
1715                        try {
1716                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1717                                    "Invoking StorageManagerService call back");
1718                            PackageHelper.getStorageManager().finishMediaUpdate();
1719                        } catch (RemoteException e) {
1720                            Log.e(TAG, "StorageManagerService not running?");
1721                        }
1722                    }
1723                } break;
1724                case WRITE_SETTINGS: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_SETTINGS);
1728                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1729                        mSettings.writeLPr();
1730                        mDirtyUsers.clear();
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case WRITE_PACKAGE_RESTRICTIONS: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1738                        for (int userId : mDirtyUsers) {
1739                            mSettings.writePackageRestrictionsLPr(userId);
1740                        }
1741                        mDirtyUsers.clear();
1742                    }
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1744                } break;
1745                case WRITE_PACKAGE_LIST: {
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1747                    synchronized (mPackages) {
1748                        removeMessages(WRITE_PACKAGE_LIST);
1749                        mSettings.writePackageListLPr(msg.arg1);
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case CHECK_PENDING_VERIFICATION: {
1754                    final int verificationId = msg.arg1;
1755                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1756
1757                    if ((state != null) && !state.timeoutExtended()) {
1758                        final InstallArgs args = state.getInstallArgs();
1759                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1760
1761                        Slog.i(TAG, "Verification timed out for " + originUri);
1762                        mPendingVerification.remove(verificationId);
1763
1764                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1765
1766                        final UserHandle user = args.getUser();
1767                        if (getDefaultVerificationResponse(user)
1768                                == PackageManager.VERIFICATION_ALLOW) {
1769                            Slog.i(TAG, "Continuing with installation of " + originUri);
1770                            state.setVerifierResponse(Binder.getCallingUid(),
1771                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    PackageManager.VERIFICATION_ALLOW, user);
1774                            try {
1775                                ret = args.copyApk(mContainerService, true);
1776                            } catch (RemoteException e) {
1777                                Slog.e(TAG, "Could not contact the ContainerService");
1778                            }
1779                        } else {
1780                            broadcastPackageVerified(verificationId, originUri,
1781                                    PackageManager.VERIFICATION_REJECT, user);
1782                        }
1783
1784                        Trace.asyncTraceEnd(
1785                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1786
1787                        processPendingInstall(args, ret);
1788                        mHandler.sendEmptyMessage(MCS_UNBIND);
1789                    }
1790                    break;
1791                }
1792                case PACKAGE_VERIFIED: {
1793                    final int verificationId = msg.arg1;
1794
1795                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1796                    if (state == null) {
1797                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1798                        break;
1799                    }
1800
1801                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1802
1803                    state.setVerifierResponse(response.callerUid, response.code);
1804
1805                    if (state.isVerificationComplete()) {
1806                        mPendingVerification.remove(verificationId);
1807
1808                        final InstallArgs args = state.getInstallArgs();
1809                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1810
1811                        int ret;
1812                        if (state.isInstallAllowed()) {
1813                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1814                            broadcastPackageVerified(verificationId, originUri,
1815                                    response.code, state.getInstallArgs().getUser());
1816                            try {
1817                                ret = args.copyApk(mContainerService, true);
1818                            } catch (RemoteException e) {
1819                                Slog.e(TAG, "Could not contact the ContainerService");
1820                            }
1821                        } else {
1822                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1823                        }
1824
1825                        Trace.asyncTraceEnd(
1826                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1827
1828                        processPendingInstall(args, ret);
1829                        mHandler.sendEmptyMessage(MCS_UNBIND);
1830                    }
1831
1832                    break;
1833                }
1834                case START_INTENT_FILTER_VERIFICATIONS: {
1835                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1836                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1837                            params.replacing, params.pkg);
1838                    break;
1839                }
1840                case INTENT_FILTER_VERIFIED: {
1841                    final int verificationId = msg.arg1;
1842
1843                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1844                            verificationId);
1845                    if (state == null) {
1846                        Slog.w(TAG, "Invalid IntentFilter verification token "
1847                                + verificationId + " received");
1848                        break;
1849                    }
1850
1851                    final int userId = state.getUserId();
1852
1853                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1854                            "Processing IntentFilter verification with token:"
1855                            + verificationId + " and userId:" + userId);
1856
1857                    final IntentFilterVerificationResponse response =
1858                            (IntentFilterVerificationResponse) msg.obj;
1859
1860                    state.setVerifierResponse(response.callerUid, response.code);
1861
1862                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1863                            "IntentFilter verification with token:" + verificationId
1864                            + " and userId:" + userId
1865                            + " is settings verifier response with response code:"
1866                            + response.code);
1867
1868                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1870                                + response.getFailedDomainsString());
1871                    }
1872
1873                    if (state.isVerificationComplete()) {
1874                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1875                    } else {
1876                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                                "IntentFilter verification with token:" + verificationId
1878                                + " was not said to be complete");
1879                    }
1880
1881                    break;
1882                }
1883                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1884                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1885                            mInstantAppResolverConnection,
1886                            (InstantAppRequest) msg.obj,
1887                            mInstantAppInstallerActivity,
1888                            mHandler);
1889                }
1890            }
1891        }
1892    }
1893
1894    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1895            boolean killApp, String[] grantedPermissions,
1896            boolean launchedForRestore, String installerPackage,
1897            IPackageInstallObserver2 installObserver) {
1898        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1899            // Send the removed broadcasts
1900            if (res.removedInfo != null) {
1901                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1902            }
1903
1904            // Now that we successfully installed the package, grant runtime
1905            // permissions if requested before broadcasting the install. Also
1906            // for legacy apps in permission review mode we clear the permission
1907            // review flag which is used to emulate runtime permissions for
1908            // legacy apps.
1909            if (grantPermissions) {
1910                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1911            }
1912
1913            final boolean update = res.removedInfo != null
1914                    && res.removedInfo.removedPackage != null;
1915            final String origInstallerPackageName = res.removedInfo != null
1916                    ? res.removedInfo.installerPackageName : null;
1917
1918            // If this is the first time we have child packages for a disabled privileged
1919            // app that had no children, we grant requested runtime permissions to the new
1920            // children if the parent on the system image had them already granted.
1921            if (res.pkg.parentPackage != null) {
1922                synchronized (mPackages) {
1923                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1924                }
1925            }
1926
1927            synchronized (mPackages) {
1928                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1929            }
1930
1931            final String packageName = res.pkg.applicationInfo.packageName;
1932
1933            // Determine the set of users who are adding this package for
1934            // the first time vs. those who are seeing an update.
1935            int[] firstUsers = EMPTY_INT_ARRAY;
1936            int[] updateUsers = EMPTY_INT_ARRAY;
1937            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1938            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1939            for (int newUser : res.newUsers) {
1940                if (ps.getInstantApp(newUser)) {
1941                    continue;
1942                }
1943                if (allNewUsers) {
1944                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1945                    continue;
1946                }
1947                boolean isNew = true;
1948                for (int origUser : res.origUsers) {
1949                    if (origUser == newUser) {
1950                        isNew = false;
1951                        break;
1952                    }
1953                }
1954                if (isNew) {
1955                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1956                } else {
1957                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1958                }
1959            }
1960
1961            // Send installed broadcasts if the package is not a static shared lib.
1962            if (res.pkg.staticSharedLibName == null) {
1963                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1964
1965                // Send added for users that see the package for the first time
1966                // sendPackageAddedForNewUsers also deals with system apps
1967                int appId = UserHandle.getAppId(res.uid);
1968                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1969                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1970
1971                // Send added for users that don't see the package for the first time
1972                Bundle extras = new Bundle(1);
1973                extras.putInt(Intent.EXTRA_UID, res.uid);
1974                if (update) {
1975                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1976                }
1977                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1978                        extras, 0 /*flags*/,
1979                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1980                if (origInstallerPackageName != null) {
1981                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1982                            extras, 0 /*flags*/,
1983                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1984                }
1985
1986                // Send replaced for users that don't see the package for the first time
1987                if (update) {
1988                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1989                            packageName, extras, 0 /*flags*/,
1990                            null /*targetPackage*/, null /*finishedReceiver*/,
1991                            updateUsers);
1992                    if (origInstallerPackageName != null) {
1993                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1994                                extras, 0 /*flags*/,
1995                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1996                    }
1997                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1998                            null /*package*/, null /*extras*/, 0 /*flags*/,
1999                            packageName /*targetPackage*/,
2000                            null /*finishedReceiver*/, updateUsers);
2001                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2002                    // First-install and we did a restore, so we're responsible for the
2003                    // first-launch broadcast.
2004                    if (DEBUG_BACKUP) {
2005                        Slog.i(TAG, "Post-restore of " + packageName
2006                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2007                    }
2008                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2009                }
2010
2011                // Send broadcast package appeared if forward locked/external for all users
2012                // treat asec-hosted packages like removable media on upgrade
2013                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2014                    if (DEBUG_INSTALL) {
2015                        Slog.i(TAG, "upgrading pkg " + res.pkg
2016                                + " is ASEC-hosted -> AVAILABLE");
2017                    }
2018                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2019                    ArrayList<String> pkgList = new ArrayList<>(1);
2020                    pkgList.add(packageName);
2021                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2022                }
2023            }
2024
2025            // Work that needs to happen on first install within each user
2026            if (firstUsers != null && firstUsers.length > 0) {
2027                synchronized (mPackages) {
2028                    for (int userId : firstUsers) {
2029                        // If this app is a browser and it's newly-installed for some
2030                        // users, clear any default-browser state in those users. The
2031                        // app's nature doesn't depend on the user, so we can just check
2032                        // its browser nature in any user and generalize.
2033                        if (packageIsBrowser(packageName, userId)) {
2034                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2035                        }
2036
2037                        // We may also need to apply pending (restored) runtime
2038                        // permission grants within these users.
2039                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2040                    }
2041                }
2042            }
2043
2044            // Log current value of "unknown sources" setting
2045            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2046                    getUnknownSourcesSettings());
2047
2048            // Remove the replaced package's older resources safely now
2049            // We delete after a gc for applications  on sdcard.
2050            if (res.removedInfo != null && res.removedInfo.args != null) {
2051                Runtime.getRuntime().gc();
2052                synchronized (mInstallLock) {
2053                    res.removedInfo.args.doPostDeleteLI(true);
2054                }
2055            } else {
2056                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2057                // and not block here.
2058                VMRuntime.getRuntime().requestConcurrentGC();
2059            }
2060
2061            // Notify DexManager that the package was installed for new users.
2062            // The updated users should already be indexed and the package code paths
2063            // should not change.
2064            // Don't notify the manager for ephemeral apps as they are not expected to
2065            // survive long enough to benefit of background optimizations.
2066            for (int userId : firstUsers) {
2067                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2068                // There's a race currently where some install events may interleave with an uninstall.
2069                // This can lead to package info being null (b/36642664).
2070                if (info != null) {
2071                    mDexManager.notifyPackageInstalled(info, userId);
2072                }
2073            }
2074        }
2075
2076        // If someone is watching installs - notify them
2077        if (installObserver != null) {
2078            try {
2079                Bundle extras = extrasForInstallResult(res);
2080                installObserver.onPackageInstalled(res.name, res.returnCode,
2081                        res.returnMsg, extras);
2082            } catch (RemoteException e) {
2083                Slog.i(TAG, "Observer no longer exists.");
2084            }
2085        }
2086    }
2087
2088    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2089            PackageParser.Package pkg) {
2090        if (pkg.parentPackage == null) {
2091            return;
2092        }
2093        if (pkg.requestedPermissions == null) {
2094            return;
2095        }
2096        final PackageSetting disabledSysParentPs = mSettings
2097                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2098        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2099                || !disabledSysParentPs.isPrivileged()
2100                || (disabledSysParentPs.childPackageNames != null
2101                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2102            return;
2103        }
2104        final int[] allUserIds = sUserManager.getUserIds();
2105        final int permCount = pkg.requestedPermissions.size();
2106        for (int i = 0; i < permCount; i++) {
2107            String permission = pkg.requestedPermissions.get(i);
2108            BasePermission bp = mSettings.mPermissions.get(permission);
2109            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2110                continue;
2111            }
2112            for (int userId : allUserIds) {
2113                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2114                        permission, userId)) {
2115                    grantRuntimePermission(pkg.packageName, permission, userId);
2116                }
2117            }
2118        }
2119    }
2120
2121    private StorageEventListener mStorageListener = new StorageEventListener() {
2122        @Override
2123        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2124            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2125                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2126                    final String volumeUuid = vol.getFsUuid();
2127
2128                    // Clean up any users or apps that were removed or recreated
2129                    // while this volume was missing
2130                    sUserManager.reconcileUsers(volumeUuid);
2131                    reconcileApps(volumeUuid);
2132
2133                    // Clean up any install sessions that expired or were
2134                    // cancelled while this volume was missing
2135                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2136
2137                    loadPrivatePackages(vol);
2138
2139                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2140                    unloadPrivatePackages(vol);
2141                }
2142            }
2143
2144            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2145                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2146                    updateExternalMediaStatus(true, false);
2147                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2148                    updateExternalMediaStatus(false, false);
2149                }
2150            }
2151        }
2152
2153        @Override
2154        public void onVolumeForgotten(String fsUuid) {
2155            if (TextUtils.isEmpty(fsUuid)) {
2156                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2157                return;
2158            }
2159
2160            // Remove any apps installed on the forgotten volume
2161            synchronized (mPackages) {
2162                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2163                for (PackageSetting ps : packages) {
2164                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2165                    deletePackageVersioned(new VersionedPackage(ps.name,
2166                            PackageManager.VERSION_CODE_HIGHEST),
2167                            new LegacyPackageDeleteObserver(null).getBinder(),
2168                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2169                    // Try very hard to release any references to this package
2170                    // so we don't risk the system server being killed due to
2171                    // open FDs
2172                    AttributeCache.instance().removePackage(ps.name);
2173                }
2174
2175                mSettings.onVolumeForgotten(fsUuid);
2176                mSettings.writeLPr();
2177            }
2178        }
2179    };
2180
2181    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2182            String[] grantedPermissions) {
2183        for (int userId : userIds) {
2184            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2185        }
2186    }
2187
2188    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2189            String[] grantedPermissions) {
2190        PackageSetting ps = (PackageSetting) pkg.mExtras;
2191        if (ps == null) {
2192            return;
2193        }
2194
2195        PermissionsState permissionsState = ps.getPermissionsState();
2196
2197        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2198                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2199
2200        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2201                >= Build.VERSION_CODES.M;
2202
2203        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2204
2205        for (String permission : pkg.requestedPermissions) {
2206            final BasePermission bp;
2207            synchronized (mPackages) {
2208                bp = mSettings.mPermissions.get(permission);
2209            }
2210            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2211                    && (!instantApp || bp.isInstant())
2212                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2213                    && (grantedPermissions == null
2214                           || ArrayUtils.contains(grantedPermissions, permission))) {
2215                final int flags = permissionsState.getPermissionFlags(permission, userId);
2216                if (supportsRuntimePermissions) {
2217                    // Installer cannot change immutable permissions.
2218                    if ((flags & immutableFlags) == 0) {
2219                        grantRuntimePermission(pkg.packageName, permission, userId);
2220                    }
2221                } else if (mPermissionReviewRequired) {
2222                    // In permission review mode we clear the review flag when we
2223                    // are asked to install the app with all permissions granted.
2224                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2225                        updatePermissionFlags(permission, pkg.packageName,
2226                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2227                    }
2228                }
2229            }
2230        }
2231    }
2232
2233    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2234        Bundle extras = null;
2235        switch (res.returnCode) {
2236            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2237                extras = new Bundle();
2238                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2239                        res.origPermission);
2240                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2241                        res.origPackage);
2242                break;
2243            }
2244            case PackageManager.INSTALL_SUCCEEDED: {
2245                extras = new Bundle();
2246                extras.putBoolean(Intent.EXTRA_REPLACING,
2247                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2248                break;
2249            }
2250        }
2251        return extras;
2252    }
2253
2254    void scheduleWriteSettingsLocked() {
2255        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2256            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2257        }
2258    }
2259
2260    void scheduleWritePackageListLocked(int userId) {
2261        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2262            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2263            msg.arg1 = userId;
2264            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2265        }
2266    }
2267
2268    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2269        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2270        scheduleWritePackageRestrictionsLocked(userId);
2271    }
2272
2273    void scheduleWritePackageRestrictionsLocked(int userId) {
2274        final int[] userIds = (userId == UserHandle.USER_ALL)
2275                ? sUserManager.getUserIds() : new int[]{userId};
2276        for (int nextUserId : userIds) {
2277            if (!sUserManager.exists(nextUserId)) return;
2278            mDirtyUsers.add(nextUserId);
2279            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2280                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2281            }
2282        }
2283    }
2284
2285    public static PackageManagerService main(Context context, Installer installer,
2286            boolean factoryTest, boolean onlyCore) {
2287        // Self-check for initial settings.
2288        PackageManagerServiceCompilerMapping.checkProperties();
2289
2290        PackageManagerService m = new PackageManagerService(context, installer,
2291                factoryTest, onlyCore);
2292        m.enableSystemUserPackages();
2293        ServiceManager.addService("package", m);
2294        return m;
2295    }
2296
2297    private void enableSystemUserPackages() {
2298        if (!UserManager.isSplitSystemUser()) {
2299            return;
2300        }
2301        // For system user, enable apps based on the following conditions:
2302        // - app is whitelisted or belong to one of these groups:
2303        //   -- system app which has no launcher icons
2304        //   -- system app which has INTERACT_ACROSS_USERS permission
2305        //   -- system IME app
2306        // - app is not in the blacklist
2307        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2308        Set<String> enableApps = new ArraySet<>();
2309        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2310                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2311                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2312        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2313        enableApps.addAll(wlApps);
2314        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2315                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2316        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2317        enableApps.removeAll(blApps);
2318        Log.i(TAG, "Applications installed for system user: " + enableApps);
2319        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2320                UserHandle.SYSTEM);
2321        final int allAppsSize = allAps.size();
2322        synchronized (mPackages) {
2323            for (int i = 0; i < allAppsSize; i++) {
2324                String pName = allAps.get(i);
2325                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2326                // Should not happen, but we shouldn't be failing if it does
2327                if (pkgSetting == null) {
2328                    continue;
2329                }
2330                boolean install = enableApps.contains(pName);
2331                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2332                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2333                            + " for system user");
2334                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2335                }
2336            }
2337            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2338        }
2339    }
2340
2341    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2342        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2343                Context.DISPLAY_SERVICE);
2344        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2345    }
2346
2347    /**
2348     * Requests that files preopted on a secondary system partition be copied to the data partition
2349     * if possible.  Note that the actual copying of the files is accomplished by init for security
2350     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2351     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2352     */
2353    private static void requestCopyPreoptedFiles() {
2354        final int WAIT_TIME_MS = 100;
2355        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2356        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2357            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2358            // We will wait for up to 100 seconds.
2359            final long timeStart = SystemClock.uptimeMillis();
2360            final long timeEnd = timeStart + 100 * 1000;
2361            long timeNow = timeStart;
2362            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2363                try {
2364                    Thread.sleep(WAIT_TIME_MS);
2365                } catch (InterruptedException e) {
2366                    // Do nothing
2367                }
2368                timeNow = SystemClock.uptimeMillis();
2369                if (timeNow > timeEnd) {
2370                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2371                    Slog.wtf(TAG, "cppreopt did not finish!");
2372                    break;
2373                }
2374            }
2375
2376            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2377        }
2378    }
2379
2380    public PackageManagerService(Context context, Installer installer,
2381            boolean factoryTest, boolean onlyCore) {
2382        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2383        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2384        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2385                SystemClock.uptimeMillis());
2386
2387        if (mSdkVersion <= 0) {
2388            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2389        }
2390
2391        mContext = context;
2392
2393        mPermissionReviewRequired = context.getResources().getBoolean(
2394                R.bool.config_permissionReviewRequired);
2395
2396        mFactoryTest = factoryTest;
2397        mOnlyCore = onlyCore;
2398        mMetrics = new DisplayMetrics();
2399        mSettings = new Settings(mPackages);
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412
2413        String separateProcesses = SystemProperties.get("debug.separate_processes");
2414        if (separateProcesses != null && separateProcesses.length() > 0) {
2415            if ("*".equals(separateProcesses)) {
2416                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2417                mSeparateProcesses = null;
2418                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2419            } else {
2420                mDefParseFlags = 0;
2421                mSeparateProcesses = separateProcesses.split(",");
2422                Slog.w(TAG, "Running with debug.separate_processes: "
2423                        + separateProcesses);
2424            }
2425        } else {
2426            mDefParseFlags = 0;
2427            mSeparateProcesses = null;
2428        }
2429
2430        mInstaller = installer;
2431        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2432                "*dexopt*");
2433        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2434        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2435
2436        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2437                FgThread.get().getLooper());
2438
2439        getDefaultDisplayMetrics(context, mMetrics);
2440
2441        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2442        SystemConfig systemConfig = SystemConfig.getInstance();
2443        mGlobalGids = systemConfig.getGlobalGids();
2444        mSystemPermissions = systemConfig.getSystemPermissions();
2445        mAvailableFeatures = systemConfig.getAvailableFeatures();
2446        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2447
2448        mProtectedPackages = new ProtectedPackages(mContext);
2449
2450        synchronized (mInstallLock) {
2451        // writer
2452        synchronized (mPackages) {
2453            mHandlerThread = new ServiceThread(TAG,
2454                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2455            mHandlerThread.start();
2456            mHandler = new PackageHandler(mHandlerThread.getLooper());
2457            mProcessLoggingHandler = new ProcessLoggingHandler();
2458            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2459
2460            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2461            mInstantAppRegistry = new InstantAppRegistry(this);
2462
2463            File dataDir = Environment.getDataDirectory();
2464            mAppInstallDir = new File(dataDir, "app");
2465            mAppLib32InstallDir = new File(dataDir, "app-lib");
2466            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2467            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2468            sUserManager = new UserManagerService(context, this,
2469                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2470
2471            // Propagate permission configuration in to package manager.
2472            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2473                    = systemConfig.getPermissions();
2474            for (int i=0; i<permConfig.size(); i++) {
2475                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2476                BasePermission bp = mSettings.mPermissions.get(perm.name);
2477                if (bp == null) {
2478                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2479                    mSettings.mPermissions.put(perm.name, bp);
2480                }
2481                if (perm.gids != null) {
2482                    bp.setGids(perm.gids, perm.perUser);
2483                }
2484            }
2485
2486            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2487            final int builtInLibCount = libConfig.size();
2488            for (int i = 0; i < builtInLibCount; i++) {
2489                String name = libConfig.keyAt(i);
2490                String path = libConfig.valueAt(i);
2491                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2492                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2493            }
2494
2495            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2496
2497            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2498            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2500
2501            // Clean up orphaned packages for which the code path doesn't exist
2502            // and they are an update to a system app - caused by bug/32321269
2503            final int packageSettingCount = mSettings.mPackages.size();
2504            for (int i = packageSettingCount - 1; i >= 0; i--) {
2505                PackageSetting ps = mSettings.mPackages.valueAt(i);
2506                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2507                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2508                    mSettings.mPackages.removeAt(i);
2509                    mSettings.enableSystemPackageLPw(ps.name);
2510                }
2511            }
2512
2513            if (mFirstBoot) {
2514                requestCopyPreoptedFiles();
2515            }
2516
2517            String customResolverActivity = Resources.getSystem().getString(
2518                    R.string.config_customResolverActivity);
2519            if (TextUtils.isEmpty(customResolverActivity)) {
2520                customResolverActivity = null;
2521            } else {
2522                mCustomResolverComponentName = ComponentName.unflattenFromString(
2523                        customResolverActivity);
2524            }
2525
2526            long startTime = SystemClock.uptimeMillis();
2527
2528            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2529                    startTime);
2530
2531            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2532            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2533
2534            if (bootClassPath == null) {
2535                Slog.w(TAG, "No BOOTCLASSPATH found!");
2536            }
2537
2538            if (systemServerClassPath == null) {
2539                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2540            }
2541
2542            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2543
2544            final VersionInfo ver = mSettings.getInternalVersion();
2545            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2546            if (mIsUpgrade) {
2547                logCriticalInfo(Log.INFO,
2548                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2549            }
2550
2551            // when upgrading from pre-M, promote system app permissions from install to runtime
2552            mPromoteSystemApps =
2553                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2554
2555            // When upgrading from pre-N, we need to handle package extraction like first boot,
2556            // as there is no profiling data available.
2557            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2558
2559            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2560
2561            // save off the names of pre-existing system packages prior to scanning; we don't
2562            // want to automatically grant runtime permissions for new system apps
2563            if (mPromoteSystemApps) {
2564                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2565                while (pkgSettingIter.hasNext()) {
2566                    PackageSetting ps = pkgSettingIter.next();
2567                    if (isSystemApp(ps)) {
2568                        mExistingSystemPackages.add(ps.name);
2569                    }
2570                }
2571            }
2572
2573            mCacheDir = preparePackageParserCache(mIsUpgrade);
2574
2575            // Set flag to monitor and not change apk file paths when
2576            // scanning install directories.
2577            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2578
2579            if (mIsUpgrade || mFirstBoot) {
2580                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2581            }
2582
2583            // Collect vendor overlay packages. (Do this before scanning any apps.)
2584            // For security and version matching reason, only consider
2585            // overlay packages if they reside in the right directory.
2586            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR
2589                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2590
2591            mParallelPackageParserCallback.findStaticOverlayPackages();
2592
2593            // Find base frameworks (resource packages without code).
2594            scanDirTracedLI(frameworkDir, mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR
2597                    | PackageParser.PARSE_IS_PRIVILEGED,
2598                    scanFlags | SCAN_NO_DEX, 0);
2599
2600            // Collected privileged system packages.
2601            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2602            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2606
2607            // Collect ordinary system packages.
2608            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2609            scanDirTracedLI(systemAppDir, mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2612
2613            // Collect all vendor packages.
2614            File vendorAppDir = new File("/vendor/app");
2615            try {
2616                vendorAppDir = vendorAppDir.getCanonicalFile();
2617            } catch (IOException e) {
2618                // failed to look up canonical path, continue with original one
2619            }
2620            scanDirTracedLI(vendorAppDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2623
2624            // Collect all OEM packages.
2625            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2626            scanDirTracedLI(oemAppDir, mDefParseFlags
2627                    | PackageParser.PARSE_IS_SYSTEM
2628                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2629
2630            // Prune any system packages that no longer exist.
2631            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2632            if (!mOnlyCore) {
2633                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2634                while (psit.hasNext()) {
2635                    PackageSetting ps = psit.next();
2636
2637                    /*
2638                     * If this is not a system app, it can't be a
2639                     * disable system app.
2640                     */
2641                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2642                        continue;
2643                    }
2644
2645                    /*
2646                     * If the package is scanned, it's not erased.
2647                     */
2648                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2649                    if (scannedPkg != null) {
2650                        /*
2651                         * If the system app is both scanned and in the
2652                         * disabled packages list, then it must have been
2653                         * added via OTA. Remove it from the currently
2654                         * scanned package so the previously user-installed
2655                         * application can be scanned.
2656                         */
2657                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2658                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2659                                    + ps.name + "; removing system app.  Last known codePath="
2660                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2661                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2662                                    + scannedPkg.mVersionCode);
2663                            removePackageLI(scannedPkg, true);
2664                            mExpectingBetter.put(ps.name, ps.codePath);
2665                        }
2666
2667                        continue;
2668                    }
2669
2670                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2671                        psit.remove();
2672                        logCriticalInfo(Log.WARN, "System package " + ps.name
2673                                + " no longer exists; it's data will be wiped");
2674                        // Actual deletion of code and data will be handled by later
2675                        // reconciliation step
2676                    } else {
2677                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2678                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2679                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2680                        }
2681                    }
2682                }
2683            }
2684
2685            //look for any incomplete package installations
2686            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2687            for (int i = 0; i < deletePkgsList.size(); i++) {
2688                // Actual deletion of code and data will be handled by later
2689                // reconciliation step
2690                final String packageName = deletePkgsList.get(i).name;
2691                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2692                synchronized (mPackages) {
2693                    mSettings.removePackageLPw(packageName);
2694                }
2695            }
2696
2697            //delete tmp files
2698            deleteTempPackageFiles();
2699
2700            // Remove any shared userIDs that have no associated packages
2701            mSettings.pruneSharedUsersLPw();
2702            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2703            final int systemPackagesCount = mPackages.size();
2704            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2705                    + " ms, packageCount: " + systemPackagesCount
2706                    + " ms, timePerPackage: "
2707                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount));
2708            if (mIsUpgrade && systemPackagesCount > 0) {
2709                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2710                        ((int) systemScanTime) / systemPackagesCount);
2711            }
2712            if (!mOnlyCore) {
2713                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2714                        SystemClock.uptimeMillis());
2715                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2716
2717                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2718                        | PackageParser.PARSE_FORWARD_LOCK,
2719                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2720
2721                /**
2722                 * Remove disable package settings for any updated system
2723                 * apps that were removed via an OTA. If they're not a
2724                 * previously-updated app, remove them completely.
2725                 * Otherwise, just revoke their system-level permissions.
2726                 */
2727                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2728                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2729                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2730
2731                    String msg;
2732                    if (deletedPkg == null) {
2733                        msg = "Updated system package " + deletedAppName
2734                                + " no longer exists; it's data will be wiped";
2735                        // Actual deletion of code and data will be handled by later
2736                        // reconciliation step
2737                    } else {
2738                        msg = "Updated system app + " + deletedAppName
2739                                + " no longer present; removing system privileges for "
2740                                + deletedAppName;
2741
2742                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2743
2744                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2745                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2746                    }
2747                    logCriticalInfo(Log.WARN, msg);
2748                }
2749
2750                /**
2751                 * Make sure all system apps that we expected to appear on
2752                 * the userdata partition actually showed up. If they never
2753                 * appeared, crawl back and revive the system version.
2754                 */
2755                for (int i = 0; i < mExpectingBetter.size(); i++) {
2756                    final String packageName = mExpectingBetter.keyAt(i);
2757                    if (!mPackages.containsKey(packageName)) {
2758                        final File scanFile = mExpectingBetter.valueAt(i);
2759
2760                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2761                                + " but never showed up; reverting to system");
2762
2763                        int reparseFlags = mDefParseFlags;
2764                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2765                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2766                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2767                                    | PackageParser.PARSE_IS_PRIVILEGED;
2768                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2769                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2770                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2771                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2772                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2773                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2774                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2775                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2776                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2777                        } else {
2778                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2779                            continue;
2780                        }
2781
2782                        mSettings.enableSystemPackageLPw(packageName);
2783
2784                        try {
2785                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2786                        } catch (PackageManagerException e) {
2787                            Slog.e(TAG, "Failed to parse original system package: "
2788                                    + e.getMessage());
2789                        }
2790                    }
2791                }
2792                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2793                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2794                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2795                        + " ms, packageCount: " + dataPackagesCount
2796                        + " ms, timePerPackage: "
2797                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount));
2798                if (mIsUpgrade && dataPackagesCount > 0) {
2799                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2800                            ((int) dataScanTime) / dataPackagesCount);
2801                }
2802            }
2803            mExpectingBetter.clear();
2804
2805            // Resolve the storage manager.
2806            mStorageManagerPackage = getStorageManagerPackageName();
2807
2808            // Resolve protected action filters. Only the setup wizard is allowed to
2809            // have a high priority filter for these actions.
2810            mSetupWizardPackage = getSetupWizardPackageName();
2811            if (mProtectedFilters.size() > 0) {
2812                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2813                    Slog.i(TAG, "No setup wizard;"
2814                        + " All protected intents capped to priority 0");
2815                }
2816                for (ActivityIntentInfo filter : mProtectedFilters) {
2817                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2818                        if (DEBUG_FILTERS) {
2819                            Slog.i(TAG, "Found setup wizard;"
2820                                + " allow priority " + filter.getPriority() + ";"
2821                                + " package: " + filter.activity.info.packageName
2822                                + " activity: " + filter.activity.className
2823                                + " priority: " + filter.getPriority());
2824                        }
2825                        // skip setup wizard; allow it to keep the high priority filter
2826                        continue;
2827                    }
2828                    if (DEBUG_FILTERS) {
2829                        Slog.i(TAG, "Protected action; cap priority to 0;"
2830                                + " package: " + filter.activity.info.packageName
2831                                + " activity: " + filter.activity.className
2832                                + " origPrio: " + filter.getPriority());
2833                    }
2834                    filter.setPriority(0);
2835                }
2836            }
2837            mDeferProtectedFilters = false;
2838            mProtectedFilters.clear();
2839
2840            // Now that we know all of the shared libraries, update all clients to have
2841            // the correct library paths.
2842            updateAllSharedLibrariesLPw(null);
2843
2844            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2845                // NOTE: We ignore potential failures here during a system scan (like
2846                // the rest of the commands above) because there's precious little we
2847                // can do about it. A settings error is reported, though.
2848                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2849            }
2850
2851            // Now that we know all the packages we are keeping,
2852            // read and update their last usage times.
2853            mPackageUsage.read(mPackages);
2854            mCompilerStats.read();
2855
2856            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2857                    SystemClock.uptimeMillis());
2858            Slog.i(TAG, "Time to scan packages: "
2859                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2860                    + " seconds");
2861
2862            // If the platform SDK has changed since the last time we booted,
2863            // we need to re-grant app permission to catch any new ones that
2864            // appear.  This is really a hack, and means that apps can in some
2865            // cases get permissions that the user didn't initially explicitly
2866            // allow...  it would be nice to have some better way to handle
2867            // this situation.
2868            int updateFlags = UPDATE_PERMISSIONS_ALL;
2869            if (ver.sdkVersion != mSdkVersion) {
2870                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2871                        + mSdkVersion + "; regranting permissions for internal storage");
2872                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2873            }
2874            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2875            ver.sdkVersion = mSdkVersion;
2876
2877            // If this is the first boot or an update from pre-M, and it is a normal
2878            // boot, then we need to initialize the default preferred apps across
2879            // all defined users.
2880            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2881                for (UserInfo user : sUserManager.getUsers(true)) {
2882                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2883                    applyFactoryDefaultBrowserLPw(user.id);
2884                    primeDomainVerificationsLPw(user.id);
2885                }
2886            }
2887
2888            // Prepare storage for system user really early during boot,
2889            // since core system apps like SettingsProvider and SystemUI
2890            // can't wait for user to start
2891            final int storageFlags;
2892            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2893                storageFlags = StorageManager.FLAG_STORAGE_DE;
2894            } else {
2895                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2896            }
2897            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2898                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2899                    true /* onlyCoreApps */);
2900            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2901                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2902                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2903                traceLog.traceBegin("AppDataFixup");
2904                try {
2905                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2906                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2907                } catch (InstallerException e) {
2908                    Slog.w(TAG, "Trouble fixing GIDs", e);
2909                }
2910                traceLog.traceEnd();
2911
2912                traceLog.traceBegin("AppDataPrepare");
2913                if (deferPackages == null || deferPackages.isEmpty()) {
2914                    return;
2915                }
2916                int count = 0;
2917                for (String pkgName : deferPackages) {
2918                    PackageParser.Package pkg = null;
2919                    synchronized (mPackages) {
2920                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2921                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2922                            pkg = ps.pkg;
2923                        }
2924                    }
2925                    if (pkg != null) {
2926                        synchronized (mInstallLock) {
2927                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2928                                    true /* maybeMigrateAppData */);
2929                        }
2930                        count++;
2931                    }
2932                }
2933                traceLog.traceEnd();
2934                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2935            }, "prepareAppData");
2936
2937            // If this is first boot after an OTA, and a normal boot, then
2938            // we need to clear code cache directories.
2939            // Note that we do *not* clear the application profiles. These remain valid
2940            // across OTAs and are used to drive profile verification (post OTA) and
2941            // profile compilation (without waiting to collect a fresh set of profiles).
2942            if (mIsUpgrade && !onlyCore) {
2943                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2944                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2945                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2946                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2947                        // No apps are running this early, so no need to freeze
2948                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2949                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2950                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2951                    }
2952                }
2953                ver.fingerprint = Build.FINGERPRINT;
2954            }
2955
2956            checkDefaultBrowser();
2957
2958            // clear only after permissions and other defaults have been updated
2959            mExistingSystemPackages.clear();
2960            mPromoteSystemApps = false;
2961
2962            // All the changes are done during package scanning.
2963            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2964
2965            // can downgrade to reader
2966            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2967            mSettings.writeLPr();
2968            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2969            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2970                    SystemClock.uptimeMillis());
2971
2972            if (!mOnlyCore) {
2973                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2974                mRequiredInstallerPackage = getRequiredInstallerLPr();
2975                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2976                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2977                if (mIntentFilterVerifierComponent != null) {
2978                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2979                            mIntentFilterVerifierComponent);
2980                } else {
2981                    mIntentFilterVerifier = null;
2982                }
2983                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2984                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2985                        SharedLibraryInfo.VERSION_UNDEFINED);
2986                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2987                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2988                        SharedLibraryInfo.VERSION_UNDEFINED);
2989            } else {
2990                mRequiredVerifierPackage = null;
2991                mRequiredInstallerPackage = null;
2992                mRequiredUninstallerPackage = null;
2993                mIntentFilterVerifierComponent = null;
2994                mIntentFilterVerifier = null;
2995                mServicesSystemSharedLibraryPackageName = null;
2996                mSharedSystemSharedLibraryPackageName = null;
2997            }
2998
2999            mInstallerService = new PackageInstallerService(context, this);
3000            final Pair<ComponentName, String> instantAppResolverComponent =
3001                    getInstantAppResolverLPr();
3002            if (instantAppResolverComponent != null) {
3003                if (DEBUG_EPHEMERAL) {
3004                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3005                }
3006                mInstantAppResolverConnection = new EphemeralResolverConnection(
3007                        mContext, instantAppResolverComponent.first,
3008                        instantAppResolverComponent.second);
3009                mInstantAppResolverSettingsComponent =
3010                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3011            } else {
3012                mInstantAppResolverConnection = null;
3013                mInstantAppResolverSettingsComponent = null;
3014            }
3015            updateInstantAppInstallerLocked(null);
3016
3017            // Read and update the usage of dex files.
3018            // Do this at the end of PM init so that all the packages have their
3019            // data directory reconciled.
3020            // At this point we know the code paths of the packages, so we can validate
3021            // the disk file and build the internal cache.
3022            // The usage file is expected to be small so loading and verifying it
3023            // should take a fairly small time compare to the other activities (e.g. package
3024            // scanning).
3025            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3026            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3027            for (int userId : currentUserIds) {
3028                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3029            }
3030            mDexManager.load(userPackages);
3031            if (mIsUpgrade) {
3032                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3033                        (int) (SystemClock.uptimeMillis() - startTime));
3034            }
3035        } // synchronized (mPackages)
3036        } // synchronized (mInstallLock)
3037
3038        // Now after opening every single application zip, make sure they
3039        // are all flushed.  Not really needed, but keeps things nice and
3040        // tidy.
3041        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3042        Runtime.getRuntime().gc();
3043        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3044
3045        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3046        FallbackCategoryProvider.loadFallbacks();
3047        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3048
3049        // The initial scanning above does many calls into installd while
3050        // holding the mPackages lock, but we're mostly interested in yelling
3051        // once we have a booted system.
3052        mInstaller.setWarnIfHeld(mPackages);
3053
3054        // Expose private service for system components to use.
3055        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3056        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3057    }
3058
3059    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3060        // we're only interested in updating the installer appliction when 1) it's not
3061        // already set or 2) the modified package is the installer
3062        if (mInstantAppInstallerActivity != null
3063                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3064                        .equals(modifiedPackage)) {
3065            return;
3066        }
3067        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3068    }
3069
3070    private static File preparePackageParserCache(boolean isUpgrade) {
3071        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3072            return null;
3073        }
3074
3075        // Disable package parsing on eng builds to allow for faster incremental development.
3076        if (Build.IS_ENG) {
3077            return null;
3078        }
3079
3080        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3081            Slog.i(TAG, "Disabling package parser cache due to system property.");
3082            return null;
3083        }
3084
3085        // The base directory for the package parser cache lives under /data/system/.
3086        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3087                "package_cache");
3088        if (cacheBaseDir == null) {
3089            return null;
3090        }
3091
3092        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3093        // This also serves to "GC" unused entries when the package cache version changes (which
3094        // can only happen during upgrades).
3095        if (isUpgrade) {
3096            FileUtils.deleteContents(cacheBaseDir);
3097        }
3098
3099
3100        // Return the versioned package cache directory. This is something like
3101        // "/data/system/package_cache/1"
3102        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3103
3104        // The following is a workaround to aid development on non-numbered userdebug
3105        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3106        // the system partition is newer.
3107        //
3108        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3109        // that starts with "eng." to signify that this is an engineering build and not
3110        // destined for release.
3111        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3112            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3113
3114            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3115            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3116            // in general and should not be used for production changes. In this specific case,
3117            // we know that they will work.
3118            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3119            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3120                FileUtils.deleteContents(cacheBaseDir);
3121                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3122            }
3123        }
3124
3125        return cacheDir;
3126    }
3127
3128    @Override
3129    public boolean isFirstBoot() {
3130        // allow instant applications
3131        return mFirstBoot;
3132    }
3133
3134    @Override
3135    public boolean isOnlyCoreApps() {
3136        // allow instant applications
3137        return mOnlyCore;
3138    }
3139
3140    @Override
3141    public boolean isUpgrade() {
3142        // allow instant applications
3143        return mIsUpgrade;
3144    }
3145
3146    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3147        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3148
3149        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3150                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3151                UserHandle.USER_SYSTEM);
3152        if (matches.size() == 1) {
3153            return matches.get(0).getComponentInfo().packageName;
3154        } else if (matches.size() == 0) {
3155            Log.e(TAG, "There should probably be a verifier, but, none were found");
3156            return null;
3157        }
3158        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3159    }
3160
3161    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3162        synchronized (mPackages) {
3163            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3164            if (libraryEntry == null) {
3165                throw new IllegalStateException("Missing required shared library:" + name);
3166            }
3167            return libraryEntry.apk;
3168        }
3169    }
3170
3171    private @NonNull String getRequiredInstallerLPr() {
3172        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3173        intent.addCategory(Intent.CATEGORY_DEFAULT);
3174        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3175
3176        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3177                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3178                UserHandle.USER_SYSTEM);
3179        if (matches.size() == 1) {
3180            ResolveInfo resolveInfo = matches.get(0);
3181            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3182                throw new RuntimeException("The installer must be a privileged app");
3183            }
3184            return matches.get(0).getComponentInfo().packageName;
3185        } else {
3186            throw new RuntimeException("There must be exactly one installer; found " + matches);
3187        }
3188    }
3189
3190    private @NonNull String getRequiredUninstallerLPr() {
3191        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3192        intent.addCategory(Intent.CATEGORY_DEFAULT);
3193        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3194
3195        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3196                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3197                UserHandle.USER_SYSTEM);
3198        if (resolveInfo == null ||
3199                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3200            throw new RuntimeException("There must be exactly one uninstaller; found "
3201                    + resolveInfo);
3202        }
3203        return resolveInfo.getComponentInfo().packageName;
3204    }
3205
3206    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3207        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3208
3209        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3210                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3211                UserHandle.USER_SYSTEM);
3212        ResolveInfo best = null;
3213        final int N = matches.size();
3214        for (int i = 0; i < N; i++) {
3215            final ResolveInfo cur = matches.get(i);
3216            final String packageName = cur.getComponentInfo().packageName;
3217            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3218                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3219                continue;
3220            }
3221
3222            if (best == null || cur.priority > best.priority) {
3223                best = cur;
3224            }
3225        }
3226
3227        if (best != null) {
3228            return best.getComponentInfo().getComponentName();
3229        }
3230        Slog.w(TAG, "Intent filter verifier not found");
3231        return null;
3232    }
3233
3234    @Override
3235    public @Nullable ComponentName getInstantAppResolverComponent() {
3236        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3237            return null;
3238        }
3239        synchronized (mPackages) {
3240            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3241            if (instantAppResolver == null) {
3242                return null;
3243            }
3244            return instantAppResolver.first;
3245        }
3246    }
3247
3248    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3249        final String[] packageArray =
3250                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3251        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3252            if (DEBUG_EPHEMERAL) {
3253                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3254            }
3255            return null;
3256        }
3257
3258        final int callingUid = Binder.getCallingUid();
3259        final int resolveFlags =
3260                MATCH_DIRECT_BOOT_AWARE
3261                | MATCH_DIRECT_BOOT_UNAWARE
3262                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3263        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3264        final Intent resolverIntent = new Intent(actionName);
3265        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3266                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3267        // temporarily look for the old action
3268        if (resolvers.size() == 0) {
3269            if (DEBUG_EPHEMERAL) {
3270                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3271            }
3272            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3273            resolverIntent.setAction(actionName);
3274            resolvers = queryIntentServicesInternal(resolverIntent, null,
3275                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3276        }
3277        final int N = resolvers.size();
3278        if (N == 0) {
3279            if (DEBUG_EPHEMERAL) {
3280                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3281            }
3282            return null;
3283        }
3284
3285        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3286        for (int i = 0; i < N; i++) {
3287            final ResolveInfo info = resolvers.get(i);
3288
3289            if (info.serviceInfo == null) {
3290                continue;
3291            }
3292
3293            final String packageName = info.serviceInfo.packageName;
3294            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3295                if (DEBUG_EPHEMERAL) {
3296                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3297                            + " pkg: " + packageName + ", info:" + info);
3298                }
3299                continue;
3300            }
3301
3302            if (DEBUG_EPHEMERAL) {
3303                Slog.v(TAG, "Ephemeral resolver found;"
3304                        + " pkg: " + packageName + ", info:" + info);
3305            }
3306            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3307        }
3308        if (DEBUG_EPHEMERAL) {
3309            Slog.v(TAG, "Ephemeral resolver NOT found");
3310        }
3311        return null;
3312    }
3313
3314    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3315        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3316        intent.addCategory(Intent.CATEGORY_DEFAULT);
3317        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3318
3319        final int resolveFlags =
3320                MATCH_DIRECT_BOOT_AWARE
3321                | MATCH_DIRECT_BOOT_UNAWARE
3322                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3323        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3324                resolveFlags, UserHandle.USER_SYSTEM);
3325        // temporarily look for the old action
3326        if (matches.isEmpty()) {
3327            if (DEBUG_EPHEMERAL) {
3328                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3329            }
3330            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3331            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3332                    resolveFlags, UserHandle.USER_SYSTEM);
3333        }
3334        Iterator<ResolveInfo> iter = matches.iterator();
3335        while (iter.hasNext()) {
3336            final ResolveInfo rInfo = iter.next();
3337            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3338            if (ps != null) {
3339                final PermissionsState permissionsState = ps.getPermissionsState();
3340                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3341                    continue;
3342                }
3343            }
3344            iter.remove();
3345        }
3346        if (matches.size() == 0) {
3347            return null;
3348        } else if (matches.size() == 1) {
3349            return (ActivityInfo) matches.get(0).getComponentInfo();
3350        } else {
3351            throw new RuntimeException(
3352                    "There must be at most one ephemeral installer; found " + matches);
3353        }
3354    }
3355
3356    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3357            @NonNull ComponentName resolver) {
3358        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3359                .addCategory(Intent.CATEGORY_DEFAULT)
3360                .setPackage(resolver.getPackageName());
3361        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3362        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3363                UserHandle.USER_SYSTEM);
3364        // temporarily look for the old action
3365        if (matches.isEmpty()) {
3366            if (DEBUG_EPHEMERAL) {
3367                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3368            }
3369            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3370            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3371                    UserHandle.USER_SYSTEM);
3372        }
3373        if (matches.isEmpty()) {
3374            return null;
3375        }
3376        return matches.get(0).getComponentInfo().getComponentName();
3377    }
3378
3379    private void primeDomainVerificationsLPw(int userId) {
3380        if (DEBUG_DOMAIN_VERIFICATION) {
3381            Slog.d(TAG, "Priming domain verifications in user " + userId);
3382        }
3383
3384        SystemConfig systemConfig = SystemConfig.getInstance();
3385        ArraySet<String> packages = systemConfig.getLinkedApps();
3386
3387        for (String packageName : packages) {
3388            PackageParser.Package pkg = mPackages.get(packageName);
3389            if (pkg != null) {
3390                if (!pkg.isSystemApp()) {
3391                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3392                    continue;
3393                }
3394
3395                ArraySet<String> domains = null;
3396                for (PackageParser.Activity a : pkg.activities) {
3397                    for (ActivityIntentInfo filter : a.intents) {
3398                        if (hasValidDomains(filter)) {
3399                            if (domains == null) {
3400                                domains = new ArraySet<String>();
3401                            }
3402                            domains.addAll(filter.getHostsList());
3403                        }
3404                    }
3405                }
3406
3407                if (domains != null && domains.size() > 0) {
3408                    if (DEBUG_DOMAIN_VERIFICATION) {
3409                        Slog.v(TAG, "      + " + packageName);
3410                    }
3411                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3412                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3413                    // and then 'always' in the per-user state actually used for intent resolution.
3414                    final IntentFilterVerificationInfo ivi;
3415                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3416                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3417                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3418                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3419                } else {
3420                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3421                            + "' does not handle web links");
3422                }
3423            } else {
3424                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3425            }
3426        }
3427
3428        scheduleWritePackageRestrictionsLocked(userId);
3429        scheduleWriteSettingsLocked();
3430    }
3431
3432    private void applyFactoryDefaultBrowserLPw(int userId) {
3433        // The default browser app's package name is stored in a string resource,
3434        // with a product-specific overlay used for vendor customization.
3435        String browserPkg = mContext.getResources().getString(
3436                com.android.internal.R.string.default_browser);
3437        if (!TextUtils.isEmpty(browserPkg)) {
3438            // non-empty string => required to be a known package
3439            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3440            if (ps == null) {
3441                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3442                browserPkg = null;
3443            } else {
3444                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3445            }
3446        }
3447
3448        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3449        // default.  If there's more than one, just leave everything alone.
3450        if (browserPkg == null) {
3451            calculateDefaultBrowserLPw(userId);
3452        }
3453    }
3454
3455    private void calculateDefaultBrowserLPw(int userId) {
3456        List<String> allBrowsers = resolveAllBrowserApps(userId);
3457        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3458        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3459    }
3460
3461    private List<String> resolveAllBrowserApps(int userId) {
3462        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3463        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3464                PackageManager.MATCH_ALL, userId);
3465
3466        final int count = list.size();
3467        List<String> result = new ArrayList<String>(count);
3468        for (int i=0; i<count; i++) {
3469            ResolveInfo info = list.get(i);
3470            if (info.activityInfo == null
3471                    || !info.handleAllWebDataURI
3472                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3473                    || result.contains(info.activityInfo.packageName)) {
3474                continue;
3475            }
3476            result.add(info.activityInfo.packageName);
3477        }
3478
3479        return result;
3480    }
3481
3482    private boolean packageIsBrowser(String packageName, int userId) {
3483        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3484                PackageManager.MATCH_ALL, userId);
3485        final int N = list.size();
3486        for (int i = 0; i < N; i++) {
3487            ResolveInfo info = list.get(i);
3488            if (packageName.equals(info.activityInfo.packageName)) {
3489                return true;
3490            }
3491        }
3492        return false;
3493    }
3494
3495    private void checkDefaultBrowser() {
3496        final int myUserId = UserHandle.myUserId();
3497        final String packageName = getDefaultBrowserPackageName(myUserId);
3498        if (packageName != null) {
3499            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3500            if (info == null) {
3501                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3502                synchronized (mPackages) {
3503                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3504                }
3505            }
3506        }
3507    }
3508
3509    @Override
3510    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3511            throws RemoteException {
3512        try {
3513            return super.onTransact(code, data, reply, flags);
3514        } catch (RuntimeException e) {
3515            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3516                Slog.wtf(TAG, "Package Manager Crash", e);
3517            }
3518            throw e;
3519        }
3520    }
3521
3522    static int[] appendInts(int[] cur, int[] add) {
3523        if (add == null) return cur;
3524        if (cur == null) return add;
3525        final int N = add.length;
3526        for (int i=0; i<N; i++) {
3527            cur = appendInt(cur, add[i]);
3528        }
3529        return cur;
3530    }
3531
3532    /**
3533     * Returns whether or not a full application can see an instant application.
3534     * <p>
3535     * Currently, there are three cases in which this can occur:
3536     * <ol>
3537     * <li>The calling application is a "special" process. The special
3538     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3539     *     and {@code 0}</li>
3540     * <li>The calling application has the permission
3541     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3542     * <li>The calling application is the default launcher on the
3543     *     system partition.</li>
3544     * </ol>
3545     */
3546    private boolean canViewInstantApps(int callingUid, int userId) {
3547        if (callingUid == Process.SYSTEM_UID
3548                || callingUid == Process.SHELL_UID
3549                || callingUid == Process.ROOT_UID) {
3550            return true;
3551        }
3552        if (mContext.checkCallingOrSelfPermission(
3553                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3554            return true;
3555        }
3556        if (mContext.checkCallingOrSelfPermission(
3557                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3558            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3559            if (homeComponent != null
3560                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3561                return true;
3562            }
3563        }
3564        return false;
3565    }
3566
3567    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3568        if (!sUserManager.exists(userId)) return null;
3569        if (ps == null) {
3570            return null;
3571        }
3572        PackageParser.Package p = ps.pkg;
3573        if (p == null) {
3574            return null;
3575        }
3576        final int callingUid = Binder.getCallingUid();
3577        // Filter out ephemeral app metadata:
3578        //   * The system/shell/root can see metadata for any app
3579        //   * An installed app can see metadata for 1) other installed apps
3580        //     and 2) ephemeral apps that have explicitly interacted with it
3581        //   * Ephemeral apps can only see their own data and exposed installed apps
3582        //   * Holding a signature permission allows seeing instant apps
3583        if (filterAppAccessLPr(ps, callingUid, userId)) {
3584            return null;
3585        }
3586
3587        final PermissionsState permissionsState = ps.getPermissionsState();
3588
3589        // Compute GIDs only if requested
3590        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3591                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3592        // Compute granted permissions only if package has requested permissions
3593        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3594                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3595        final PackageUserState state = ps.readUserState(userId);
3596
3597        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3598                && ps.isSystem()) {
3599            flags |= MATCH_ANY_USER;
3600        }
3601
3602        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3603                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3604
3605        if (packageInfo == null) {
3606            return null;
3607        }
3608
3609        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3610                resolveExternalPackageNameLPr(p);
3611
3612        return packageInfo;
3613    }
3614
3615    @Override
3616    public void checkPackageStartable(String packageName, int userId) {
3617        final int callingUid = Binder.getCallingUid();
3618        if (getInstantAppPackageName(callingUid) != null) {
3619            throw new SecurityException("Instant applications don't have access to this method");
3620        }
3621        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3622        synchronized (mPackages) {
3623            final PackageSetting ps = mSettings.mPackages.get(packageName);
3624            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3625                throw new SecurityException("Package " + packageName + " was not found!");
3626            }
3627
3628            if (!ps.getInstalled(userId)) {
3629                throw new SecurityException(
3630                        "Package " + packageName + " was not installed for user " + userId + "!");
3631            }
3632
3633            if (mSafeMode && !ps.isSystem()) {
3634                throw new SecurityException("Package " + packageName + " not a system app!");
3635            }
3636
3637            if (mFrozenPackages.contains(packageName)) {
3638                throw new SecurityException("Package " + packageName + " is currently frozen!");
3639            }
3640
3641            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3642                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3643                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3644            }
3645        }
3646    }
3647
3648    @Override
3649    public boolean isPackageAvailable(String packageName, int userId) {
3650        if (!sUserManager.exists(userId)) return false;
3651        final int callingUid = Binder.getCallingUid();
3652        enforceCrossUserPermission(callingUid, userId,
3653                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3654        synchronized (mPackages) {
3655            PackageParser.Package p = mPackages.get(packageName);
3656            if (p != null) {
3657                final PackageSetting ps = (PackageSetting) p.mExtras;
3658                if (filterAppAccessLPr(ps, callingUid, userId)) {
3659                    return false;
3660                }
3661                if (ps != null) {
3662                    final PackageUserState state = ps.readUserState(userId);
3663                    if (state != null) {
3664                        return PackageParser.isAvailable(state);
3665                    }
3666                }
3667            }
3668        }
3669        return false;
3670    }
3671
3672    @Override
3673    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3674        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3675                flags, Binder.getCallingUid(), userId);
3676    }
3677
3678    @Override
3679    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3680            int flags, int userId) {
3681        return getPackageInfoInternal(versionedPackage.getPackageName(),
3682                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3683    }
3684
3685    /**
3686     * Important: The provided filterCallingUid is used exclusively to filter out packages
3687     * that can be seen based on user state. It's typically the original caller uid prior
3688     * to clearing. Because it can only be provided by trusted code, it's value can be
3689     * trusted and will be used as-is; unlike userId which will be validated by this method.
3690     */
3691    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3692            int flags, int filterCallingUid, int userId) {
3693        if (!sUserManager.exists(userId)) return null;
3694        flags = updateFlagsForPackage(flags, userId, packageName);
3695        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3696                false /* requireFullPermission */, false /* checkShell */, "get package info");
3697
3698        // reader
3699        synchronized (mPackages) {
3700            // Normalize package name to handle renamed packages and static libs
3701            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3702
3703            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3704            if (matchFactoryOnly) {
3705                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3706                if (ps != null) {
3707                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3708                        return null;
3709                    }
3710                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3711                        return null;
3712                    }
3713                    return generatePackageInfo(ps, flags, userId);
3714                }
3715            }
3716
3717            PackageParser.Package p = mPackages.get(packageName);
3718            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3719                return null;
3720            }
3721            if (DEBUG_PACKAGE_INFO)
3722                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3723            if (p != null) {
3724                final PackageSetting ps = (PackageSetting) p.mExtras;
3725                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3726                    return null;
3727                }
3728                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3729                    return null;
3730                }
3731                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3732            }
3733            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3734                final PackageSetting ps = mSettings.mPackages.get(packageName);
3735                if (ps == null) return null;
3736                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3737                    return null;
3738                }
3739                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3740                    return null;
3741                }
3742                return generatePackageInfo(ps, flags, userId);
3743            }
3744        }
3745        return null;
3746    }
3747
3748    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3749        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3750            return true;
3751        }
3752        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3753            return true;
3754        }
3755        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3756            return true;
3757        }
3758        return false;
3759    }
3760
3761    private boolean isComponentVisibleToInstantApp(
3762            @Nullable ComponentName component, @ComponentType int type) {
3763        if (type == TYPE_ACTIVITY) {
3764            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3765            return activity != null
3766                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3767                    : false;
3768        } else if (type == TYPE_RECEIVER) {
3769            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3770            return activity != null
3771                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3772                    : false;
3773        } else if (type == TYPE_SERVICE) {
3774            final PackageParser.Service service = mServices.mServices.get(component);
3775            return service != null
3776                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3777                    : false;
3778        } else if (type == TYPE_PROVIDER) {
3779            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3780            return provider != null
3781                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3782                    : false;
3783        } else if (type == TYPE_UNKNOWN) {
3784            return isComponentVisibleToInstantApp(component);
3785        }
3786        return false;
3787    }
3788
3789    /**
3790     * Returns whether or not access to the application should be filtered.
3791     * <p>
3792     * Access may be limited based upon whether the calling or target applications
3793     * are instant applications.
3794     *
3795     * @see #canAccessInstantApps(int)
3796     */
3797    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3798            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3799        // if we're in an isolated process, get the real calling UID
3800        if (Process.isIsolated(callingUid)) {
3801            callingUid = mIsolatedOwners.get(callingUid);
3802        }
3803        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3804        final boolean callerIsInstantApp = instantAppPkgName != null;
3805        if (ps == null) {
3806            if (callerIsInstantApp) {
3807                // pretend the application exists, but, needs to be filtered
3808                return true;
3809            }
3810            return false;
3811        }
3812        // if the target and caller are the same application, don't filter
3813        if (isCallerSameApp(ps.name, callingUid)) {
3814            return false;
3815        }
3816        if (callerIsInstantApp) {
3817            // request for a specific component; if it hasn't been explicitly exposed, filter
3818            if (component != null) {
3819                return !isComponentVisibleToInstantApp(component, componentType);
3820            }
3821            // request for application; if no components have been explicitly exposed, filter
3822            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3823        }
3824        if (ps.getInstantApp(userId)) {
3825            // caller can see all components of all instant applications, don't filter
3826            if (canViewInstantApps(callingUid, userId)) {
3827                return false;
3828            }
3829            // request for a specific instant application component, filter
3830            if (component != null) {
3831                return true;
3832            }
3833            // request for an instant application; if the caller hasn't been granted access, filter
3834            return !mInstantAppRegistry.isInstantAccessGranted(
3835                    userId, UserHandle.getAppId(callingUid), ps.appId);
3836        }
3837        return false;
3838    }
3839
3840    /**
3841     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3842     */
3843    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3844        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3845    }
3846
3847    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3848            int flags) {
3849        // Callers can access only the libs they depend on, otherwise they need to explicitly
3850        // ask for the shared libraries given the caller is allowed to access all static libs.
3851        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3852            // System/shell/root get to see all static libs
3853            final int appId = UserHandle.getAppId(uid);
3854            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3855                    || appId == Process.ROOT_UID) {
3856                return false;
3857            }
3858        }
3859
3860        // No package means no static lib as it is always on internal storage
3861        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3862            return false;
3863        }
3864
3865        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3866                ps.pkg.staticSharedLibVersion);
3867        if (libEntry == null) {
3868            return false;
3869        }
3870
3871        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3872        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3873        if (uidPackageNames == null) {
3874            return true;
3875        }
3876
3877        for (String uidPackageName : uidPackageNames) {
3878            if (ps.name.equals(uidPackageName)) {
3879                return false;
3880            }
3881            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3882            if (uidPs != null) {
3883                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3884                        libEntry.info.getName());
3885                if (index < 0) {
3886                    continue;
3887                }
3888                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3889                    return false;
3890                }
3891            }
3892        }
3893        return true;
3894    }
3895
3896    @Override
3897    public String[] currentToCanonicalPackageNames(String[] names) {
3898        final int callingUid = Binder.getCallingUid();
3899        if (getInstantAppPackageName(callingUid) != null) {
3900            return names;
3901        }
3902        final String[] out = new String[names.length];
3903        // reader
3904        synchronized (mPackages) {
3905            final int callingUserId = UserHandle.getUserId(callingUid);
3906            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3907            for (int i=names.length-1; i>=0; i--) {
3908                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3909                boolean translateName = false;
3910                if (ps != null && ps.realName != null) {
3911                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3912                    translateName = !targetIsInstantApp
3913                            || canViewInstantApps
3914                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3915                                    UserHandle.getAppId(callingUid), ps.appId);
3916                }
3917                out[i] = translateName ? ps.realName : names[i];
3918            }
3919        }
3920        return out;
3921    }
3922
3923    @Override
3924    public String[] canonicalToCurrentPackageNames(String[] names) {
3925        final int callingUid = Binder.getCallingUid();
3926        if (getInstantAppPackageName(callingUid) != null) {
3927            return names;
3928        }
3929        final String[] out = new String[names.length];
3930        // reader
3931        synchronized (mPackages) {
3932            final int callingUserId = UserHandle.getUserId(callingUid);
3933            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3934            for (int i=names.length-1; i>=0; i--) {
3935                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3936                boolean translateName = false;
3937                if (cur != null) {
3938                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3939                    final boolean targetIsInstantApp =
3940                            ps != null && ps.getInstantApp(callingUserId);
3941                    translateName = !targetIsInstantApp
3942                            || canViewInstantApps
3943                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3944                                    UserHandle.getAppId(callingUid), ps.appId);
3945                }
3946                out[i] = translateName ? cur : names[i];
3947            }
3948        }
3949        return out;
3950    }
3951
3952    @Override
3953    public int getPackageUid(String packageName, int flags, int userId) {
3954        if (!sUserManager.exists(userId)) return -1;
3955        final int callingUid = Binder.getCallingUid();
3956        flags = updateFlagsForPackage(flags, userId, packageName);
3957        enforceCrossUserPermission(callingUid, userId,
3958                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3959
3960        // reader
3961        synchronized (mPackages) {
3962            final PackageParser.Package p = mPackages.get(packageName);
3963            if (p != null && p.isMatch(flags)) {
3964                PackageSetting ps = (PackageSetting) p.mExtras;
3965                if (filterAppAccessLPr(ps, callingUid, userId)) {
3966                    return -1;
3967                }
3968                return UserHandle.getUid(userId, p.applicationInfo.uid);
3969            }
3970            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3971                final PackageSetting ps = mSettings.mPackages.get(packageName);
3972                if (ps != null && ps.isMatch(flags)
3973                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3974                    return UserHandle.getUid(userId, ps.appId);
3975                }
3976            }
3977        }
3978
3979        return -1;
3980    }
3981
3982    @Override
3983    public int[] getPackageGids(String packageName, int flags, int userId) {
3984        if (!sUserManager.exists(userId)) return null;
3985        final int callingUid = Binder.getCallingUid();
3986        flags = updateFlagsForPackage(flags, userId, packageName);
3987        enforceCrossUserPermission(callingUid, userId,
3988                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3989
3990        // reader
3991        synchronized (mPackages) {
3992            final PackageParser.Package p = mPackages.get(packageName);
3993            if (p != null && p.isMatch(flags)) {
3994                PackageSetting ps = (PackageSetting) p.mExtras;
3995                if (filterAppAccessLPr(ps, callingUid, userId)) {
3996                    return null;
3997                }
3998                // TODO: Shouldn't this be checking for package installed state for userId and
3999                // return null?
4000                return ps.getPermissionsState().computeGids(userId);
4001            }
4002            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4003                final PackageSetting ps = mSettings.mPackages.get(packageName);
4004                if (ps != null && ps.isMatch(flags)
4005                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4006                    return ps.getPermissionsState().computeGids(userId);
4007                }
4008            }
4009        }
4010
4011        return null;
4012    }
4013
4014    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4015        if (bp.perm != null) {
4016            return PackageParser.generatePermissionInfo(bp.perm, flags);
4017        }
4018        PermissionInfo pi = new PermissionInfo();
4019        pi.name = bp.name;
4020        pi.packageName = bp.sourcePackage;
4021        pi.nonLocalizedLabel = bp.name;
4022        pi.protectionLevel = bp.protectionLevel;
4023        return pi;
4024    }
4025
4026    @Override
4027    public PermissionInfo getPermissionInfo(String name, int flags) {
4028        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4029            return null;
4030        }
4031        // reader
4032        synchronized (mPackages) {
4033            final BasePermission p = mSettings.mPermissions.get(name);
4034            if (p != null) {
4035                return generatePermissionInfo(p, flags);
4036            }
4037            return null;
4038        }
4039    }
4040
4041    @Override
4042    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4043            int flags) {
4044        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4045            return null;
4046        }
4047        // reader
4048        synchronized (mPackages) {
4049            if (group != null && !mPermissionGroups.containsKey(group)) {
4050                // This is thrown as NameNotFoundException
4051                return null;
4052            }
4053
4054            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4055            for (BasePermission p : mSettings.mPermissions.values()) {
4056                if (group == null) {
4057                    if (p.perm == null || p.perm.info.group == null) {
4058                        out.add(generatePermissionInfo(p, flags));
4059                    }
4060                } else {
4061                    if (p.perm != null && group.equals(p.perm.info.group)) {
4062                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4063                    }
4064                }
4065            }
4066            return new ParceledListSlice<>(out);
4067        }
4068    }
4069
4070    @Override
4071    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4072        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4073            return null;
4074        }
4075        // reader
4076        synchronized (mPackages) {
4077            return PackageParser.generatePermissionGroupInfo(
4078                    mPermissionGroups.get(name), flags);
4079        }
4080    }
4081
4082    @Override
4083    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4084        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4085            return ParceledListSlice.emptyList();
4086        }
4087        // reader
4088        synchronized (mPackages) {
4089            final int N = mPermissionGroups.size();
4090            ArrayList<PermissionGroupInfo> out
4091                    = new ArrayList<PermissionGroupInfo>(N);
4092            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4093                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4094            }
4095            return new ParceledListSlice<>(out);
4096        }
4097    }
4098
4099    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4100            int filterCallingUid, int userId) {
4101        if (!sUserManager.exists(userId)) return null;
4102        PackageSetting ps = mSettings.mPackages.get(packageName);
4103        if (ps != null) {
4104            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4105                return null;
4106            }
4107            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4108                return null;
4109            }
4110            if (ps.pkg == null) {
4111                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4112                if (pInfo != null) {
4113                    return pInfo.applicationInfo;
4114                }
4115                return null;
4116            }
4117            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4118                    ps.readUserState(userId), userId);
4119            if (ai != null) {
4120                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4121            }
4122            return ai;
4123        }
4124        return null;
4125    }
4126
4127    @Override
4128    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4129        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4130    }
4131
4132    /**
4133     * Important: The provided filterCallingUid is used exclusively to filter out applications
4134     * that can be seen based on user state. It's typically the original caller uid prior
4135     * to clearing. Because it can only be provided by trusted code, it's value can be
4136     * trusted and will be used as-is; unlike userId which will be validated by this method.
4137     */
4138    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4139            int filterCallingUid, int userId) {
4140        if (!sUserManager.exists(userId)) return null;
4141        flags = updateFlagsForApplication(flags, userId, packageName);
4142        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4143                false /* requireFullPermission */, false /* checkShell */, "get application info");
4144
4145        // writer
4146        synchronized (mPackages) {
4147            // Normalize package name to handle renamed packages and static libs
4148            packageName = resolveInternalPackageNameLPr(packageName,
4149                    PackageManager.VERSION_CODE_HIGHEST);
4150
4151            PackageParser.Package p = mPackages.get(packageName);
4152            if (DEBUG_PACKAGE_INFO) Log.v(
4153                    TAG, "getApplicationInfo " + packageName
4154                    + ": " + p);
4155            if (p != null) {
4156                PackageSetting ps = mSettings.mPackages.get(packageName);
4157                if (ps == null) return null;
4158                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4159                    return null;
4160                }
4161                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4162                    return null;
4163                }
4164                // Note: isEnabledLP() does not apply here - always return info
4165                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4166                        p, flags, ps.readUserState(userId), userId);
4167                if (ai != null) {
4168                    ai.packageName = resolveExternalPackageNameLPr(p);
4169                }
4170                return ai;
4171            }
4172            if ("android".equals(packageName)||"system".equals(packageName)) {
4173                return mAndroidApplication;
4174            }
4175            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4176                // Already generates the external package name
4177                return generateApplicationInfoFromSettingsLPw(packageName,
4178                        flags, filterCallingUid, userId);
4179            }
4180        }
4181        return null;
4182    }
4183
4184    private String normalizePackageNameLPr(String packageName) {
4185        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4186        return normalizedPackageName != null ? normalizedPackageName : packageName;
4187    }
4188
4189    @Override
4190    public void deletePreloadsFileCache() {
4191        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4192            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4193        }
4194        File dir = Environment.getDataPreloadsFileCacheDirectory();
4195        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4196        FileUtils.deleteContents(dir);
4197    }
4198
4199    @Override
4200    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4201            final int storageFlags, final IPackageDataObserver observer) {
4202        mContext.enforceCallingOrSelfPermission(
4203                android.Manifest.permission.CLEAR_APP_CACHE, null);
4204        mHandler.post(() -> {
4205            boolean success = false;
4206            try {
4207                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4208                success = true;
4209            } catch (IOException e) {
4210                Slog.w(TAG, e);
4211            }
4212            if (observer != null) {
4213                try {
4214                    observer.onRemoveCompleted(null, success);
4215                } catch (RemoteException e) {
4216                    Slog.w(TAG, e);
4217                }
4218            }
4219        });
4220    }
4221
4222    @Override
4223    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4224            final int storageFlags, final IntentSender pi) {
4225        mContext.enforceCallingOrSelfPermission(
4226                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4227        mHandler.post(() -> {
4228            boolean success = false;
4229            try {
4230                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4231                success = true;
4232            } catch (IOException e) {
4233                Slog.w(TAG, e);
4234            }
4235            if (pi != null) {
4236                try {
4237                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4238                } catch (SendIntentException e) {
4239                    Slog.w(TAG, e);
4240                }
4241            }
4242        });
4243    }
4244
4245    /**
4246     * Blocking call to clear various types of cached data across the system
4247     * until the requested bytes are available.
4248     */
4249    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4250        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4251        final File file = storage.findPathForUuid(volumeUuid);
4252        if (file.getUsableSpace() >= bytes) return;
4253
4254        if (ENABLE_FREE_CACHE_V2) {
4255            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4256                    volumeUuid);
4257            final boolean aggressive = (storageFlags
4258                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4259            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4260
4261            // 1. Pre-flight to determine if we have any chance to succeed
4262            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4263            if (internalVolume && (aggressive || SystemProperties
4264                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4265                deletePreloadsFileCache();
4266                if (file.getUsableSpace() >= bytes) return;
4267            }
4268
4269            // 3. Consider parsed APK data (aggressive only)
4270            if (internalVolume && aggressive) {
4271                FileUtils.deleteContents(mCacheDir);
4272                if (file.getUsableSpace() >= bytes) return;
4273            }
4274
4275            // 4. Consider cached app data (above quotas)
4276            try {
4277                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4278                        Installer.FLAG_FREE_CACHE_V2);
4279            } catch (InstallerException ignored) {
4280            }
4281            if (file.getUsableSpace() >= bytes) return;
4282
4283            // 5. Consider shared libraries with refcount=0 and age>min cache period
4284            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4285                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4286                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4287                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4288                return;
4289            }
4290
4291            // 6. Consider dexopt output (aggressive only)
4292            // TODO: Implement
4293
4294            // 7. Consider installed instant apps unused longer than min cache period
4295            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4296                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4297                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4298                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4299                return;
4300            }
4301
4302            // 8. Consider cached app data (below quotas)
4303            try {
4304                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4305                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4306            } catch (InstallerException ignored) {
4307            }
4308            if (file.getUsableSpace() >= bytes) return;
4309
4310            // 9. Consider DropBox entries
4311            // TODO: Implement
4312
4313            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4314            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4315                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4316                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4317                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4318                return;
4319            }
4320        } else {
4321            try {
4322                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4323            } catch (InstallerException ignored) {
4324            }
4325            if (file.getUsableSpace() >= bytes) return;
4326        }
4327
4328        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4329    }
4330
4331    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4332            throws IOException {
4333        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4334        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4335
4336        List<VersionedPackage> packagesToDelete = null;
4337        final long now = System.currentTimeMillis();
4338
4339        synchronized (mPackages) {
4340            final int[] allUsers = sUserManager.getUserIds();
4341            final int libCount = mSharedLibraries.size();
4342            for (int i = 0; i < libCount; i++) {
4343                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4344                if (versionedLib == null) {
4345                    continue;
4346                }
4347                final int versionCount = versionedLib.size();
4348                for (int j = 0; j < versionCount; j++) {
4349                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4350                    // Skip packages that are not static shared libs.
4351                    if (!libInfo.isStatic()) {
4352                        break;
4353                    }
4354                    // Important: We skip static shared libs used for some user since
4355                    // in such a case we need to keep the APK on the device. The check for
4356                    // a lib being used for any user is performed by the uninstall call.
4357                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4358                    // Resolve the package name - we use synthetic package names internally
4359                    final String internalPackageName = resolveInternalPackageNameLPr(
4360                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4361                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4362                    // Skip unused static shared libs cached less than the min period
4363                    // to prevent pruning a lib needed by a subsequently installed package.
4364                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4365                        continue;
4366                    }
4367                    if (packagesToDelete == null) {
4368                        packagesToDelete = new ArrayList<>();
4369                    }
4370                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4371                            declaringPackage.getVersionCode()));
4372                }
4373            }
4374        }
4375
4376        if (packagesToDelete != null) {
4377            final int packageCount = packagesToDelete.size();
4378            for (int i = 0; i < packageCount; i++) {
4379                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4380                // Delete the package synchronously (will fail of the lib used for any user).
4381                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4382                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4383                                == PackageManager.DELETE_SUCCEEDED) {
4384                    if (volume.getUsableSpace() >= neededSpace) {
4385                        return true;
4386                    }
4387                }
4388            }
4389        }
4390
4391        return false;
4392    }
4393
4394    /**
4395     * Update given flags based on encryption status of current user.
4396     */
4397    private int updateFlags(int flags, int userId) {
4398        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4399                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4400            // Caller expressed an explicit opinion about what encryption
4401            // aware/unaware components they want to see, so fall through and
4402            // give them what they want
4403        } else {
4404            // Caller expressed no opinion, so match based on user state
4405            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4406                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4407            } else {
4408                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4409            }
4410        }
4411        return flags;
4412    }
4413
4414    private UserManagerInternal getUserManagerInternal() {
4415        if (mUserManagerInternal == null) {
4416            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4417        }
4418        return mUserManagerInternal;
4419    }
4420
4421    private DeviceIdleController.LocalService getDeviceIdleController() {
4422        if (mDeviceIdleController == null) {
4423            mDeviceIdleController =
4424                    LocalServices.getService(DeviceIdleController.LocalService.class);
4425        }
4426        return mDeviceIdleController;
4427    }
4428
4429    /**
4430     * Update given flags when being used to request {@link PackageInfo}.
4431     */
4432    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4433        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4434        boolean triaged = true;
4435        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4436                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4437            // Caller is asking for component details, so they'd better be
4438            // asking for specific encryption matching behavior, or be triaged
4439            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4440                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4441                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4442                triaged = false;
4443            }
4444        }
4445        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4446                | PackageManager.MATCH_SYSTEM_ONLY
4447                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4448            triaged = false;
4449        }
4450        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4451            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4452                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4453                    + Debug.getCallers(5));
4454        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4455                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4456            // If the caller wants all packages and has a restricted profile associated with it,
4457            // then match all users. This is to make sure that launchers that need to access work
4458            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4459            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4460            flags |= PackageManager.MATCH_ANY_USER;
4461        }
4462        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4463            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4464                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4465        }
4466        return updateFlags(flags, userId);
4467    }
4468
4469    /**
4470     * Update given flags when being used to request {@link ApplicationInfo}.
4471     */
4472    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4473        return updateFlagsForPackage(flags, userId, cookie);
4474    }
4475
4476    /**
4477     * Update given flags when being used to request {@link ComponentInfo}.
4478     */
4479    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4480        if (cookie instanceof Intent) {
4481            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4482                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4483            }
4484        }
4485
4486        boolean triaged = true;
4487        // Caller is asking for component details, so they'd better be
4488        // asking for specific encryption matching behavior, or be triaged
4489        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4490                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4491                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4492            triaged = false;
4493        }
4494        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4495            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4496                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4497        }
4498
4499        return updateFlags(flags, userId);
4500    }
4501
4502    /**
4503     * Update given intent when being used to request {@link ResolveInfo}.
4504     */
4505    private Intent updateIntentForResolve(Intent intent) {
4506        if (intent.getSelector() != null) {
4507            intent = intent.getSelector();
4508        }
4509        if (DEBUG_PREFERRED) {
4510            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4511        }
4512        return intent;
4513    }
4514
4515    /**
4516     * Update given flags when being used to request {@link ResolveInfo}.
4517     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4518     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4519     * flag set. However, this flag is only honoured in three circumstances:
4520     * <ul>
4521     * <li>when called from a system process</li>
4522     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4523     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4524     * action and a {@code android.intent.category.BROWSABLE} category</li>
4525     * </ul>
4526     */
4527    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4528        return updateFlagsForResolve(flags, userId, intent, callingUid,
4529                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4530    }
4531    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4532            boolean wantInstantApps) {
4533        return updateFlagsForResolve(flags, userId, intent, callingUid,
4534                wantInstantApps, false /*onlyExposedExplicitly*/);
4535    }
4536    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4537            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4538        // Safe mode means we shouldn't match any third-party components
4539        if (mSafeMode) {
4540            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4541        }
4542        if (getInstantAppPackageName(callingUid) != null) {
4543            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4544            if (onlyExposedExplicitly) {
4545                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4546            }
4547            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4548            flags |= PackageManager.MATCH_INSTANT;
4549        } else {
4550            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4551            final boolean allowMatchInstant =
4552                    (wantInstantApps
4553                            && Intent.ACTION_VIEW.equals(intent.getAction())
4554                            && hasWebURI(intent))
4555                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4556            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4557                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4558            if (!allowMatchInstant) {
4559                flags &= ~PackageManager.MATCH_INSTANT;
4560            }
4561        }
4562        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4563    }
4564
4565    @Override
4566    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4567        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4568    }
4569
4570    /**
4571     * Important: The provided filterCallingUid is used exclusively to filter out activities
4572     * that can be seen based on user state. It's typically the original caller uid prior
4573     * to clearing. Because it can only be provided by trusted code, it's value can be
4574     * trusted and will be used as-is; unlike userId which will be validated by this method.
4575     */
4576    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4577            int filterCallingUid, int userId) {
4578        if (!sUserManager.exists(userId)) return null;
4579        flags = updateFlagsForComponent(flags, userId, component);
4580        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4581                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4582        synchronized (mPackages) {
4583            PackageParser.Activity a = mActivities.mActivities.get(component);
4584
4585            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4586            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4587                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4588                if (ps == null) return null;
4589                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4590                    return null;
4591                }
4592                return PackageParser.generateActivityInfo(
4593                        a, flags, ps.readUserState(userId), userId);
4594            }
4595            if (mResolveComponentName.equals(component)) {
4596                return PackageParser.generateActivityInfo(
4597                        mResolveActivity, flags, new PackageUserState(), userId);
4598            }
4599        }
4600        return null;
4601    }
4602
4603    @Override
4604    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4605            String resolvedType) {
4606        synchronized (mPackages) {
4607            if (component.equals(mResolveComponentName)) {
4608                // The resolver supports EVERYTHING!
4609                return true;
4610            }
4611            final int callingUid = Binder.getCallingUid();
4612            final int callingUserId = UserHandle.getUserId(callingUid);
4613            PackageParser.Activity a = mActivities.mActivities.get(component);
4614            if (a == null) {
4615                return false;
4616            }
4617            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4618            if (ps == null) {
4619                return false;
4620            }
4621            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4622                return false;
4623            }
4624            for (int i=0; i<a.intents.size(); i++) {
4625                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4626                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4627                    return true;
4628                }
4629            }
4630            return false;
4631        }
4632    }
4633
4634    @Override
4635    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4636        if (!sUserManager.exists(userId)) return null;
4637        final int callingUid = Binder.getCallingUid();
4638        flags = updateFlagsForComponent(flags, userId, component);
4639        enforceCrossUserPermission(callingUid, userId,
4640                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4641        synchronized (mPackages) {
4642            PackageParser.Activity a = mReceivers.mActivities.get(component);
4643            if (DEBUG_PACKAGE_INFO) Log.v(
4644                TAG, "getReceiverInfo " + component + ": " + a);
4645            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4646                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4647                if (ps == null) return null;
4648                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4649                    return null;
4650                }
4651                return PackageParser.generateActivityInfo(
4652                        a, flags, ps.readUserState(userId), userId);
4653            }
4654        }
4655        return null;
4656    }
4657
4658    @Override
4659    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4660            int flags, int userId) {
4661        if (!sUserManager.exists(userId)) return null;
4662        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4663        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4664            return null;
4665        }
4666
4667        flags = updateFlagsForPackage(flags, userId, null);
4668
4669        final boolean canSeeStaticLibraries =
4670                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4671                        == PERMISSION_GRANTED
4672                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4673                        == PERMISSION_GRANTED
4674                || canRequestPackageInstallsInternal(packageName,
4675                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4676                        false  /* throwIfPermNotDeclared*/)
4677                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4678                        == PERMISSION_GRANTED;
4679
4680        synchronized (mPackages) {
4681            List<SharedLibraryInfo> result = null;
4682
4683            final int libCount = mSharedLibraries.size();
4684            for (int i = 0; i < libCount; i++) {
4685                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4686                if (versionedLib == null) {
4687                    continue;
4688                }
4689
4690                final int versionCount = versionedLib.size();
4691                for (int j = 0; j < versionCount; j++) {
4692                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4693                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4694                        break;
4695                    }
4696                    final long identity = Binder.clearCallingIdentity();
4697                    try {
4698                        PackageInfo packageInfo = getPackageInfoVersioned(
4699                                libInfo.getDeclaringPackage(), flags
4700                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4701                        if (packageInfo == null) {
4702                            continue;
4703                        }
4704                    } finally {
4705                        Binder.restoreCallingIdentity(identity);
4706                    }
4707
4708                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4709                            libInfo.getVersion(), libInfo.getType(),
4710                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4711                            flags, userId));
4712
4713                    if (result == null) {
4714                        result = new ArrayList<>();
4715                    }
4716                    result.add(resLibInfo);
4717                }
4718            }
4719
4720            return result != null ? new ParceledListSlice<>(result) : null;
4721        }
4722    }
4723
4724    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4725            SharedLibraryInfo libInfo, int flags, int userId) {
4726        List<VersionedPackage> versionedPackages = null;
4727        final int packageCount = mSettings.mPackages.size();
4728        for (int i = 0; i < packageCount; i++) {
4729            PackageSetting ps = mSettings.mPackages.valueAt(i);
4730
4731            if (ps == null) {
4732                continue;
4733            }
4734
4735            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4736                continue;
4737            }
4738
4739            final String libName = libInfo.getName();
4740            if (libInfo.isStatic()) {
4741                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4742                if (libIdx < 0) {
4743                    continue;
4744                }
4745                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4746                    continue;
4747                }
4748                if (versionedPackages == null) {
4749                    versionedPackages = new ArrayList<>();
4750                }
4751                // If the dependent is a static shared lib, use the public package name
4752                String dependentPackageName = ps.name;
4753                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4754                    dependentPackageName = ps.pkg.manifestPackageName;
4755                }
4756                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4757            } else if (ps.pkg != null) {
4758                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4759                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4760                    if (versionedPackages == null) {
4761                        versionedPackages = new ArrayList<>();
4762                    }
4763                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4764                }
4765            }
4766        }
4767
4768        return versionedPackages;
4769    }
4770
4771    @Override
4772    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4773        if (!sUserManager.exists(userId)) return null;
4774        final int callingUid = Binder.getCallingUid();
4775        flags = updateFlagsForComponent(flags, userId, component);
4776        enforceCrossUserPermission(callingUid, userId,
4777                false /* requireFullPermission */, false /* checkShell */, "get service info");
4778        synchronized (mPackages) {
4779            PackageParser.Service s = mServices.mServices.get(component);
4780            if (DEBUG_PACKAGE_INFO) Log.v(
4781                TAG, "getServiceInfo " + component + ": " + s);
4782            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4783                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4784                if (ps == null) return null;
4785                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4786                    return null;
4787                }
4788                return PackageParser.generateServiceInfo(
4789                        s, flags, ps.readUserState(userId), userId);
4790            }
4791        }
4792        return null;
4793    }
4794
4795    @Override
4796    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4797        if (!sUserManager.exists(userId)) return null;
4798        final int callingUid = Binder.getCallingUid();
4799        flags = updateFlagsForComponent(flags, userId, component);
4800        enforceCrossUserPermission(callingUid, userId,
4801                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4802        synchronized (mPackages) {
4803            PackageParser.Provider p = mProviders.mProviders.get(component);
4804            if (DEBUG_PACKAGE_INFO) Log.v(
4805                TAG, "getProviderInfo " + component + ": " + p);
4806            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4807                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4808                if (ps == null) return null;
4809                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4810                    return null;
4811                }
4812                return PackageParser.generateProviderInfo(
4813                        p, flags, ps.readUserState(userId), userId);
4814            }
4815        }
4816        return null;
4817    }
4818
4819    @Override
4820    public String[] getSystemSharedLibraryNames() {
4821        // allow instant applications
4822        synchronized (mPackages) {
4823            Set<String> libs = null;
4824            final int libCount = mSharedLibraries.size();
4825            for (int i = 0; i < libCount; i++) {
4826                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4827                if (versionedLib == null) {
4828                    continue;
4829                }
4830                final int versionCount = versionedLib.size();
4831                for (int j = 0; j < versionCount; j++) {
4832                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4833                    if (!libEntry.info.isStatic()) {
4834                        if (libs == null) {
4835                            libs = new ArraySet<>();
4836                        }
4837                        libs.add(libEntry.info.getName());
4838                        break;
4839                    }
4840                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4841                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4842                            UserHandle.getUserId(Binder.getCallingUid()),
4843                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4844                        if (libs == null) {
4845                            libs = new ArraySet<>();
4846                        }
4847                        libs.add(libEntry.info.getName());
4848                        break;
4849                    }
4850                }
4851            }
4852
4853            if (libs != null) {
4854                String[] libsArray = new String[libs.size()];
4855                libs.toArray(libsArray);
4856                return libsArray;
4857            }
4858
4859            return null;
4860        }
4861    }
4862
4863    @Override
4864    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4865        // allow instant applications
4866        synchronized (mPackages) {
4867            return mServicesSystemSharedLibraryPackageName;
4868        }
4869    }
4870
4871    @Override
4872    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4873        // allow instant applications
4874        synchronized (mPackages) {
4875            return mSharedSystemSharedLibraryPackageName;
4876        }
4877    }
4878
4879    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4880        for (int i = userList.length - 1; i >= 0; --i) {
4881            final int userId = userList[i];
4882            // don't add instant app to the list of updates
4883            if (pkgSetting.getInstantApp(userId)) {
4884                continue;
4885            }
4886            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4887            if (changedPackages == null) {
4888                changedPackages = new SparseArray<>();
4889                mChangedPackages.put(userId, changedPackages);
4890            }
4891            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4892            if (sequenceNumbers == null) {
4893                sequenceNumbers = new HashMap<>();
4894                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4895            }
4896            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4897            if (sequenceNumber != null) {
4898                changedPackages.remove(sequenceNumber);
4899            }
4900            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4901            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4902        }
4903        mChangedPackagesSequenceNumber++;
4904    }
4905
4906    @Override
4907    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4908        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4909            return null;
4910        }
4911        synchronized (mPackages) {
4912            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4913                return null;
4914            }
4915            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4916            if (changedPackages == null) {
4917                return null;
4918            }
4919            final List<String> packageNames =
4920                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4921            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4922                final String packageName = changedPackages.get(i);
4923                if (packageName != null) {
4924                    packageNames.add(packageName);
4925                }
4926            }
4927            return packageNames.isEmpty()
4928                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4929        }
4930    }
4931
4932    @Override
4933    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4934        // allow instant applications
4935        ArrayList<FeatureInfo> res;
4936        synchronized (mAvailableFeatures) {
4937            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4938            res.addAll(mAvailableFeatures.values());
4939        }
4940        final FeatureInfo fi = new FeatureInfo();
4941        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4942                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4943        res.add(fi);
4944
4945        return new ParceledListSlice<>(res);
4946    }
4947
4948    @Override
4949    public boolean hasSystemFeature(String name, int version) {
4950        // allow instant applications
4951        synchronized (mAvailableFeatures) {
4952            final FeatureInfo feat = mAvailableFeatures.get(name);
4953            if (feat == null) {
4954                return false;
4955            } else {
4956                return feat.version >= version;
4957            }
4958        }
4959    }
4960
4961    @Override
4962    public int checkPermission(String permName, String pkgName, int userId) {
4963        if (!sUserManager.exists(userId)) {
4964            return PackageManager.PERMISSION_DENIED;
4965        }
4966        final int callingUid = Binder.getCallingUid();
4967
4968        synchronized (mPackages) {
4969            final PackageParser.Package p = mPackages.get(pkgName);
4970            if (p != null && p.mExtras != null) {
4971                final PackageSetting ps = (PackageSetting) p.mExtras;
4972                if (filterAppAccessLPr(ps, callingUid, userId)) {
4973                    return PackageManager.PERMISSION_DENIED;
4974                }
4975                final boolean instantApp = ps.getInstantApp(userId);
4976                final PermissionsState permissionsState = ps.getPermissionsState();
4977                if (permissionsState.hasPermission(permName, userId)) {
4978                    if (instantApp) {
4979                        BasePermission bp = mSettings.mPermissions.get(permName);
4980                        if (bp != null && bp.isInstant()) {
4981                            return PackageManager.PERMISSION_GRANTED;
4982                        }
4983                    } else {
4984                        return PackageManager.PERMISSION_GRANTED;
4985                    }
4986                }
4987                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4988                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4989                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4990                    return PackageManager.PERMISSION_GRANTED;
4991                }
4992            }
4993        }
4994
4995        return PackageManager.PERMISSION_DENIED;
4996    }
4997
4998    @Override
4999    public int checkUidPermission(String permName, int uid) {
5000        final int callingUid = Binder.getCallingUid();
5001        final int callingUserId = UserHandle.getUserId(callingUid);
5002        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5003        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5004        final int userId = UserHandle.getUserId(uid);
5005        if (!sUserManager.exists(userId)) {
5006            return PackageManager.PERMISSION_DENIED;
5007        }
5008
5009        synchronized (mPackages) {
5010            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5011            if (obj != null) {
5012                if (obj instanceof SharedUserSetting) {
5013                    if (isCallerInstantApp) {
5014                        return PackageManager.PERMISSION_DENIED;
5015                    }
5016                } else if (obj instanceof PackageSetting) {
5017                    final PackageSetting ps = (PackageSetting) obj;
5018                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5019                        return PackageManager.PERMISSION_DENIED;
5020                    }
5021                }
5022                final SettingBase settingBase = (SettingBase) obj;
5023                final PermissionsState permissionsState = settingBase.getPermissionsState();
5024                if (permissionsState.hasPermission(permName, userId)) {
5025                    if (isUidInstantApp) {
5026                        BasePermission bp = mSettings.mPermissions.get(permName);
5027                        if (bp != null && bp.isInstant()) {
5028                            return PackageManager.PERMISSION_GRANTED;
5029                        }
5030                    } else {
5031                        return PackageManager.PERMISSION_GRANTED;
5032                    }
5033                }
5034                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5035                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5036                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5037                    return PackageManager.PERMISSION_GRANTED;
5038                }
5039            } else {
5040                ArraySet<String> perms = mSystemPermissions.get(uid);
5041                if (perms != null) {
5042                    if (perms.contains(permName)) {
5043                        return PackageManager.PERMISSION_GRANTED;
5044                    }
5045                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5046                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5047                        return PackageManager.PERMISSION_GRANTED;
5048                    }
5049                }
5050            }
5051        }
5052
5053        return PackageManager.PERMISSION_DENIED;
5054    }
5055
5056    @Override
5057    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5058        if (UserHandle.getCallingUserId() != userId) {
5059            mContext.enforceCallingPermission(
5060                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5061                    "isPermissionRevokedByPolicy for user " + userId);
5062        }
5063
5064        if (checkPermission(permission, packageName, userId)
5065                == PackageManager.PERMISSION_GRANTED) {
5066            return false;
5067        }
5068
5069        final int callingUid = Binder.getCallingUid();
5070        if (getInstantAppPackageName(callingUid) != null) {
5071            if (!isCallerSameApp(packageName, callingUid)) {
5072                return false;
5073            }
5074        } else {
5075            if (isInstantApp(packageName, userId)) {
5076                return false;
5077            }
5078        }
5079
5080        final long identity = Binder.clearCallingIdentity();
5081        try {
5082            final int flags = getPermissionFlags(permission, packageName, userId);
5083            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5084        } finally {
5085            Binder.restoreCallingIdentity(identity);
5086        }
5087    }
5088
5089    @Override
5090    public String getPermissionControllerPackageName() {
5091        synchronized (mPackages) {
5092            return mRequiredInstallerPackage;
5093        }
5094    }
5095
5096    /**
5097     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5098     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5099     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5100     * @param message the message to log on security exception
5101     */
5102    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5103            boolean checkShell, String message) {
5104        if (userId < 0) {
5105            throw new IllegalArgumentException("Invalid userId " + userId);
5106        }
5107        if (checkShell) {
5108            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5109        }
5110        if (userId == UserHandle.getUserId(callingUid)) return;
5111        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5112            if (requireFullPermission) {
5113                mContext.enforceCallingOrSelfPermission(
5114                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5115            } else {
5116                try {
5117                    mContext.enforceCallingOrSelfPermission(
5118                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5119                } catch (SecurityException se) {
5120                    mContext.enforceCallingOrSelfPermission(
5121                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5122                }
5123            }
5124        }
5125    }
5126
5127    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5128        if (callingUid == Process.SHELL_UID) {
5129            if (userHandle >= 0
5130                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5131                throw new SecurityException("Shell does not have permission to access user "
5132                        + userHandle);
5133            } else if (userHandle < 0) {
5134                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5135                        + Debug.getCallers(3));
5136            }
5137        }
5138    }
5139
5140    private BasePermission findPermissionTreeLP(String permName) {
5141        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5142            if (permName.startsWith(bp.name) &&
5143                    permName.length() > bp.name.length() &&
5144                    permName.charAt(bp.name.length()) == '.') {
5145                return bp;
5146            }
5147        }
5148        return null;
5149    }
5150
5151    private BasePermission checkPermissionTreeLP(String permName) {
5152        if (permName != null) {
5153            BasePermission bp = findPermissionTreeLP(permName);
5154            if (bp != null) {
5155                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5156                    return bp;
5157                }
5158                throw new SecurityException("Calling uid "
5159                        + Binder.getCallingUid()
5160                        + " is not allowed to add to permission tree "
5161                        + bp.name + " owned by uid " + bp.uid);
5162            }
5163        }
5164        throw new SecurityException("No permission tree found for " + permName);
5165    }
5166
5167    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5168        if (s1 == null) {
5169            return s2 == null;
5170        }
5171        if (s2 == null) {
5172            return false;
5173        }
5174        if (s1.getClass() != s2.getClass()) {
5175            return false;
5176        }
5177        return s1.equals(s2);
5178    }
5179
5180    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5181        if (pi1.icon != pi2.icon) return false;
5182        if (pi1.logo != pi2.logo) return false;
5183        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5184        if (!compareStrings(pi1.name, pi2.name)) return false;
5185        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5186        // We'll take care of setting this one.
5187        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5188        // These are not currently stored in settings.
5189        //if (!compareStrings(pi1.group, pi2.group)) return false;
5190        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5191        //if (pi1.labelRes != pi2.labelRes) return false;
5192        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5193        return true;
5194    }
5195
5196    int permissionInfoFootprint(PermissionInfo info) {
5197        int size = info.name.length();
5198        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5199        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5200        return size;
5201    }
5202
5203    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5204        int size = 0;
5205        for (BasePermission perm : mSettings.mPermissions.values()) {
5206            if (perm.uid == tree.uid) {
5207                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5208            }
5209        }
5210        return size;
5211    }
5212
5213    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5214        // We calculate the max size of permissions defined by this uid and throw
5215        // if that plus the size of 'info' would exceed our stated maximum.
5216        if (tree.uid != Process.SYSTEM_UID) {
5217            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5218            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5219                throw new SecurityException("Permission tree size cap exceeded");
5220            }
5221        }
5222    }
5223
5224    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5225        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5226            throw new SecurityException("Instant apps can't add permissions");
5227        }
5228        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5229            throw new SecurityException("Label must be specified in permission");
5230        }
5231        BasePermission tree = checkPermissionTreeLP(info.name);
5232        BasePermission bp = mSettings.mPermissions.get(info.name);
5233        boolean added = bp == null;
5234        boolean changed = true;
5235        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5236        if (added) {
5237            enforcePermissionCapLocked(info, tree);
5238            bp = new BasePermission(info.name, tree.sourcePackage,
5239                    BasePermission.TYPE_DYNAMIC);
5240        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5241            throw new SecurityException(
5242                    "Not allowed to modify non-dynamic permission "
5243                    + info.name);
5244        } else {
5245            if (bp.protectionLevel == fixedLevel
5246                    && bp.perm.owner.equals(tree.perm.owner)
5247                    && bp.uid == tree.uid
5248                    && comparePermissionInfos(bp.perm.info, info)) {
5249                changed = false;
5250            }
5251        }
5252        bp.protectionLevel = fixedLevel;
5253        info = new PermissionInfo(info);
5254        info.protectionLevel = fixedLevel;
5255        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5256        bp.perm.info.packageName = tree.perm.info.packageName;
5257        bp.uid = tree.uid;
5258        if (added) {
5259            mSettings.mPermissions.put(info.name, bp);
5260        }
5261        if (changed) {
5262            if (!async) {
5263                mSettings.writeLPr();
5264            } else {
5265                scheduleWriteSettingsLocked();
5266            }
5267        }
5268        return added;
5269    }
5270
5271    @Override
5272    public boolean addPermission(PermissionInfo info) {
5273        synchronized (mPackages) {
5274            return addPermissionLocked(info, false);
5275        }
5276    }
5277
5278    @Override
5279    public boolean addPermissionAsync(PermissionInfo info) {
5280        synchronized (mPackages) {
5281            return addPermissionLocked(info, true);
5282        }
5283    }
5284
5285    @Override
5286    public void removePermission(String name) {
5287        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5288            throw new SecurityException("Instant applications don't have access to this method");
5289        }
5290        synchronized (mPackages) {
5291            checkPermissionTreeLP(name);
5292            BasePermission bp = mSettings.mPermissions.get(name);
5293            if (bp != null) {
5294                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5295                    throw new SecurityException(
5296                            "Not allowed to modify non-dynamic permission "
5297                            + name);
5298                }
5299                mSettings.mPermissions.remove(name);
5300                mSettings.writeLPr();
5301            }
5302        }
5303    }
5304
5305    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5306            PackageParser.Package pkg, BasePermission bp) {
5307        int index = pkg.requestedPermissions.indexOf(bp.name);
5308        if (index == -1) {
5309            throw new SecurityException("Package " + pkg.packageName
5310                    + " has not requested permission " + bp.name);
5311        }
5312        if (!bp.isRuntime() && !bp.isDevelopment()) {
5313            throw new SecurityException("Permission " + bp.name
5314                    + " is not a changeable permission type");
5315        }
5316    }
5317
5318    @Override
5319    public void grantRuntimePermission(String packageName, String name, final int userId) {
5320        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5321    }
5322
5323    private void grantRuntimePermission(String packageName, String name, final int userId,
5324            boolean overridePolicy) {
5325        if (!sUserManager.exists(userId)) {
5326            Log.e(TAG, "No such user:" + userId);
5327            return;
5328        }
5329        final int callingUid = Binder.getCallingUid();
5330
5331        mContext.enforceCallingOrSelfPermission(
5332                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5333                "grantRuntimePermission");
5334
5335        enforceCrossUserPermission(callingUid, userId,
5336                true /* requireFullPermission */, true /* checkShell */,
5337                "grantRuntimePermission");
5338
5339        final int uid;
5340        final PackageSetting ps;
5341
5342        synchronized (mPackages) {
5343            final PackageParser.Package pkg = mPackages.get(packageName);
5344            if (pkg == null) {
5345                throw new IllegalArgumentException("Unknown package: " + packageName);
5346            }
5347            final BasePermission bp = mSettings.mPermissions.get(name);
5348            if (bp == null) {
5349                throw new IllegalArgumentException("Unknown permission: " + name);
5350            }
5351            ps = (PackageSetting) pkg.mExtras;
5352            if (ps == null
5353                    || filterAppAccessLPr(ps, callingUid, userId)) {
5354                throw new IllegalArgumentException("Unknown package: " + packageName);
5355            }
5356
5357            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5358
5359            // If a permission review is required for legacy apps we represent
5360            // their permissions as always granted runtime ones since we need
5361            // to keep the review required permission flag per user while an
5362            // install permission's state is shared across all users.
5363            if (mPermissionReviewRequired
5364                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5365                    && bp.isRuntime()) {
5366                return;
5367            }
5368
5369            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5370
5371            final PermissionsState permissionsState = ps.getPermissionsState();
5372
5373            final int flags = permissionsState.getPermissionFlags(name, userId);
5374            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5375                throw new SecurityException("Cannot grant system fixed permission "
5376                        + name + " for package " + packageName);
5377            }
5378            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5379                throw new SecurityException("Cannot grant policy fixed permission "
5380                        + name + " for package " + packageName);
5381            }
5382
5383            if (bp.isDevelopment()) {
5384                // Development permissions must be handled specially, since they are not
5385                // normal runtime permissions.  For now they apply to all users.
5386                if (permissionsState.grantInstallPermission(bp) !=
5387                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5388                    scheduleWriteSettingsLocked();
5389                }
5390                return;
5391            }
5392
5393            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5394                throw new SecurityException("Cannot grant non-ephemeral permission"
5395                        + name + " for package " + packageName);
5396            }
5397
5398            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5399                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5400                return;
5401            }
5402
5403            final int result = permissionsState.grantRuntimePermission(bp, userId);
5404            switch (result) {
5405                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5406                    return;
5407                }
5408
5409                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5410                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5411                    mHandler.post(new Runnable() {
5412                        @Override
5413                        public void run() {
5414                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5415                        }
5416                    });
5417                }
5418                break;
5419            }
5420
5421            if (bp.isRuntime()) {
5422                logPermissionGranted(mContext, name, packageName);
5423            }
5424
5425            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5426
5427            // Not critical if that is lost - app has to request again.
5428            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5429        }
5430
5431        // Only need to do this if user is initialized. Otherwise it's a new user
5432        // and there are no processes running as the user yet and there's no need
5433        // to make an expensive call to remount processes for the changed permissions.
5434        if (READ_EXTERNAL_STORAGE.equals(name)
5435                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5436            final long token = Binder.clearCallingIdentity();
5437            try {
5438                if (sUserManager.isInitialized(userId)) {
5439                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5440                            StorageManagerInternal.class);
5441                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5442                }
5443            } finally {
5444                Binder.restoreCallingIdentity(token);
5445            }
5446        }
5447    }
5448
5449    @Override
5450    public void revokeRuntimePermission(String packageName, String name, int userId) {
5451        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5452    }
5453
5454    private void revokeRuntimePermission(String packageName, String name, int userId,
5455            boolean overridePolicy) {
5456        if (!sUserManager.exists(userId)) {
5457            Log.e(TAG, "No such user:" + userId);
5458            return;
5459        }
5460
5461        mContext.enforceCallingOrSelfPermission(
5462                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5463                "revokeRuntimePermission");
5464
5465        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5466                true /* requireFullPermission */, true /* checkShell */,
5467                "revokeRuntimePermission");
5468
5469        final int appId;
5470
5471        synchronized (mPackages) {
5472            final PackageParser.Package pkg = mPackages.get(packageName);
5473            if (pkg == null) {
5474                throw new IllegalArgumentException("Unknown package: " + packageName);
5475            }
5476            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5477            if (ps == null
5478                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5479                throw new IllegalArgumentException("Unknown package: " + packageName);
5480            }
5481            final BasePermission bp = mSettings.mPermissions.get(name);
5482            if (bp == null) {
5483                throw new IllegalArgumentException("Unknown permission: " + name);
5484            }
5485
5486            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5487
5488            // If a permission review is required for legacy apps we represent
5489            // their permissions as always granted runtime ones since we need
5490            // to keep the review required permission flag per user while an
5491            // install permission's state is shared across all users.
5492            if (mPermissionReviewRequired
5493                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5494                    && bp.isRuntime()) {
5495                return;
5496            }
5497
5498            final PermissionsState permissionsState = ps.getPermissionsState();
5499
5500            final int flags = permissionsState.getPermissionFlags(name, userId);
5501            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5502                throw new SecurityException("Cannot revoke system fixed permission "
5503                        + name + " for package " + packageName);
5504            }
5505            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5506                throw new SecurityException("Cannot revoke policy fixed permission "
5507                        + name + " for package " + packageName);
5508            }
5509
5510            if (bp.isDevelopment()) {
5511                // Development permissions must be handled specially, since they are not
5512                // normal runtime permissions.  For now they apply to all users.
5513                if (permissionsState.revokeInstallPermission(bp) !=
5514                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5515                    scheduleWriteSettingsLocked();
5516                }
5517                return;
5518            }
5519
5520            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5521                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5522                return;
5523            }
5524
5525            if (bp.isRuntime()) {
5526                logPermissionRevoked(mContext, name, packageName);
5527            }
5528
5529            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5530
5531            // Critical, after this call app should never have the permission.
5532            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5533
5534            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5535        }
5536
5537        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5538    }
5539
5540    /**
5541     * Get the first event id for the permission.
5542     *
5543     * <p>There are four events for each permission: <ul>
5544     *     <li>Request permission: first id + 0</li>
5545     *     <li>Grant permission: first id + 1</li>
5546     *     <li>Request for permission denied: first id + 2</li>
5547     *     <li>Revoke permission: first id + 3</li>
5548     * </ul></p>
5549     *
5550     * @param name name of the permission
5551     *
5552     * @return The first event id for the permission
5553     */
5554    private static int getBaseEventId(@NonNull String name) {
5555        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5556
5557        if (eventIdIndex == -1) {
5558            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5559                    || Build.IS_USER) {
5560                Log.i(TAG, "Unknown permission " + name);
5561
5562                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5563            } else {
5564                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5565                //
5566                // Also update
5567                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5568                // - metrics_constants.proto
5569                throw new IllegalStateException("Unknown permission " + name);
5570            }
5571        }
5572
5573        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5574    }
5575
5576    /**
5577     * Log that a permission was revoked.
5578     *
5579     * @param context Context of the caller
5580     * @param name name of the permission
5581     * @param packageName package permission if for
5582     */
5583    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5584            @NonNull String packageName) {
5585        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5586    }
5587
5588    /**
5589     * Log that a permission request was granted.
5590     *
5591     * @param context Context of the caller
5592     * @param name name of the permission
5593     * @param packageName package permission if for
5594     */
5595    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5596            @NonNull String packageName) {
5597        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5598    }
5599
5600    @Override
5601    public void resetRuntimePermissions() {
5602        mContext.enforceCallingOrSelfPermission(
5603                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5604                "revokeRuntimePermission");
5605
5606        int callingUid = Binder.getCallingUid();
5607        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5608            mContext.enforceCallingOrSelfPermission(
5609                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5610                    "resetRuntimePermissions");
5611        }
5612
5613        synchronized (mPackages) {
5614            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5615            for (int userId : UserManagerService.getInstance().getUserIds()) {
5616                final int packageCount = mPackages.size();
5617                for (int i = 0; i < packageCount; i++) {
5618                    PackageParser.Package pkg = mPackages.valueAt(i);
5619                    if (!(pkg.mExtras instanceof PackageSetting)) {
5620                        continue;
5621                    }
5622                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5623                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5624                }
5625            }
5626        }
5627    }
5628
5629    @Override
5630    public int getPermissionFlags(String name, String packageName, int userId) {
5631        if (!sUserManager.exists(userId)) {
5632            return 0;
5633        }
5634
5635        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5636
5637        final int callingUid = Binder.getCallingUid();
5638        enforceCrossUserPermission(callingUid, userId,
5639                true /* requireFullPermission */, false /* checkShell */,
5640                "getPermissionFlags");
5641
5642        synchronized (mPackages) {
5643            final PackageParser.Package pkg = mPackages.get(packageName);
5644            if (pkg == null) {
5645                return 0;
5646            }
5647            final BasePermission bp = mSettings.mPermissions.get(name);
5648            if (bp == null) {
5649                return 0;
5650            }
5651            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5652            if (ps == null
5653                    || filterAppAccessLPr(ps, callingUid, userId)) {
5654                return 0;
5655            }
5656            PermissionsState permissionsState = ps.getPermissionsState();
5657            return permissionsState.getPermissionFlags(name, userId);
5658        }
5659    }
5660
5661    @Override
5662    public void updatePermissionFlags(String name, String packageName, int flagMask,
5663            int flagValues, int userId) {
5664        if (!sUserManager.exists(userId)) {
5665            return;
5666        }
5667
5668        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5669
5670        final int callingUid = Binder.getCallingUid();
5671        enforceCrossUserPermission(callingUid, userId,
5672                true /* requireFullPermission */, true /* checkShell */,
5673                "updatePermissionFlags");
5674
5675        // Only the system can change these flags and nothing else.
5676        if (getCallingUid() != Process.SYSTEM_UID) {
5677            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5678            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5679            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5680            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5681            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5682        }
5683
5684        synchronized (mPackages) {
5685            final PackageParser.Package pkg = mPackages.get(packageName);
5686            if (pkg == null) {
5687                throw new IllegalArgumentException("Unknown package: " + packageName);
5688            }
5689            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5690            if (ps == null
5691                    || filterAppAccessLPr(ps, callingUid, userId)) {
5692                throw new IllegalArgumentException("Unknown package: " + packageName);
5693            }
5694
5695            final BasePermission bp = mSettings.mPermissions.get(name);
5696            if (bp == null) {
5697                throw new IllegalArgumentException("Unknown permission: " + name);
5698            }
5699
5700            PermissionsState permissionsState = ps.getPermissionsState();
5701
5702            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5703
5704            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5705                // Install and runtime permissions are stored in different places,
5706                // so figure out what permission changed and persist the change.
5707                if (permissionsState.getInstallPermissionState(name) != null) {
5708                    scheduleWriteSettingsLocked();
5709                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5710                        || hadState) {
5711                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5712                }
5713            }
5714        }
5715    }
5716
5717    /**
5718     * Update the permission flags for all packages and runtime permissions of a user in order
5719     * to allow device or profile owner to remove POLICY_FIXED.
5720     */
5721    @Override
5722    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5723        if (!sUserManager.exists(userId)) {
5724            return;
5725        }
5726
5727        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5728
5729        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5730                true /* requireFullPermission */, true /* checkShell */,
5731                "updatePermissionFlagsForAllApps");
5732
5733        // Only the system can change system fixed flags.
5734        if (getCallingUid() != Process.SYSTEM_UID) {
5735            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5736            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5737        }
5738
5739        synchronized (mPackages) {
5740            boolean changed = false;
5741            final int packageCount = mPackages.size();
5742            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5743                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5744                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5745                if (ps == null) {
5746                    continue;
5747                }
5748                PermissionsState permissionsState = ps.getPermissionsState();
5749                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5750                        userId, flagMask, flagValues);
5751            }
5752            if (changed) {
5753                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5754            }
5755        }
5756    }
5757
5758    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5759        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5760                != PackageManager.PERMISSION_GRANTED
5761            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5762                != PackageManager.PERMISSION_GRANTED) {
5763            throw new SecurityException(message + " requires "
5764                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5765                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5766        }
5767    }
5768
5769    @Override
5770    public boolean shouldShowRequestPermissionRationale(String permissionName,
5771            String packageName, int userId) {
5772        if (UserHandle.getCallingUserId() != userId) {
5773            mContext.enforceCallingPermission(
5774                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5775                    "canShowRequestPermissionRationale for user " + userId);
5776        }
5777
5778        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5779        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5780            return false;
5781        }
5782
5783        if (checkPermission(permissionName, packageName, userId)
5784                == PackageManager.PERMISSION_GRANTED) {
5785            return false;
5786        }
5787
5788        final int flags;
5789
5790        final long identity = Binder.clearCallingIdentity();
5791        try {
5792            flags = getPermissionFlags(permissionName,
5793                    packageName, userId);
5794        } finally {
5795            Binder.restoreCallingIdentity(identity);
5796        }
5797
5798        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5799                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5800                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5801
5802        if ((flags & fixedFlags) != 0) {
5803            return false;
5804        }
5805
5806        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5807    }
5808
5809    @Override
5810    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5811        mContext.enforceCallingOrSelfPermission(
5812                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5813                "addOnPermissionsChangeListener");
5814
5815        synchronized (mPackages) {
5816            mOnPermissionChangeListeners.addListenerLocked(listener);
5817        }
5818    }
5819
5820    @Override
5821    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5822        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5823            throw new SecurityException("Instant applications don't have access to this method");
5824        }
5825        synchronized (mPackages) {
5826            mOnPermissionChangeListeners.removeListenerLocked(listener);
5827        }
5828    }
5829
5830    @Override
5831    public boolean isProtectedBroadcast(String actionName) {
5832        // allow instant applications
5833        synchronized (mProtectedBroadcasts) {
5834            if (mProtectedBroadcasts.contains(actionName)) {
5835                return true;
5836            } else if (actionName != null) {
5837                // TODO: remove these terrible hacks
5838                if (actionName.startsWith("android.net.netmon.lingerExpired")
5839                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5840                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5841                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5842                    return true;
5843                }
5844            }
5845        }
5846        return false;
5847    }
5848
5849    @Override
5850    public int checkSignatures(String pkg1, String pkg2) {
5851        synchronized (mPackages) {
5852            final PackageParser.Package p1 = mPackages.get(pkg1);
5853            final PackageParser.Package p2 = mPackages.get(pkg2);
5854            if (p1 == null || p1.mExtras == null
5855                    || p2 == null || p2.mExtras == null) {
5856                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5857            }
5858            final int callingUid = Binder.getCallingUid();
5859            final int callingUserId = UserHandle.getUserId(callingUid);
5860            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5861            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5862            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5863                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5864                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5865            }
5866            return compareSignatures(p1.mSignatures, p2.mSignatures);
5867        }
5868    }
5869
5870    @Override
5871    public int checkUidSignatures(int uid1, int uid2) {
5872        final int callingUid = Binder.getCallingUid();
5873        final int callingUserId = UserHandle.getUserId(callingUid);
5874        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5875        // Map to base uids.
5876        uid1 = UserHandle.getAppId(uid1);
5877        uid2 = UserHandle.getAppId(uid2);
5878        // reader
5879        synchronized (mPackages) {
5880            Signature[] s1;
5881            Signature[] s2;
5882            Object obj = mSettings.getUserIdLPr(uid1);
5883            if (obj != null) {
5884                if (obj instanceof SharedUserSetting) {
5885                    if (isCallerInstantApp) {
5886                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5887                    }
5888                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5889                } else if (obj instanceof PackageSetting) {
5890                    final PackageSetting ps = (PackageSetting) obj;
5891                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5892                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5893                    }
5894                    s1 = ps.signatures.mSignatures;
5895                } else {
5896                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5897                }
5898            } else {
5899                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5900            }
5901            obj = mSettings.getUserIdLPr(uid2);
5902            if (obj != null) {
5903                if (obj instanceof SharedUserSetting) {
5904                    if (isCallerInstantApp) {
5905                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5906                    }
5907                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5908                } else if (obj instanceof PackageSetting) {
5909                    final PackageSetting ps = (PackageSetting) obj;
5910                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5911                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5912                    }
5913                    s2 = ps.signatures.mSignatures;
5914                } else {
5915                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5916                }
5917            } else {
5918                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5919            }
5920            return compareSignatures(s1, s2);
5921        }
5922    }
5923
5924    /**
5925     * This method should typically only be used when granting or revoking
5926     * permissions, since the app may immediately restart after this call.
5927     * <p>
5928     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5929     * guard your work against the app being relaunched.
5930     */
5931    private void killUid(int appId, int userId, String reason) {
5932        final long identity = Binder.clearCallingIdentity();
5933        try {
5934            IActivityManager am = ActivityManager.getService();
5935            if (am != null) {
5936                try {
5937                    am.killUid(appId, userId, reason);
5938                } catch (RemoteException e) {
5939                    /* ignore - same process */
5940                }
5941            }
5942        } finally {
5943            Binder.restoreCallingIdentity(identity);
5944        }
5945    }
5946
5947    /**
5948     * Compares two sets of signatures. Returns:
5949     * <br />
5950     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5951     * <br />
5952     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5953     * <br />
5954     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5955     * <br />
5956     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5957     * <br />
5958     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5959     */
5960    static int compareSignatures(Signature[] s1, Signature[] s2) {
5961        if (s1 == null) {
5962            return s2 == null
5963                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5964                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5965        }
5966
5967        if (s2 == null) {
5968            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5969        }
5970
5971        if (s1.length != s2.length) {
5972            return PackageManager.SIGNATURE_NO_MATCH;
5973        }
5974
5975        // Since both signature sets are of size 1, we can compare without HashSets.
5976        if (s1.length == 1) {
5977            return s1[0].equals(s2[0]) ?
5978                    PackageManager.SIGNATURE_MATCH :
5979                    PackageManager.SIGNATURE_NO_MATCH;
5980        }
5981
5982        ArraySet<Signature> set1 = new ArraySet<Signature>();
5983        for (Signature sig : s1) {
5984            set1.add(sig);
5985        }
5986        ArraySet<Signature> set2 = new ArraySet<Signature>();
5987        for (Signature sig : s2) {
5988            set2.add(sig);
5989        }
5990        // Make sure s2 contains all signatures in s1.
5991        if (set1.equals(set2)) {
5992            return PackageManager.SIGNATURE_MATCH;
5993        }
5994        return PackageManager.SIGNATURE_NO_MATCH;
5995    }
5996
5997    /**
5998     * If the database version for this type of package (internal storage or
5999     * external storage) is less than the version where package signatures
6000     * were updated, return true.
6001     */
6002    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6003        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6004        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6005    }
6006
6007    /**
6008     * Used for backward compatibility to make sure any packages with
6009     * certificate chains get upgraded to the new style. {@code existingSigs}
6010     * will be in the old format (since they were stored on disk from before the
6011     * system upgrade) and {@code scannedSigs} will be in the newer format.
6012     */
6013    private int compareSignaturesCompat(PackageSignatures existingSigs,
6014            PackageParser.Package scannedPkg) {
6015        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6016            return PackageManager.SIGNATURE_NO_MATCH;
6017        }
6018
6019        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6020        for (Signature sig : existingSigs.mSignatures) {
6021            existingSet.add(sig);
6022        }
6023        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6024        for (Signature sig : scannedPkg.mSignatures) {
6025            try {
6026                Signature[] chainSignatures = sig.getChainSignatures();
6027                for (Signature chainSig : chainSignatures) {
6028                    scannedCompatSet.add(chainSig);
6029                }
6030            } catch (CertificateEncodingException e) {
6031                scannedCompatSet.add(sig);
6032            }
6033        }
6034        /*
6035         * Make sure the expanded scanned set contains all signatures in the
6036         * existing one.
6037         */
6038        if (scannedCompatSet.equals(existingSet)) {
6039            // Migrate the old signatures to the new scheme.
6040            existingSigs.assignSignatures(scannedPkg.mSignatures);
6041            // The new KeySets will be re-added later in the scanning process.
6042            synchronized (mPackages) {
6043                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6044            }
6045            return PackageManager.SIGNATURE_MATCH;
6046        }
6047        return PackageManager.SIGNATURE_NO_MATCH;
6048    }
6049
6050    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6051        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6052        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6053    }
6054
6055    private int compareSignaturesRecover(PackageSignatures existingSigs,
6056            PackageParser.Package scannedPkg) {
6057        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6058            return PackageManager.SIGNATURE_NO_MATCH;
6059        }
6060
6061        String msg = null;
6062        try {
6063            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6064                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6065                        + scannedPkg.packageName);
6066                return PackageManager.SIGNATURE_MATCH;
6067            }
6068        } catch (CertificateException e) {
6069            msg = e.getMessage();
6070        }
6071
6072        logCriticalInfo(Log.INFO,
6073                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6074        return PackageManager.SIGNATURE_NO_MATCH;
6075    }
6076
6077    @Override
6078    public List<String> getAllPackages() {
6079        final int callingUid = Binder.getCallingUid();
6080        final int callingUserId = UserHandle.getUserId(callingUid);
6081        synchronized (mPackages) {
6082            if (canViewInstantApps(callingUid, callingUserId)) {
6083                return new ArrayList<String>(mPackages.keySet());
6084            }
6085            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6086            final List<String> result = new ArrayList<>();
6087            if (instantAppPkgName != null) {
6088                // caller is an instant application; filter unexposed applications
6089                for (PackageParser.Package pkg : mPackages.values()) {
6090                    if (!pkg.visibleToInstantApps) {
6091                        continue;
6092                    }
6093                    result.add(pkg.packageName);
6094                }
6095            } else {
6096                // caller is a normal application; filter instant applications
6097                for (PackageParser.Package pkg : mPackages.values()) {
6098                    final PackageSetting ps =
6099                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6100                    if (ps != null
6101                            && ps.getInstantApp(callingUserId)
6102                            && !mInstantAppRegistry.isInstantAccessGranted(
6103                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6104                        continue;
6105                    }
6106                    result.add(pkg.packageName);
6107                }
6108            }
6109            return result;
6110        }
6111    }
6112
6113    @Override
6114    public String[] getPackagesForUid(int uid) {
6115        final int callingUid = Binder.getCallingUid();
6116        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6117        final int userId = UserHandle.getUserId(uid);
6118        uid = UserHandle.getAppId(uid);
6119        // reader
6120        synchronized (mPackages) {
6121            Object obj = mSettings.getUserIdLPr(uid);
6122            if (obj instanceof SharedUserSetting) {
6123                if (isCallerInstantApp) {
6124                    return null;
6125                }
6126                final SharedUserSetting sus = (SharedUserSetting) obj;
6127                final int N = sus.packages.size();
6128                String[] res = new String[N];
6129                final Iterator<PackageSetting> it = sus.packages.iterator();
6130                int i = 0;
6131                while (it.hasNext()) {
6132                    PackageSetting ps = it.next();
6133                    if (ps.getInstalled(userId)) {
6134                        res[i++] = ps.name;
6135                    } else {
6136                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6137                    }
6138                }
6139                return res;
6140            } else if (obj instanceof PackageSetting) {
6141                final PackageSetting ps = (PackageSetting) obj;
6142                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6143                    return new String[]{ps.name};
6144                }
6145            }
6146        }
6147        return null;
6148    }
6149
6150    @Override
6151    public String getNameForUid(int uid) {
6152        final int callingUid = Binder.getCallingUid();
6153        if (getInstantAppPackageName(callingUid) != null) {
6154            return null;
6155        }
6156        synchronized (mPackages) {
6157            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6158            if (obj instanceof SharedUserSetting) {
6159                final SharedUserSetting sus = (SharedUserSetting) obj;
6160                return sus.name + ":" + sus.userId;
6161            } else if (obj instanceof PackageSetting) {
6162                final PackageSetting ps = (PackageSetting) obj;
6163                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6164                    return null;
6165                }
6166                return ps.name;
6167            }
6168        }
6169        return null;
6170    }
6171
6172    @Override
6173    public int getUidForSharedUser(String sharedUserName) {
6174        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6175            return -1;
6176        }
6177        if (sharedUserName == null) {
6178            return -1;
6179        }
6180        // reader
6181        synchronized (mPackages) {
6182            SharedUserSetting suid;
6183            try {
6184                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6185                if (suid != null) {
6186                    return suid.userId;
6187                }
6188            } catch (PackageManagerException ignore) {
6189                // can't happen, but, still need to catch it
6190            }
6191            return -1;
6192        }
6193    }
6194
6195    @Override
6196    public int getFlagsForUid(int uid) {
6197        final int callingUid = Binder.getCallingUid();
6198        if (getInstantAppPackageName(callingUid) != null) {
6199            return 0;
6200        }
6201        synchronized (mPackages) {
6202            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6203            if (obj instanceof SharedUserSetting) {
6204                final SharedUserSetting sus = (SharedUserSetting) obj;
6205                return sus.pkgFlags;
6206            } else if (obj instanceof PackageSetting) {
6207                final PackageSetting ps = (PackageSetting) obj;
6208                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6209                    return 0;
6210                }
6211                return ps.pkgFlags;
6212            }
6213        }
6214        return 0;
6215    }
6216
6217    @Override
6218    public int getPrivateFlagsForUid(int uid) {
6219        final int callingUid = Binder.getCallingUid();
6220        if (getInstantAppPackageName(callingUid) != null) {
6221            return 0;
6222        }
6223        synchronized (mPackages) {
6224            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6225            if (obj instanceof SharedUserSetting) {
6226                final SharedUserSetting sus = (SharedUserSetting) obj;
6227                return sus.pkgPrivateFlags;
6228            } else if (obj instanceof PackageSetting) {
6229                final PackageSetting ps = (PackageSetting) obj;
6230                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6231                    return 0;
6232                }
6233                return ps.pkgPrivateFlags;
6234            }
6235        }
6236        return 0;
6237    }
6238
6239    @Override
6240    public boolean isUidPrivileged(int uid) {
6241        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6242            return false;
6243        }
6244        uid = UserHandle.getAppId(uid);
6245        // reader
6246        synchronized (mPackages) {
6247            Object obj = mSettings.getUserIdLPr(uid);
6248            if (obj instanceof SharedUserSetting) {
6249                final SharedUserSetting sus = (SharedUserSetting) obj;
6250                final Iterator<PackageSetting> it = sus.packages.iterator();
6251                while (it.hasNext()) {
6252                    if (it.next().isPrivileged()) {
6253                        return true;
6254                    }
6255                }
6256            } else if (obj instanceof PackageSetting) {
6257                final PackageSetting ps = (PackageSetting) obj;
6258                return ps.isPrivileged();
6259            }
6260        }
6261        return false;
6262    }
6263
6264    @Override
6265    public String[] getAppOpPermissionPackages(String permissionName) {
6266        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6267            return null;
6268        }
6269        synchronized (mPackages) {
6270            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6271            if (pkgs == null) {
6272                return null;
6273            }
6274            return pkgs.toArray(new String[pkgs.size()]);
6275        }
6276    }
6277
6278    @Override
6279    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6280            int flags, int userId) {
6281        return resolveIntentInternal(
6282                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6283    }
6284
6285    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6286            int flags, int userId, boolean resolveForStart) {
6287        try {
6288            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6289
6290            if (!sUserManager.exists(userId)) return null;
6291            final int callingUid = Binder.getCallingUid();
6292            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6293            enforceCrossUserPermission(callingUid, userId,
6294                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6295
6296            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6297            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6298                    flags, callingUid, userId, resolveForStart);
6299            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6300
6301            final ResolveInfo bestChoice =
6302                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6303            return bestChoice;
6304        } finally {
6305            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6306        }
6307    }
6308
6309    @Override
6310    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6311        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6312            throw new SecurityException(
6313                    "findPersistentPreferredActivity can only be run by the system");
6314        }
6315        if (!sUserManager.exists(userId)) {
6316            return null;
6317        }
6318        final int callingUid = Binder.getCallingUid();
6319        intent = updateIntentForResolve(intent);
6320        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6321        final int flags = updateFlagsForResolve(
6322                0, userId, intent, callingUid, false /*includeInstantApps*/);
6323        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6324                userId);
6325        synchronized (mPackages) {
6326            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6327                    userId);
6328        }
6329    }
6330
6331    @Override
6332    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6333            IntentFilter filter, int match, ComponentName activity) {
6334        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6335            return;
6336        }
6337        final int userId = UserHandle.getCallingUserId();
6338        if (DEBUG_PREFERRED) {
6339            Log.v(TAG, "setLastChosenActivity intent=" + intent
6340                + " resolvedType=" + resolvedType
6341                + " flags=" + flags
6342                + " filter=" + filter
6343                + " match=" + match
6344                + " activity=" + activity);
6345            filter.dump(new PrintStreamPrinter(System.out), "    ");
6346        }
6347        intent.setComponent(null);
6348        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6349                userId);
6350        // Find any earlier preferred or last chosen entries and nuke them
6351        findPreferredActivity(intent, resolvedType,
6352                flags, query, 0, false, true, false, userId);
6353        // Add the new activity as the last chosen for this filter
6354        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6355                "Setting last chosen");
6356    }
6357
6358    @Override
6359    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6360        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6361            return null;
6362        }
6363        final int userId = UserHandle.getCallingUserId();
6364        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6365        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6366                userId);
6367        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6368                false, false, false, userId);
6369    }
6370
6371    /**
6372     * Returns whether or not instant apps have been disabled remotely.
6373     */
6374    private boolean isEphemeralDisabled() {
6375        return mEphemeralAppsDisabled;
6376    }
6377
6378    private boolean isInstantAppAllowed(
6379            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6380            boolean skipPackageCheck) {
6381        if (mInstantAppResolverConnection == null) {
6382            return false;
6383        }
6384        if (mInstantAppInstallerActivity == null) {
6385            return false;
6386        }
6387        if (intent.getComponent() != null) {
6388            return false;
6389        }
6390        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6391            return false;
6392        }
6393        if (!skipPackageCheck && intent.getPackage() != null) {
6394            return false;
6395        }
6396        final boolean isWebUri = hasWebURI(intent);
6397        if (!isWebUri || intent.getData().getHost() == null) {
6398            return false;
6399        }
6400        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6401        // Or if there's already an ephemeral app installed that handles the action
6402        synchronized (mPackages) {
6403            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6404            for (int n = 0; n < count; n++) {
6405                final ResolveInfo info = resolvedActivities.get(n);
6406                final String packageName = info.activityInfo.packageName;
6407                final PackageSetting ps = mSettings.mPackages.get(packageName);
6408                if (ps != null) {
6409                    // only check domain verification status if the app is not a browser
6410                    if (!info.handleAllWebDataURI) {
6411                        // Try to get the status from User settings first
6412                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6413                        final int status = (int) (packedStatus >> 32);
6414                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6415                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6416                            if (DEBUG_EPHEMERAL) {
6417                                Slog.v(TAG, "DENY instant app;"
6418                                    + " pkg: " + packageName + ", status: " + status);
6419                            }
6420                            return false;
6421                        }
6422                    }
6423                    if (ps.getInstantApp(userId)) {
6424                        if (DEBUG_EPHEMERAL) {
6425                            Slog.v(TAG, "DENY instant app installed;"
6426                                    + " pkg: " + packageName);
6427                        }
6428                        return false;
6429                    }
6430                }
6431            }
6432        }
6433        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6434        return true;
6435    }
6436
6437    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6438            Intent origIntent, String resolvedType, String callingPackage,
6439            Bundle verificationBundle, int userId) {
6440        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6441                new InstantAppRequest(responseObj, origIntent, resolvedType,
6442                        callingPackage, userId, verificationBundle));
6443        mHandler.sendMessage(msg);
6444    }
6445
6446    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6447            int flags, List<ResolveInfo> query, int userId) {
6448        if (query != null) {
6449            final int N = query.size();
6450            if (N == 1) {
6451                return query.get(0);
6452            } else if (N > 1) {
6453                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6454                // If there is more than one activity with the same priority,
6455                // then let the user decide between them.
6456                ResolveInfo r0 = query.get(0);
6457                ResolveInfo r1 = query.get(1);
6458                if (DEBUG_INTENT_MATCHING || debug) {
6459                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6460                            + r1.activityInfo.name + "=" + r1.priority);
6461                }
6462                // If the first activity has a higher priority, or a different
6463                // default, then it is always desirable to pick it.
6464                if (r0.priority != r1.priority
6465                        || r0.preferredOrder != r1.preferredOrder
6466                        || r0.isDefault != r1.isDefault) {
6467                    return query.get(0);
6468                }
6469                // If we have saved a preference for a preferred activity for
6470                // this Intent, use that.
6471                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6472                        flags, query, r0.priority, true, false, debug, userId);
6473                if (ri != null) {
6474                    return ri;
6475                }
6476                // If we have an ephemeral app, use it
6477                for (int i = 0; i < N; i++) {
6478                    ri = query.get(i);
6479                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6480                        final String packageName = ri.activityInfo.packageName;
6481                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6482                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6483                        final int status = (int)(packedStatus >> 32);
6484                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6485                            return ri;
6486                        }
6487                    }
6488                }
6489                ri = new ResolveInfo(mResolveInfo);
6490                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6491                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6492                // If all of the options come from the same package, show the application's
6493                // label and icon instead of the generic resolver's.
6494                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6495                // and then throw away the ResolveInfo itself, meaning that the caller loses
6496                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6497                // a fallback for this case; we only set the target package's resources on
6498                // the ResolveInfo, not the ActivityInfo.
6499                final String intentPackage = intent.getPackage();
6500                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6501                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6502                    ri.resolvePackageName = intentPackage;
6503                    if (userNeedsBadging(userId)) {
6504                        ri.noResourceId = true;
6505                    } else {
6506                        ri.icon = appi.icon;
6507                    }
6508                    ri.iconResourceId = appi.icon;
6509                    ri.labelRes = appi.labelRes;
6510                }
6511                ri.activityInfo.applicationInfo = new ApplicationInfo(
6512                        ri.activityInfo.applicationInfo);
6513                if (userId != 0) {
6514                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6515                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6516                }
6517                // Make sure that the resolver is displayable in car mode
6518                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6519                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6520                return ri;
6521            }
6522        }
6523        return null;
6524    }
6525
6526    /**
6527     * Return true if the given list is not empty and all of its contents have
6528     * an activityInfo with the given package name.
6529     */
6530    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6531        if (ArrayUtils.isEmpty(list)) {
6532            return false;
6533        }
6534        for (int i = 0, N = list.size(); i < N; i++) {
6535            final ResolveInfo ri = list.get(i);
6536            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6537            if (ai == null || !packageName.equals(ai.packageName)) {
6538                return false;
6539            }
6540        }
6541        return true;
6542    }
6543
6544    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6545            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6546        final int N = query.size();
6547        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6548                .get(userId);
6549        // Get the list of persistent preferred activities that handle the intent
6550        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6551        List<PersistentPreferredActivity> pprefs = ppir != null
6552                ? ppir.queryIntent(intent, resolvedType,
6553                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6554                        userId)
6555                : null;
6556        if (pprefs != null && pprefs.size() > 0) {
6557            final int M = pprefs.size();
6558            for (int i=0; i<M; i++) {
6559                final PersistentPreferredActivity ppa = pprefs.get(i);
6560                if (DEBUG_PREFERRED || debug) {
6561                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6562                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6563                            + "\n  component=" + ppa.mComponent);
6564                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6565                }
6566                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6567                        flags | MATCH_DISABLED_COMPONENTS, userId);
6568                if (DEBUG_PREFERRED || debug) {
6569                    Slog.v(TAG, "Found persistent preferred activity:");
6570                    if (ai != null) {
6571                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6572                    } else {
6573                        Slog.v(TAG, "  null");
6574                    }
6575                }
6576                if (ai == null) {
6577                    // This previously registered persistent preferred activity
6578                    // component is no longer known. Ignore it and do NOT remove it.
6579                    continue;
6580                }
6581                for (int j=0; j<N; j++) {
6582                    final ResolveInfo ri = query.get(j);
6583                    if (!ri.activityInfo.applicationInfo.packageName
6584                            .equals(ai.applicationInfo.packageName)) {
6585                        continue;
6586                    }
6587                    if (!ri.activityInfo.name.equals(ai.name)) {
6588                        continue;
6589                    }
6590                    //  Found a persistent preference that can handle the intent.
6591                    if (DEBUG_PREFERRED || debug) {
6592                        Slog.v(TAG, "Returning persistent preferred activity: " +
6593                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6594                    }
6595                    return ri;
6596                }
6597            }
6598        }
6599        return null;
6600    }
6601
6602    // TODO: handle preferred activities missing while user has amnesia
6603    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6604            List<ResolveInfo> query, int priority, boolean always,
6605            boolean removeMatches, boolean debug, int userId) {
6606        if (!sUserManager.exists(userId)) return null;
6607        final int callingUid = Binder.getCallingUid();
6608        flags = updateFlagsForResolve(
6609                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6610        intent = updateIntentForResolve(intent);
6611        // writer
6612        synchronized (mPackages) {
6613            // Try to find a matching persistent preferred activity.
6614            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6615                    debug, userId);
6616
6617            // If a persistent preferred activity matched, use it.
6618            if (pri != null) {
6619                return pri;
6620            }
6621
6622            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6623            // Get the list of preferred activities that handle the intent
6624            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6625            List<PreferredActivity> prefs = pir != null
6626                    ? pir.queryIntent(intent, resolvedType,
6627                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6628                            userId)
6629                    : null;
6630            if (prefs != null && prefs.size() > 0) {
6631                boolean changed = false;
6632                try {
6633                    // First figure out how good the original match set is.
6634                    // We will only allow preferred activities that came
6635                    // from the same match quality.
6636                    int match = 0;
6637
6638                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6639
6640                    final int N = query.size();
6641                    for (int j=0; j<N; j++) {
6642                        final ResolveInfo ri = query.get(j);
6643                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6644                                + ": 0x" + Integer.toHexString(match));
6645                        if (ri.match > match) {
6646                            match = ri.match;
6647                        }
6648                    }
6649
6650                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6651                            + Integer.toHexString(match));
6652
6653                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6654                    final int M = prefs.size();
6655                    for (int i=0; i<M; i++) {
6656                        final PreferredActivity pa = prefs.get(i);
6657                        if (DEBUG_PREFERRED || debug) {
6658                            Slog.v(TAG, "Checking PreferredActivity ds="
6659                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6660                                    + "\n  component=" + pa.mPref.mComponent);
6661                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6662                        }
6663                        if (pa.mPref.mMatch != match) {
6664                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6665                                    + Integer.toHexString(pa.mPref.mMatch));
6666                            continue;
6667                        }
6668                        // If it's not an "always" type preferred activity and that's what we're
6669                        // looking for, skip it.
6670                        if (always && !pa.mPref.mAlways) {
6671                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6672                            continue;
6673                        }
6674                        final ActivityInfo ai = getActivityInfo(
6675                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6676                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6677                                userId);
6678                        if (DEBUG_PREFERRED || debug) {
6679                            Slog.v(TAG, "Found preferred activity:");
6680                            if (ai != null) {
6681                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6682                            } else {
6683                                Slog.v(TAG, "  null");
6684                            }
6685                        }
6686                        if (ai == null) {
6687                            // This previously registered preferred activity
6688                            // component is no longer known.  Most likely an update
6689                            // to the app was installed and in the new version this
6690                            // component no longer exists.  Clean it up by removing
6691                            // it from the preferred activities list, and skip it.
6692                            Slog.w(TAG, "Removing dangling preferred activity: "
6693                                    + pa.mPref.mComponent);
6694                            pir.removeFilter(pa);
6695                            changed = true;
6696                            continue;
6697                        }
6698                        for (int j=0; j<N; j++) {
6699                            final ResolveInfo ri = query.get(j);
6700                            if (!ri.activityInfo.applicationInfo.packageName
6701                                    .equals(ai.applicationInfo.packageName)) {
6702                                continue;
6703                            }
6704                            if (!ri.activityInfo.name.equals(ai.name)) {
6705                                continue;
6706                            }
6707
6708                            if (removeMatches) {
6709                                pir.removeFilter(pa);
6710                                changed = true;
6711                                if (DEBUG_PREFERRED) {
6712                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6713                                }
6714                                break;
6715                            }
6716
6717                            // Okay we found a previously set preferred or last chosen app.
6718                            // If the result set is different from when this
6719                            // was created, we need to clear it and re-ask the
6720                            // user their preference, if we're looking for an "always" type entry.
6721                            if (always && !pa.mPref.sameSet(query)) {
6722                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6723                                        + intent + " type " + resolvedType);
6724                                if (DEBUG_PREFERRED) {
6725                                    Slog.v(TAG, "Removing preferred activity since set changed "
6726                                            + pa.mPref.mComponent);
6727                                }
6728                                pir.removeFilter(pa);
6729                                // Re-add the filter as a "last chosen" entry (!always)
6730                                PreferredActivity lastChosen = new PreferredActivity(
6731                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6732                                pir.addFilter(lastChosen);
6733                                changed = true;
6734                                return null;
6735                            }
6736
6737                            // Yay! Either the set matched or we're looking for the last chosen
6738                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6739                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6740                            return ri;
6741                        }
6742                    }
6743                } finally {
6744                    if (changed) {
6745                        if (DEBUG_PREFERRED) {
6746                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6747                        }
6748                        scheduleWritePackageRestrictionsLocked(userId);
6749                    }
6750                }
6751            }
6752        }
6753        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6754        return null;
6755    }
6756
6757    /*
6758     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6759     */
6760    @Override
6761    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6762            int targetUserId) {
6763        mContext.enforceCallingOrSelfPermission(
6764                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6765        List<CrossProfileIntentFilter> matches =
6766                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6767        if (matches != null) {
6768            int size = matches.size();
6769            for (int i = 0; i < size; i++) {
6770                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6771            }
6772        }
6773        if (hasWebURI(intent)) {
6774            // cross-profile app linking works only towards the parent.
6775            final int callingUid = Binder.getCallingUid();
6776            final UserInfo parent = getProfileParent(sourceUserId);
6777            synchronized(mPackages) {
6778                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6779                        false /*includeInstantApps*/);
6780                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6781                        intent, resolvedType, flags, sourceUserId, parent.id);
6782                return xpDomainInfo != null;
6783            }
6784        }
6785        return false;
6786    }
6787
6788    private UserInfo getProfileParent(int userId) {
6789        final long identity = Binder.clearCallingIdentity();
6790        try {
6791            return sUserManager.getProfileParent(userId);
6792        } finally {
6793            Binder.restoreCallingIdentity(identity);
6794        }
6795    }
6796
6797    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6798            String resolvedType, int userId) {
6799        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6800        if (resolver != null) {
6801            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6802        }
6803        return null;
6804    }
6805
6806    @Override
6807    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6808            String resolvedType, int flags, int userId) {
6809        try {
6810            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6811
6812            return new ParceledListSlice<>(
6813                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6814        } finally {
6815            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6816        }
6817    }
6818
6819    /**
6820     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6821     * instant, returns {@code null}.
6822     */
6823    private String getInstantAppPackageName(int callingUid) {
6824        synchronized (mPackages) {
6825            // If the caller is an isolated app use the owner's uid for the lookup.
6826            if (Process.isIsolated(callingUid)) {
6827                callingUid = mIsolatedOwners.get(callingUid);
6828            }
6829            final int appId = UserHandle.getAppId(callingUid);
6830            final Object obj = mSettings.getUserIdLPr(appId);
6831            if (obj instanceof PackageSetting) {
6832                final PackageSetting ps = (PackageSetting) obj;
6833                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6834                return isInstantApp ? ps.pkg.packageName : null;
6835            }
6836        }
6837        return null;
6838    }
6839
6840    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6841            String resolvedType, int flags, int userId) {
6842        return queryIntentActivitiesInternal(
6843                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6844    }
6845
6846    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6847            String resolvedType, int flags, int filterCallingUid, int userId,
6848            boolean resolveForStart) {
6849        if (!sUserManager.exists(userId)) return Collections.emptyList();
6850        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6851        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6852                false /* requireFullPermission */, false /* checkShell */,
6853                "query intent activities");
6854        final String pkgName = intent.getPackage();
6855        ComponentName comp = intent.getComponent();
6856        if (comp == null) {
6857            if (intent.getSelector() != null) {
6858                intent = intent.getSelector();
6859                comp = intent.getComponent();
6860            }
6861        }
6862
6863        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6864                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6865        if (comp != null) {
6866            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6867            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6868            if (ai != null) {
6869                // When specifying an explicit component, we prevent the activity from being
6870                // used when either 1) the calling package is normal and the activity is within
6871                // an ephemeral application or 2) the calling package is ephemeral and the
6872                // activity is not visible to ephemeral applications.
6873                final boolean matchInstantApp =
6874                        (flags & PackageManager.MATCH_INSTANT) != 0;
6875                final boolean matchVisibleToInstantAppOnly =
6876                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6877                final boolean matchExplicitlyVisibleOnly =
6878                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6879                final boolean isCallerInstantApp =
6880                        instantAppPkgName != null;
6881                final boolean isTargetSameInstantApp =
6882                        comp.getPackageName().equals(instantAppPkgName);
6883                final boolean isTargetInstantApp =
6884                        (ai.applicationInfo.privateFlags
6885                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6886                final boolean isTargetVisibleToInstantApp =
6887                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6888                final boolean isTargetExplicitlyVisibleToInstantApp =
6889                        isTargetVisibleToInstantApp
6890                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6891                final boolean isTargetHiddenFromInstantApp =
6892                        !isTargetVisibleToInstantApp
6893                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6894                final boolean blockResolution =
6895                        !isTargetSameInstantApp
6896                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6897                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6898                                        && isTargetHiddenFromInstantApp));
6899                if (!blockResolution) {
6900                    final ResolveInfo ri = new ResolveInfo();
6901                    ri.activityInfo = ai;
6902                    list.add(ri);
6903                }
6904            }
6905            return applyPostResolutionFilter(list, instantAppPkgName);
6906        }
6907
6908        // reader
6909        boolean sortResult = false;
6910        boolean addEphemeral = false;
6911        List<ResolveInfo> result;
6912        final boolean ephemeralDisabled = isEphemeralDisabled();
6913        synchronized (mPackages) {
6914            if (pkgName == null) {
6915                List<CrossProfileIntentFilter> matchingFilters =
6916                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6917                // Check for results that need to skip the current profile.
6918                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6919                        resolvedType, flags, userId);
6920                if (xpResolveInfo != null) {
6921                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6922                    xpResult.add(xpResolveInfo);
6923                    return applyPostResolutionFilter(
6924                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6925                }
6926
6927                // Check for results in the current profile.
6928                result = filterIfNotSystemUser(mActivities.queryIntent(
6929                        intent, resolvedType, flags, userId), userId);
6930                addEphemeral = !ephemeralDisabled
6931                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6932                // Check for cross profile results.
6933                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6934                xpResolveInfo = queryCrossProfileIntents(
6935                        matchingFilters, intent, resolvedType, flags, userId,
6936                        hasNonNegativePriorityResult);
6937                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6938                    boolean isVisibleToUser = filterIfNotSystemUser(
6939                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6940                    if (isVisibleToUser) {
6941                        result.add(xpResolveInfo);
6942                        sortResult = true;
6943                    }
6944                }
6945                if (hasWebURI(intent)) {
6946                    CrossProfileDomainInfo xpDomainInfo = null;
6947                    final UserInfo parent = getProfileParent(userId);
6948                    if (parent != null) {
6949                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6950                                flags, userId, parent.id);
6951                    }
6952                    if (xpDomainInfo != null) {
6953                        if (xpResolveInfo != null) {
6954                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6955                            // in the result.
6956                            result.remove(xpResolveInfo);
6957                        }
6958                        if (result.size() == 0 && !addEphemeral) {
6959                            // No result in current profile, but found candidate in parent user.
6960                            // And we are not going to add emphemeral app, so we can return the
6961                            // result straight away.
6962                            result.add(xpDomainInfo.resolveInfo);
6963                            return applyPostResolutionFilter(result, instantAppPkgName);
6964                        }
6965                    } else if (result.size() <= 1 && !addEphemeral) {
6966                        // No result in parent user and <= 1 result in current profile, and we
6967                        // are not going to add emphemeral app, so we can return the result without
6968                        // further processing.
6969                        return applyPostResolutionFilter(result, instantAppPkgName);
6970                    }
6971                    // We have more than one candidate (combining results from current and parent
6972                    // profile), so we need filtering and sorting.
6973                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6974                            intent, flags, result, xpDomainInfo, userId);
6975                    sortResult = true;
6976                }
6977            } else {
6978                final PackageParser.Package pkg = mPackages.get(pkgName);
6979                result = null;
6980                if (pkg != null) {
6981                    result = filterIfNotSystemUser(
6982                            mActivities.queryIntentForPackage(
6983                                    intent, resolvedType, flags, pkg.activities, userId),
6984                            userId);
6985                }
6986                if (result == null || result.size() == 0) {
6987                    // the caller wants to resolve for a particular package; however, there
6988                    // were no installed results, so, try to find an ephemeral result
6989                    addEphemeral = !ephemeralDisabled
6990                            && isInstantAppAllowed(
6991                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6992                    if (result == null) {
6993                        result = new ArrayList<>();
6994                    }
6995                }
6996            }
6997        }
6998        if (addEphemeral) {
6999            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7000        }
7001        if (sortResult) {
7002            Collections.sort(result, mResolvePrioritySorter);
7003        }
7004        return applyPostResolutionFilter(result, instantAppPkgName);
7005    }
7006
7007    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7008            String resolvedType, int flags, int userId) {
7009        // first, check to see if we've got an instant app already installed
7010        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7011        ResolveInfo localInstantApp = null;
7012        boolean blockResolution = false;
7013        if (!alreadyResolvedLocally) {
7014            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7015                    flags
7016                        | PackageManager.GET_RESOLVED_FILTER
7017                        | PackageManager.MATCH_INSTANT
7018                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7019                    userId);
7020            for (int i = instantApps.size() - 1; i >= 0; --i) {
7021                final ResolveInfo info = instantApps.get(i);
7022                final String packageName = info.activityInfo.packageName;
7023                final PackageSetting ps = mSettings.mPackages.get(packageName);
7024                if (ps.getInstantApp(userId)) {
7025                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7026                    final int status = (int)(packedStatus >> 32);
7027                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7028                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7029                        // there's a local instant application installed, but, the user has
7030                        // chosen to never use it; skip resolution and don't acknowledge
7031                        // an instant application is even available
7032                        if (DEBUG_EPHEMERAL) {
7033                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7034                        }
7035                        blockResolution = true;
7036                        break;
7037                    } else {
7038                        // we have a locally installed instant application; skip resolution
7039                        // but acknowledge there's an instant application available
7040                        if (DEBUG_EPHEMERAL) {
7041                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7042                        }
7043                        localInstantApp = info;
7044                        break;
7045                    }
7046                }
7047            }
7048        }
7049        // no app installed, let's see if one's available
7050        AuxiliaryResolveInfo auxiliaryResponse = null;
7051        if (!blockResolution) {
7052            if (localInstantApp == null) {
7053                // we don't have an instant app locally, resolve externally
7054                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7055                final InstantAppRequest requestObject = new InstantAppRequest(
7056                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7057                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7058                auxiliaryResponse =
7059                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7060                                mContext, mInstantAppResolverConnection, requestObject);
7061                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7062            } else {
7063                // we have an instant application locally, but, we can't admit that since
7064                // callers shouldn't be able to determine prior browsing. create a dummy
7065                // auxiliary response so the downstream code behaves as if there's an
7066                // instant application available externally. when it comes time to start
7067                // the instant application, we'll do the right thing.
7068                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7069                auxiliaryResponse = new AuxiliaryResolveInfo(
7070                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7071            }
7072        }
7073        if (auxiliaryResponse != null) {
7074            if (DEBUG_EPHEMERAL) {
7075                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7076            }
7077            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7078            final PackageSetting ps =
7079                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7080            if (ps != null) {
7081                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7082                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7083                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7084                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7085                // make sure this resolver is the default
7086                ephemeralInstaller.isDefault = true;
7087                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7088                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7089                // add a non-generic filter
7090                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7091                ephemeralInstaller.filter.addDataPath(
7092                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7093                ephemeralInstaller.isInstantAppAvailable = true;
7094                result.add(ephemeralInstaller);
7095            }
7096        }
7097        return result;
7098    }
7099
7100    private static class CrossProfileDomainInfo {
7101        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7102        ResolveInfo resolveInfo;
7103        /* Best domain verification status of the activities found in the other profile */
7104        int bestDomainVerificationStatus;
7105    }
7106
7107    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7108            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7109        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7110                sourceUserId)) {
7111            return null;
7112        }
7113        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7114                resolvedType, flags, parentUserId);
7115
7116        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7117            return null;
7118        }
7119        CrossProfileDomainInfo result = null;
7120        int size = resultTargetUser.size();
7121        for (int i = 0; i < size; i++) {
7122            ResolveInfo riTargetUser = resultTargetUser.get(i);
7123            // Intent filter verification is only for filters that specify a host. So don't return
7124            // those that handle all web uris.
7125            if (riTargetUser.handleAllWebDataURI) {
7126                continue;
7127            }
7128            String packageName = riTargetUser.activityInfo.packageName;
7129            PackageSetting ps = mSettings.mPackages.get(packageName);
7130            if (ps == null) {
7131                continue;
7132            }
7133            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7134            int status = (int)(verificationState >> 32);
7135            if (result == null) {
7136                result = new CrossProfileDomainInfo();
7137                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7138                        sourceUserId, parentUserId);
7139                result.bestDomainVerificationStatus = status;
7140            } else {
7141                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7142                        result.bestDomainVerificationStatus);
7143            }
7144        }
7145        // Don't consider matches with status NEVER across profiles.
7146        if (result != null && result.bestDomainVerificationStatus
7147                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7148            return null;
7149        }
7150        return result;
7151    }
7152
7153    /**
7154     * Verification statuses are ordered from the worse to the best, except for
7155     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7156     */
7157    private int bestDomainVerificationStatus(int status1, int status2) {
7158        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7159            return status2;
7160        }
7161        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7162            return status1;
7163        }
7164        return (int) MathUtils.max(status1, status2);
7165    }
7166
7167    private boolean isUserEnabled(int userId) {
7168        long callingId = Binder.clearCallingIdentity();
7169        try {
7170            UserInfo userInfo = sUserManager.getUserInfo(userId);
7171            return userInfo != null && userInfo.isEnabled();
7172        } finally {
7173            Binder.restoreCallingIdentity(callingId);
7174        }
7175    }
7176
7177    /**
7178     * Filter out activities with systemUserOnly flag set, when current user is not System.
7179     *
7180     * @return filtered list
7181     */
7182    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7183        if (userId == UserHandle.USER_SYSTEM) {
7184            return resolveInfos;
7185        }
7186        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7187            ResolveInfo info = resolveInfos.get(i);
7188            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7189                resolveInfos.remove(i);
7190            }
7191        }
7192        return resolveInfos;
7193    }
7194
7195    /**
7196     * Filters out ephemeral activities.
7197     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7198     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7199     *
7200     * @param resolveInfos The pre-filtered list of resolved activities
7201     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7202     *          is performed.
7203     * @return A filtered list of resolved activities.
7204     */
7205    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7206            String ephemeralPkgName) {
7207        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7208            final ResolveInfo info = resolveInfos.get(i);
7209            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7210            // TODO: When adding on-demand split support for non-instant apps, remove this check
7211            // and always apply post filtering
7212            // allow activities that are defined in the provided package
7213            if (isEphemeralApp) {
7214                if (info.activityInfo.splitName != null
7215                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7216                                info.activityInfo.splitName)) {
7217                    // requested activity is defined in a split that hasn't been installed yet.
7218                    // add the installer to the resolve list
7219                    if (DEBUG_EPHEMERAL) {
7220                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7221                    }
7222                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7223                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7224                            info.activityInfo.packageName, info.activityInfo.splitName,
7225                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7226                    // make sure this resolver is the default
7227                    installerInfo.isDefault = true;
7228                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7229                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7230                    // add a non-generic filter
7231                    installerInfo.filter = new IntentFilter();
7232                    // load resources from the correct package
7233                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7234                    resolveInfos.set(i, installerInfo);
7235                    continue;
7236                }
7237            }
7238            // caller is a full app, don't need to apply any other filtering
7239            if (ephemeralPkgName == null) {
7240                continue;
7241            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7242                // caller is same app; don't need to apply any other filtering
7243                continue;
7244            }
7245            // allow activities that have been explicitly exposed to ephemeral apps
7246            if (!isEphemeralApp
7247                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7248                continue;
7249            }
7250            resolveInfos.remove(i);
7251        }
7252        return resolveInfos;
7253    }
7254
7255    /**
7256     * @param resolveInfos list of resolve infos in descending priority order
7257     * @return if the list contains a resolve info with non-negative priority
7258     */
7259    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7260        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7261    }
7262
7263    private static boolean hasWebURI(Intent intent) {
7264        if (intent.getData() == null) {
7265            return false;
7266        }
7267        final String scheme = intent.getScheme();
7268        if (TextUtils.isEmpty(scheme)) {
7269            return false;
7270        }
7271        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7272    }
7273
7274    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7275            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7276            int userId) {
7277        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7278
7279        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7280            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7281                    candidates.size());
7282        }
7283
7284        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7285        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7286        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7287        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7288        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7289        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7290
7291        synchronized (mPackages) {
7292            final int count = candidates.size();
7293            // First, try to use linked apps. Partition the candidates into four lists:
7294            // one for the final results, one for the "do not use ever", one for "undefined status"
7295            // and finally one for "browser app type".
7296            for (int n=0; n<count; n++) {
7297                ResolveInfo info = candidates.get(n);
7298                String packageName = info.activityInfo.packageName;
7299                PackageSetting ps = mSettings.mPackages.get(packageName);
7300                if (ps != null) {
7301                    // Add to the special match all list (Browser use case)
7302                    if (info.handleAllWebDataURI) {
7303                        matchAllList.add(info);
7304                        continue;
7305                    }
7306                    // Try to get the status from User settings first
7307                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7308                    int status = (int)(packedStatus >> 32);
7309                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7310                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7311                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7312                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7313                                    + " : linkgen=" + linkGeneration);
7314                        }
7315                        // Use link-enabled generation as preferredOrder, i.e.
7316                        // prefer newly-enabled over earlier-enabled.
7317                        info.preferredOrder = linkGeneration;
7318                        alwaysList.add(info);
7319                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7320                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7321                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7322                        }
7323                        neverList.add(info);
7324                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7325                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7326                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7327                        }
7328                        alwaysAskList.add(info);
7329                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7330                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7331                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7332                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7333                        }
7334                        undefinedList.add(info);
7335                    }
7336                }
7337            }
7338
7339            // We'll want to include browser possibilities in a few cases
7340            boolean includeBrowser = false;
7341
7342            // First try to add the "always" resolution(s) for the current user, if any
7343            if (alwaysList.size() > 0) {
7344                result.addAll(alwaysList);
7345            } else {
7346                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7347                result.addAll(undefinedList);
7348                // Maybe add one for the other profile.
7349                if (xpDomainInfo != null && (
7350                        xpDomainInfo.bestDomainVerificationStatus
7351                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7352                    result.add(xpDomainInfo.resolveInfo);
7353                }
7354                includeBrowser = true;
7355            }
7356
7357            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7358            // If there were 'always' entries their preferred order has been set, so we also
7359            // back that off to make the alternatives equivalent
7360            if (alwaysAskList.size() > 0) {
7361                for (ResolveInfo i : result) {
7362                    i.preferredOrder = 0;
7363                }
7364                result.addAll(alwaysAskList);
7365                includeBrowser = true;
7366            }
7367
7368            if (includeBrowser) {
7369                // Also add browsers (all of them or only the default one)
7370                if (DEBUG_DOMAIN_VERIFICATION) {
7371                    Slog.v(TAG, "   ...including browsers in candidate set");
7372                }
7373                if ((matchFlags & MATCH_ALL) != 0) {
7374                    result.addAll(matchAllList);
7375                } else {
7376                    // Browser/generic handling case.  If there's a default browser, go straight
7377                    // to that (but only if there is no other higher-priority match).
7378                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7379                    int maxMatchPrio = 0;
7380                    ResolveInfo defaultBrowserMatch = null;
7381                    final int numCandidates = matchAllList.size();
7382                    for (int n = 0; n < numCandidates; n++) {
7383                        ResolveInfo info = matchAllList.get(n);
7384                        // track the highest overall match priority...
7385                        if (info.priority > maxMatchPrio) {
7386                            maxMatchPrio = info.priority;
7387                        }
7388                        // ...and the highest-priority default browser match
7389                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7390                            if (defaultBrowserMatch == null
7391                                    || (defaultBrowserMatch.priority < info.priority)) {
7392                                if (debug) {
7393                                    Slog.v(TAG, "Considering default browser match " + info);
7394                                }
7395                                defaultBrowserMatch = info;
7396                            }
7397                        }
7398                    }
7399                    if (defaultBrowserMatch != null
7400                            && defaultBrowserMatch.priority >= maxMatchPrio
7401                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7402                    {
7403                        if (debug) {
7404                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7405                        }
7406                        result.add(defaultBrowserMatch);
7407                    } else {
7408                        result.addAll(matchAllList);
7409                    }
7410                }
7411
7412                // If there is nothing selected, add all candidates and remove the ones that the user
7413                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7414                if (result.size() == 0) {
7415                    result.addAll(candidates);
7416                    result.removeAll(neverList);
7417                }
7418            }
7419        }
7420        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7421            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7422                    result.size());
7423            for (ResolveInfo info : result) {
7424                Slog.v(TAG, "  + " + info.activityInfo);
7425            }
7426        }
7427        return result;
7428    }
7429
7430    // Returns a packed value as a long:
7431    //
7432    // high 'int'-sized word: link status: undefined/ask/never/always.
7433    // low 'int'-sized word: relative priority among 'always' results.
7434    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7435        long result = ps.getDomainVerificationStatusForUser(userId);
7436        // if none available, get the master status
7437        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7438            if (ps.getIntentFilterVerificationInfo() != null) {
7439                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7440            }
7441        }
7442        return result;
7443    }
7444
7445    private ResolveInfo querySkipCurrentProfileIntents(
7446            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7447            int flags, int sourceUserId) {
7448        if (matchingFilters != null) {
7449            int size = matchingFilters.size();
7450            for (int i = 0; i < size; i ++) {
7451                CrossProfileIntentFilter filter = matchingFilters.get(i);
7452                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7453                    // Checking if there are activities in the target user that can handle the
7454                    // intent.
7455                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7456                            resolvedType, flags, sourceUserId);
7457                    if (resolveInfo != null) {
7458                        return resolveInfo;
7459                    }
7460                }
7461            }
7462        }
7463        return null;
7464    }
7465
7466    // Return matching ResolveInfo in target user if any.
7467    private ResolveInfo queryCrossProfileIntents(
7468            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7469            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7470        if (matchingFilters != null) {
7471            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7472            // match the same intent. For performance reasons, it is better not to
7473            // run queryIntent twice for the same userId
7474            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7475            int size = matchingFilters.size();
7476            for (int i = 0; i < size; i++) {
7477                CrossProfileIntentFilter filter = matchingFilters.get(i);
7478                int targetUserId = filter.getTargetUserId();
7479                boolean skipCurrentProfile =
7480                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7481                boolean skipCurrentProfileIfNoMatchFound =
7482                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7483                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7484                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7485                    // Checking if there are activities in the target user that can handle the
7486                    // intent.
7487                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7488                            resolvedType, flags, sourceUserId);
7489                    if (resolveInfo != null) return resolveInfo;
7490                    alreadyTriedUserIds.put(targetUserId, true);
7491                }
7492            }
7493        }
7494        return null;
7495    }
7496
7497    /**
7498     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7499     * will forward the intent to the filter's target user.
7500     * Otherwise, returns null.
7501     */
7502    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7503            String resolvedType, int flags, int sourceUserId) {
7504        int targetUserId = filter.getTargetUserId();
7505        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7506                resolvedType, flags, targetUserId);
7507        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7508            // If all the matches in the target profile are suspended, return null.
7509            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7510                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7511                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7512                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7513                            targetUserId);
7514                }
7515            }
7516        }
7517        return null;
7518    }
7519
7520    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7521            int sourceUserId, int targetUserId) {
7522        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7523        long ident = Binder.clearCallingIdentity();
7524        boolean targetIsProfile;
7525        try {
7526            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7527        } finally {
7528            Binder.restoreCallingIdentity(ident);
7529        }
7530        String className;
7531        if (targetIsProfile) {
7532            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7533        } else {
7534            className = FORWARD_INTENT_TO_PARENT;
7535        }
7536        ComponentName forwardingActivityComponentName = new ComponentName(
7537                mAndroidApplication.packageName, className);
7538        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7539                sourceUserId);
7540        if (!targetIsProfile) {
7541            forwardingActivityInfo.showUserIcon = targetUserId;
7542            forwardingResolveInfo.noResourceId = true;
7543        }
7544        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7545        forwardingResolveInfo.priority = 0;
7546        forwardingResolveInfo.preferredOrder = 0;
7547        forwardingResolveInfo.match = 0;
7548        forwardingResolveInfo.isDefault = true;
7549        forwardingResolveInfo.filter = filter;
7550        forwardingResolveInfo.targetUserId = targetUserId;
7551        return forwardingResolveInfo;
7552    }
7553
7554    @Override
7555    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7556            Intent[] specifics, String[] specificTypes, Intent intent,
7557            String resolvedType, int flags, int userId) {
7558        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7559                specificTypes, intent, resolvedType, flags, userId));
7560    }
7561
7562    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7563            Intent[] specifics, String[] specificTypes, Intent intent,
7564            String resolvedType, int flags, int userId) {
7565        if (!sUserManager.exists(userId)) return Collections.emptyList();
7566        final int callingUid = Binder.getCallingUid();
7567        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7568                false /*includeInstantApps*/);
7569        enforceCrossUserPermission(callingUid, userId,
7570                false /*requireFullPermission*/, false /*checkShell*/,
7571                "query intent activity options");
7572        final String resultsAction = intent.getAction();
7573
7574        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7575                | PackageManager.GET_RESOLVED_FILTER, userId);
7576
7577        if (DEBUG_INTENT_MATCHING) {
7578            Log.v(TAG, "Query " + intent + ": " + results);
7579        }
7580
7581        int specificsPos = 0;
7582        int N;
7583
7584        // todo: note that the algorithm used here is O(N^2).  This
7585        // isn't a problem in our current environment, but if we start running
7586        // into situations where we have more than 5 or 10 matches then this
7587        // should probably be changed to something smarter...
7588
7589        // First we go through and resolve each of the specific items
7590        // that were supplied, taking care of removing any corresponding
7591        // duplicate items in the generic resolve list.
7592        if (specifics != null) {
7593            for (int i=0; i<specifics.length; i++) {
7594                final Intent sintent = specifics[i];
7595                if (sintent == null) {
7596                    continue;
7597                }
7598
7599                if (DEBUG_INTENT_MATCHING) {
7600                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7601                }
7602
7603                String action = sintent.getAction();
7604                if (resultsAction != null && resultsAction.equals(action)) {
7605                    // If this action was explicitly requested, then don't
7606                    // remove things that have it.
7607                    action = null;
7608                }
7609
7610                ResolveInfo ri = null;
7611                ActivityInfo ai = null;
7612
7613                ComponentName comp = sintent.getComponent();
7614                if (comp == null) {
7615                    ri = resolveIntent(
7616                        sintent,
7617                        specificTypes != null ? specificTypes[i] : null,
7618                            flags, userId);
7619                    if (ri == null) {
7620                        continue;
7621                    }
7622                    if (ri == mResolveInfo) {
7623                        // ACK!  Must do something better with this.
7624                    }
7625                    ai = ri.activityInfo;
7626                    comp = new ComponentName(ai.applicationInfo.packageName,
7627                            ai.name);
7628                } else {
7629                    ai = getActivityInfo(comp, flags, userId);
7630                    if (ai == null) {
7631                        continue;
7632                    }
7633                }
7634
7635                // Look for any generic query activities that are duplicates
7636                // of this specific one, and remove them from the results.
7637                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7638                N = results.size();
7639                int j;
7640                for (j=specificsPos; j<N; j++) {
7641                    ResolveInfo sri = results.get(j);
7642                    if ((sri.activityInfo.name.equals(comp.getClassName())
7643                            && sri.activityInfo.applicationInfo.packageName.equals(
7644                                    comp.getPackageName()))
7645                        || (action != null && sri.filter.matchAction(action))) {
7646                        results.remove(j);
7647                        if (DEBUG_INTENT_MATCHING) Log.v(
7648                            TAG, "Removing duplicate item from " + j
7649                            + " due to specific " + specificsPos);
7650                        if (ri == null) {
7651                            ri = sri;
7652                        }
7653                        j--;
7654                        N--;
7655                    }
7656                }
7657
7658                // Add this specific item to its proper place.
7659                if (ri == null) {
7660                    ri = new ResolveInfo();
7661                    ri.activityInfo = ai;
7662                }
7663                results.add(specificsPos, ri);
7664                ri.specificIndex = i;
7665                specificsPos++;
7666            }
7667        }
7668
7669        // Now we go through the remaining generic results and remove any
7670        // duplicate actions that are found here.
7671        N = results.size();
7672        for (int i=specificsPos; i<N-1; i++) {
7673            final ResolveInfo rii = results.get(i);
7674            if (rii.filter == null) {
7675                continue;
7676            }
7677
7678            // Iterate over all of the actions of this result's intent
7679            // filter...  typically this should be just one.
7680            final Iterator<String> it = rii.filter.actionsIterator();
7681            if (it == null) {
7682                continue;
7683            }
7684            while (it.hasNext()) {
7685                final String action = it.next();
7686                if (resultsAction != null && resultsAction.equals(action)) {
7687                    // If this action was explicitly requested, then don't
7688                    // remove things that have it.
7689                    continue;
7690                }
7691                for (int j=i+1; j<N; j++) {
7692                    final ResolveInfo rij = results.get(j);
7693                    if (rij.filter != null && rij.filter.hasAction(action)) {
7694                        results.remove(j);
7695                        if (DEBUG_INTENT_MATCHING) Log.v(
7696                            TAG, "Removing duplicate item from " + j
7697                            + " due to action " + action + " at " + i);
7698                        j--;
7699                        N--;
7700                    }
7701                }
7702            }
7703
7704            // If the caller didn't request filter information, drop it now
7705            // so we don't have to marshall/unmarshall it.
7706            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7707                rii.filter = null;
7708            }
7709        }
7710
7711        // Filter out the caller activity if so requested.
7712        if (caller != null) {
7713            N = results.size();
7714            for (int i=0; i<N; i++) {
7715                ActivityInfo ainfo = results.get(i).activityInfo;
7716                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7717                        && caller.getClassName().equals(ainfo.name)) {
7718                    results.remove(i);
7719                    break;
7720                }
7721            }
7722        }
7723
7724        // If the caller didn't request filter information,
7725        // drop them now so we don't have to
7726        // marshall/unmarshall it.
7727        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7728            N = results.size();
7729            for (int i=0; i<N; i++) {
7730                results.get(i).filter = null;
7731            }
7732        }
7733
7734        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7735        return results;
7736    }
7737
7738    @Override
7739    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7740            String resolvedType, int flags, int userId) {
7741        return new ParceledListSlice<>(
7742                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7743    }
7744
7745    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7746            String resolvedType, int flags, int userId) {
7747        if (!sUserManager.exists(userId)) return Collections.emptyList();
7748        final int callingUid = Binder.getCallingUid();
7749        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7750        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7751                false /*includeInstantApps*/);
7752        ComponentName comp = intent.getComponent();
7753        if (comp == null) {
7754            if (intent.getSelector() != null) {
7755                intent = intent.getSelector();
7756                comp = intent.getComponent();
7757            }
7758        }
7759        if (comp != null) {
7760            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7761            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7762            if (ai != null) {
7763                // When specifying an explicit component, we prevent the activity from being
7764                // used when either 1) the calling package is normal and the activity is within
7765                // an instant application or 2) the calling package is ephemeral and the
7766                // activity is not visible to instant applications.
7767                final boolean matchInstantApp =
7768                        (flags & PackageManager.MATCH_INSTANT) != 0;
7769                final boolean matchVisibleToInstantAppOnly =
7770                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7771                final boolean matchExplicitlyVisibleOnly =
7772                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7773                final boolean isCallerInstantApp =
7774                        instantAppPkgName != null;
7775                final boolean isTargetSameInstantApp =
7776                        comp.getPackageName().equals(instantAppPkgName);
7777                final boolean isTargetInstantApp =
7778                        (ai.applicationInfo.privateFlags
7779                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7780                final boolean isTargetVisibleToInstantApp =
7781                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7782                final boolean isTargetExplicitlyVisibleToInstantApp =
7783                        isTargetVisibleToInstantApp
7784                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7785                final boolean isTargetHiddenFromInstantApp =
7786                        !isTargetVisibleToInstantApp
7787                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7788                final boolean blockResolution =
7789                        !isTargetSameInstantApp
7790                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7791                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7792                                        && isTargetHiddenFromInstantApp));
7793                if (!blockResolution) {
7794                    ResolveInfo ri = new ResolveInfo();
7795                    ri.activityInfo = ai;
7796                    list.add(ri);
7797                }
7798            }
7799            return applyPostResolutionFilter(list, instantAppPkgName);
7800        }
7801
7802        // reader
7803        synchronized (mPackages) {
7804            String pkgName = intent.getPackage();
7805            if (pkgName == null) {
7806                final List<ResolveInfo> result =
7807                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7808                return applyPostResolutionFilter(result, instantAppPkgName);
7809            }
7810            final PackageParser.Package pkg = mPackages.get(pkgName);
7811            if (pkg != null) {
7812                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7813                        intent, resolvedType, flags, pkg.receivers, userId);
7814                return applyPostResolutionFilter(result, instantAppPkgName);
7815            }
7816            return Collections.emptyList();
7817        }
7818    }
7819
7820    @Override
7821    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7822        final int callingUid = Binder.getCallingUid();
7823        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7824    }
7825
7826    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7827            int userId, int callingUid) {
7828        if (!sUserManager.exists(userId)) return null;
7829        flags = updateFlagsForResolve(
7830                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7831        List<ResolveInfo> query = queryIntentServicesInternal(
7832                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7833        if (query != null) {
7834            if (query.size() >= 1) {
7835                // If there is more than one service with the same priority,
7836                // just arbitrarily pick the first one.
7837                return query.get(0);
7838            }
7839        }
7840        return null;
7841    }
7842
7843    @Override
7844    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7845            String resolvedType, int flags, int userId) {
7846        final int callingUid = Binder.getCallingUid();
7847        return new ParceledListSlice<>(queryIntentServicesInternal(
7848                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7849    }
7850
7851    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7852            String resolvedType, int flags, int userId, int callingUid,
7853            boolean includeInstantApps) {
7854        if (!sUserManager.exists(userId)) return Collections.emptyList();
7855        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7856        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7857        ComponentName comp = intent.getComponent();
7858        if (comp == null) {
7859            if (intent.getSelector() != null) {
7860                intent = intent.getSelector();
7861                comp = intent.getComponent();
7862            }
7863        }
7864        if (comp != null) {
7865            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7866            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7867            if (si != null) {
7868                // When specifying an explicit component, we prevent the service from being
7869                // used when either 1) the service is in an instant application and the
7870                // caller is not the same instant application or 2) the calling package is
7871                // ephemeral and the activity is not visible to ephemeral applications.
7872                final boolean matchInstantApp =
7873                        (flags & PackageManager.MATCH_INSTANT) != 0;
7874                final boolean matchVisibleToInstantAppOnly =
7875                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7876                final boolean isCallerInstantApp =
7877                        instantAppPkgName != null;
7878                final boolean isTargetSameInstantApp =
7879                        comp.getPackageName().equals(instantAppPkgName);
7880                final boolean isTargetInstantApp =
7881                        (si.applicationInfo.privateFlags
7882                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7883                final boolean isTargetHiddenFromInstantApp =
7884                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7885                final boolean blockResolution =
7886                        !isTargetSameInstantApp
7887                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7888                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7889                                        && isTargetHiddenFromInstantApp));
7890                if (!blockResolution) {
7891                    final ResolveInfo ri = new ResolveInfo();
7892                    ri.serviceInfo = si;
7893                    list.add(ri);
7894                }
7895            }
7896            return list;
7897        }
7898
7899        // reader
7900        synchronized (mPackages) {
7901            String pkgName = intent.getPackage();
7902            if (pkgName == null) {
7903                return applyPostServiceResolutionFilter(
7904                        mServices.queryIntent(intent, resolvedType, flags, userId),
7905                        instantAppPkgName);
7906            }
7907            final PackageParser.Package pkg = mPackages.get(pkgName);
7908            if (pkg != null) {
7909                return applyPostServiceResolutionFilter(
7910                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7911                                userId),
7912                        instantAppPkgName);
7913            }
7914            return Collections.emptyList();
7915        }
7916    }
7917
7918    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7919            String instantAppPkgName) {
7920        // TODO: When adding on-demand split support for non-instant apps, remove this check
7921        // and always apply post filtering
7922        if (instantAppPkgName == null) {
7923            return resolveInfos;
7924        }
7925        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7926            final ResolveInfo info = resolveInfos.get(i);
7927            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7928            // allow services that are defined in the provided package
7929            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7930                if (info.serviceInfo.splitName != null
7931                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7932                                info.serviceInfo.splitName)) {
7933                    // requested service is defined in a split that hasn't been installed yet.
7934                    // add the installer to the resolve list
7935                    if (DEBUG_EPHEMERAL) {
7936                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7937                    }
7938                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7939                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7940                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7941                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7942                    // make sure this resolver is the default
7943                    installerInfo.isDefault = true;
7944                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7945                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7946                    // add a non-generic filter
7947                    installerInfo.filter = new IntentFilter();
7948                    // load resources from the correct package
7949                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7950                    resolveInfos.set(i, installerInfo);
7951                }
7952                continue;
7953            }
7954            // allow services that have been explicitly exposed to ephemeral apps
7955            if (!isEphemeralApp
7956                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7957                continue;
7958            }
7959            resolveInfos.remove(i);
7960        }
7961        return resolveInfos;
7962    }
7963
7964    @Override
7965    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7966            String resolvedType, int flags, int userId) {
7967        return new ParceledListSlice<>(
7968                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7969    }
7970
7971    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7972            Intent intent, String resolvedType, int flags, int userId) {
7973        if (!sUserManager.exists(userId)) return Collections.emptyList();
7974        final int callingUid = Binder.getCallingUid();
7975        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7976        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7977                false /*includeInstantApps*/);
7978        ComponentName comp = intent.getComponent();
7979        if (comp == null) {
7980            if (intent.getSelector() != null) {
7981                intent = intent.getSelector();
7982                comp = intent.getComponent();
7983            }
7984        }
7985        if (comp != null) {
7986            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7987            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7988            if (pi != null) {
7989                // When specifying an explicit component, we prevent the provider from being
7990                // used when either 1) the provider is in an instant application and the
7991                // caller is not the same instant application or 2) the calling package is an
7992                // instant application and the provider is not visible to instant applications.
7993                final boolean matchInstantApp =
7994                        (flags & PackageManager.MATCH_INSTANT) != 0;
7995                final boolean matchVisibleToInstantAppOnly =
7996                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7997                final boolean isCallerInstantApp =
7998                        instantAppPkgName != null;
7999                final boolean isTargetSameInstantApp =
8000                        comp.getPackageName().equals(instantAppPkgName);
8001                final boolean isTargetInstantApp =
8002                        (pi.applicationInfo.privateFlags
8003                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8004                final boolean isTargetHiddenFromInstantApp =
8005                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8006                final boolean blockResolution =
8007                        !isTargetSameInstantApp
8008                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8009                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8010                                        && isTargetHiddenFromInstantApp));
8011                if (!blockResolution) {
8012                    final ResolveInfo ri = new ResolveInfo();
8013                    ri.providerInfo = pi;
8014                    list.add(ri);
8015                }
8016            }
8017            return list;
8018        }
8019
8020        // reader
8021        synchronized (mPackages) {
8022            String pkgName = intent.getPackage();
8023            if (pkgName == null) {
8024                return applyPostContentProviderResolutionFilter(
8025                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8026                        instantAppPkgName);
8027            }
8028            final PackageParser.Package pkg = mPackages.get(pkgName);
8029            if (pkg != null) {
8030                return applyPostContentProviderResolutionFilter(
8031                        mProviders.queryIntentForPackage(
8032                        intent, resolvedType, flags, pkg.providers, userId),
8033                        instantAppPkgName);
8034            }
8035            return Collections.emptyList();
8036        }
8037    }
8038
8039    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8040            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8041        // TODO: When adding on-demand split support for non-instant applications, remove
8042        // this check and always apply post filtering
8043        if (instantAppPkgName == null) {
8044            return resolveInfos;
8045        }
8046        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8047            final ResolveInfo info = resolveInfos.get(i);
8048            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8049            // allow providers that are defined in the provided package
8050            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8051                if (info.providerInfo.splitName != null
8052                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8053                                info.providerInfo.splitName)) {
8054                    // requested provider is defined in a split that hasn't been installed yet.
8055                    // add the installer to the resolve list
8056                    if (DEBUG_EPHEMERAL) {
8057                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8058                    }
8059                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8060                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8061                            info.providerInfo.packageName, info.providerInfo.splitName,
8062                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8063                    // make sure this resolver is the default
8064                    installerInfo.isDefault = true;
8065                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8066                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8067                    // add a non-generic filter
8068                    installerInfo.filter = new IntentFilter();
8069                    // load resources from the correct package
8070                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8071                    resolveInfos.set(i, installerInfo);
8072                }
8073                continue;
8074            }
8075            // allow providers that have been explicitly exposed to instant applications
8076            if (!isEphemeralApp
8077                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8078                continue;
8079            }
8080            resolveInfos.remove(i);
8081        }
8082        return resolveInfos;
8083    }
8084
8085    @Override
8086    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8087        final int callingUid = Binder.getCallingUid();
8088        if (getInstantAppPackageName(callingUid) != null) {
8089            return ParceledListSlice.emptyList();
8090        }
8091        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8092        flags = updateFlagsForPackage(flags, userId, null);
8093        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8094        enforceCrossUserPermission(callingUid, userId,
8095                true /* requireFullPermission */, false /* checkShell */,
8096                "get installed packages");
8097
8098        // writer
8099        synchronized (mPackages) {
8100            ArrayList<PackageInfo> list;
8101            if (listUninstalled) {
8102                list = new ArrayList<>(mSettings.mPackages.size());
8103                for (PackageSetting ps : mSettings.mPackages.values()) {
8104                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8105                        continue;
8106                    }
8107                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8108                        return null;
8109                    }
8110                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8111                    if (pi != null) {
8112                        list.add(pi);
8113                    }
8114                }
8115            } else {
8116                list = new ArrayList<>(mPackages.size());
8117                for (PackageParser.Package p : mPackages.values()) {
8118                    final PackageSetting ps = (PackageSetting) p.mExtras;
8119                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8120                        continue;
8121                    }
8122                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8123                        return null;
8124                    }
8125                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8126                            p.mExtras, flags, userId);
8127                    if (pi != null) {
8128                        list.add(pi);
8129                    }
8130                }
8131            }
8132
8133            return new ParceledListSlice<>(list);
8134        }
8135    }
8136
8137    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8138            String[] permissions, boolean[] tmp, int flags, int userId) {
8139        int numMatch = 0;
8140        final PermissionsState permissionsState = ps.getPermissionsState();
8141        for (int i=0; i<permissions.length; i++) {
8142            final String permission = permissions[i];
8143            if (permissionsState.hasPermission(permission, userId)) {
8144                tmp[i] = true;
8145                numMatch++;
8146            } else {
8147                tmp[i] = false;
8148            }
8149        }
8150        if (numMatch == 0) {
8151            return;
8152        }
8153        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8154
8155        // The above might return null in cases of uninstalled apps or install-state
8156        // skew across users/profiles.
8157        if (pi != null) {
8158            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8159                if (numMatch == permissions.length) {
8160                    pi.requestedPermissions = permissions;
8161                } else {
8162                    pi.requestedPermissions = new String[numMatch];
8163                    numMatch = 0;
8164                    for (int i=0; i<permissions.length; i++) {
8165                        if (tmp[i]) {
8166                            pi.requestedPermissions[numMatch] = permissions[i];
8167                            numMatch++;
8168                        }
8169                    }
8170                }
8171            }
8172            list.add(pi);
8173        }
8174    }
8175
8176    @Override
8177    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8178            String[] permissions, int flags, int userId) {
8179        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8180        flags = updateFlagsForPackage(flags, userId, permissions);
8181        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8182                true /* requireFullPermission */, false /* checkShell */,
8183                "get packages holding permissions");
8184        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8185
8186        // writer
8187        synchronized (mPackages) {
8188            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8189            boolean[] tmpBools = new boolean[permissions.length];
8190            if (listUninstalled) {
8191                for (PackageSetting ps : mSettings.mPackages.values()) {
8192                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8193                            userId);
8194                }
8195            } else {
8196                for (PackageParser.Package pkg : mPackages.values()) {
8197                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8198                    if (ps != null) {
8199                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8200                                userId);
8201                    }
8202                }
8203            }
8204
8205            return new ParceledListSlice<PackageInfo>(list);
8206        }
8207    }
8208
8209    @Override
8210    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8211        final int callingUid = Binder.getCallingUid();
8212        if (getInstantAppPackageName(callingUid) != null) {
8213            return ParceledListSlice.emptyList();
8214        }
8215        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8216        flags = updateFlagsForApplication(flags, userId, null);
8217        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8218
8219        // writer
8220        synchronized (mPackages) {
8221            ArrayList<ApplicationInfo> list;
8222            if (listUninstalled) {
8223                list = new ArrayList<>(mSettings.mPackages.size());
8224                for (PackageSetting ps : mSettings.mPackages.values()) {
8225                    ApplicationInfo ai;
8226                    int effectiveFlags = flags;
8227                    if (ps.isSystem()) {
8228                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8229                    }
8230                    if (ps.pkg != null) {
8231                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8232                            continue;
8233                        }
8234                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8235                            return null;
8236                        }
8237                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8238                                ps.readUserState(userId), userId);
8239                        if (ai != null) {
8240                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8241                        }
8242                    } else {
8243                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8244                        // and already converts to externally visible package name
8245                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8246                                callingUid, effectiveFlags, userId);
8247                    }
8248                    if (ai != null) {
8249                        list.add(ai);
8250                    }
8251                }
8252            } else {
8253                list = new ArrayList<>(mPackages.size());
8254                for (PackageParser.Package p : mPackages.values()) {
8255                    if (p.mExtras != null) {
8256                        PackageSetting ps = (PackageSetting) p.mExtras;
8257                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8258                            continue;
8259                        }
8260                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8261                            return null;
8262                        }
8263                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8264                                ps.readUserState(userId), userId);
8265                        if (ai != null) {
8266                            ai.packageName = resolveExternalPackageNameLPr(p);
8267                            list.add(ai);
8268                        }
8269                    }
8270                }
8271            }
8272
8273            return new ParceledListSlice<>(list);
8274        }
8275    }
8276
8277    @Override
8278    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8279        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8280            return null;
8281        }
8282        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8283                "getEphemeralApplications");
8284        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8285                true /* requireFullPermission */, false /* checkShell */,
8286                "getEphemeralApplications");
8287        synchronized (mPackages) {
8288            List<InstantAppInfo> instantApps = mInstantAppRegistry
8289                    .getInstantAppsLPr(userId);
8290            if (instantApps != null) {
8291                return new ParceledListSlice<>(instantApps);
8292            }
8293        }
8294        return null;
8295    }
8296
8297    @Override
8298    public boolean isInstantApp(String packageName, int userId) {
8299        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8300                true /* requireFullPermission */, false /* checkShell */,
8301                "isInstantApp");
8302        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8303            return false;
8304        }
8305
8306        synchronized (mPackages) {
8307            int callingUid = Binder.getCallingUid();
8308            if (Process.isIsolated(callingUid)) {
8309                callingUid = mIsolatedOwners.get(callingUid);
8310            }
8311            final PackageSetting ps = mSettings.mPackages.get(packageName);
8312            PackageParser.Package pkg = mPackages.get(packageName);
8313            final boolean returnAllowed =
8314                    ps != null
8315                    && (isCallerSameApp(packageName, callingUid)
8316                            || canViewInstantApps(callingUid, userId)
8317                            || mInstantAppRegistry.isInstantAccessGranted(
8318                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8319            if (returnAllowed) {
8320                return ps.getInstantApp(userId);
8321            }
8322        }
8323        return false;
8324    }
8325
8326    @Override
8327    public byte[] getInstantAppCookie(String packageName, int userId) {
8328        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8329            return null;
8330        }
8331
8332        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8333                true /* requireFullPermission */, false /* checkShell */,
8334                "getInstantAppCookie");
8335        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8336            return null;
8337        }
8338        synchronized (mPackages) {
8339            return mInstantAppRegistry.getInstantAppCookieLPw(
8340                    packageName, userId);
8341        }
8342    }
8343
8344    @Override
8345    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8346        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8347            return true;
8348        }
8349
8350        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8351                true /* requireFullPermission */, true /* checkShell */,
8352                "setInstantAppCookie");
8353        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8354            return false;
8355        }
8356        synchronized (mPackages) {
8357            return mInstantAppRegistry.setInstantAppCookieLPw(
8358                    packageName, cookie, userId);
8359        }
8360    }
8361
8362    @Override
8363    public Bitmap getInstantAppIcon(String packageName, int userId) {
8364        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8365            return null;
8366        }
8367
8368        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8369                "getInstantAppIcon");
8370
8371        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8372                true /* requireFullPermission */, false /* checkShell */,
8373                "getInstantAppIcon");
8374
8375        synchronized (mPackages) {
8376            return mInstantAppRegistry.getInstantAppIconLPw(
8377                    packageName, userId);
8378        }
8379    }
8380
8381    private boolean isCallerSameApp(String packageName, int uid) {
8382        PackageParser.Package pkg = mPackages.get(packageName);
8383        return pkg != null
8384                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8385    }
8386
8387    @Override
8388    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8389        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8390            return ParceledListSlice.emptyList();
8391        }
8392        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8393    }
8394
8395    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8396        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8397
8398        // reader
8399        synchronized (mPackages) {
8400            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8401            final int userId = UserHandle.getCallingUserId();
8402            while (i.hasNext()) {
8403                final PackageParser.Package p = i.next();
8404                if (p.applicationInfo == null) continue;
8405
8406                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8407                        && !p.applicationInfo.isDirectBootAware();
8408                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8409                        && p.applicationInfo.isDirectBootAware();
8410
8411                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8412                        && (!mSafeMode || isSystemApp(p))
8413                        && (matchesUnaware || matchesAware)) {
8414                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8415                    if (ps != null) {
8416                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8417                                ps.readUserState(userId), userId);
8418                        if (ai != null) {
8419                            finalList.add(ai);
8420                        }
8421                    }
8422                }
8423            }
8424        }
8425
8426        return finalList;
8427    }
8428
8429    @Override
8430    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8431        if (!sUserManager.exists(userId)) return null;
8432        flags = updateFlagsForComponent(flags, userId, name);
8433        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8434        // reader
8435        synchronized (mPackages) {
8436            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8437            PackageSetting ps = provider != null
8438                    ? mSettings.mPackages.get(provider.owner.packageName)
8439                    : null;
8440            if (ps != null) {
8441                final boolean isInstantApp = ps.getInstantApp(userId);
8442                // normal application; filter out instant application provider
8443                if (instantAppPkgName == null && isInstantApp) {
8444                    return null;
8445                }
8446                // instant application; filter out other instant applications
8447                if (instantAppPkgName != null
8448                        && isInstantApp
8449                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8450                    return null;
8451                }
8452                // instant application; filter out non-exposed provider
8453                if (instantAppPkgName != null
8454                        && !isInstantApp
8455                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8456                    return null;
8457                }
8458                // provider not enabled
8459                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8460                    return null;
8461                }
8462                return PackageParser.generateProviderInfo(
8463                        provider, flags, ps.readUserState(userId), userId);
8464            }
8465            return null;
8466        }
8467    }
8468
8469    /**
8470     * @deprecated
8471     */
8472    @Deprecated
8473    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8474        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8475            return;
8476        }
8477        // reader
8478        synchronized (mPackages) {
8479            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8480                    .entrySet().iterator();
8481            final int userId = UserHandle.getCallingUserId();
8482            while (i.hasNext()) {
8483                Map.Entry<String, PackageParser.Provider> entry = i.next();
8484                PackageParser.Provider p = entry.getValue();
8485                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8486
8487                if (ps != null && p.syncable
8488                        && (!mSafeMode || (p.info.applicationInfo.flags
8489                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8490                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8491                            ps.readUserState(userId), userId);
8492                    if (info != null) {
8493                        outNames.add(entry.getKey());
8494                        outInfo.add(info);
8495                    }
8496                }
8497            }
8498        }
8499    }
8500
8501    @Override
8502    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8503            int uid, int flags, String metaDataKey) {
8504        final int callingUid = Binder.getCallingUid();
8505        final int userId = processName != null ? UserHandle.getUserId(uid)
8506                : UserHandle.getCallingUserId();
8507        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8508        flags = updateFlagsForComponent(flags, userId, processName);
8509        ArrayList<ProviderInfo> finalList = null;
8510        // reader
8511        synchronized (mPackages) {
8512            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8513            while (i.hasNext()) {
8514                final PackageParser.Provider p = i.next();
8515                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8516                if (ps != null && p.info.authority != null
8517                        && (processName == null
8518                                || (p.info.processName.equals(processName)
8519                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8520                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8521
8522                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8523                    // parameter.
8524                    if (metaDataKey != null
8525                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8526                        continue;
8527                    }
8528                    final ComponentName component =
8529                            new ComponentName(p.info.packageName, p.info.name);
8530                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8531                        continue;
8532                    }
8533                    if (finalList == null) {
8534                        finalList = new ArrayList<ProviderInfo>(3);
8535                    }
8536                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8537                            ps.readUserState(userId), userId);
8538                    if (info != null) {
8539                        finalList.add(info);
8540                    }
8541                }
8542            }
8543        }
8544
8545        if (finalList != null) {
8546            Collections.sort(finalList, mProviderInitOrderSorter);
8547            return new ParceledListSlice<ProviderInfo>(finalList);
8548        }
8549
8550        return ParceledListSlice.emptyList();
8551    }
8552
8553    @Override
8554    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8555        // reader
8556        synchronized (mPackages) {
8557            final int callingUid = Binder.getCallingUid();
8558            final int callingUserId = UserHandle.getUserId(callingUid);
8559            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8560            if (ps == null) return null;
8561            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8562                return null;
8563            }
8564            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8565            return PackageParser.generateInstrumentationInfo(i, flags);
8566        }
8567    }
8568
8569    @Override
8570    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8571            String targetPackage, int flags) {
8572        final int callingUid = Binder.getCallingUid();
8573        final int callingUserId = UserHandle.getUserId(callingUid);
8574        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8575        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8576            return ParceledListSlice.emptyList();
8577        }
8578        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8579    }
8580
8581    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8582            int flags) {
8583        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8584
8585        // reader
8586        synchronized (mPackages) {
8587            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8588            while (i.hasNext()) {
8589                final PackageParser.Instrumentation p = i.next();
8590                if (targetPackage == null
8591                        || targetPackage.equals(p.info.targetPackage)) {
8592                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8593                            flags);
8594                    if (ii != null) {
8595                        finalList.add(ii);
8596                    }
8597                }
8598            }
8599        }
8600
8601        return finalList;
8602    }
8603
8604    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8605        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8606        try {
8607            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8608        } finally {
8609            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8610        }
8611    }
8612
8613    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8614        final File[] files = dir.listFiles();
8615        if (ArrayUtils.isEmpty(files)) {
8616            Log.d(TAG, "No files in app dir " + dir);
8617            return;
8618        }
8619
8620        if (DEBUG_PACKAGE_SCANNING) {
8621            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8622                    + " flags=0x" + Integer.toHexString(parseFlags));
8623        }
8624        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8625                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8626                mParallelPackageParserCallback);
8627
8628        // Submit files for parsing in parallel
8629        int fileCount = 0;
8630        for (File file : files) {
8631            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8632                    && !PackageInstallerService.isStageName(file.getName());
8633            if (!isPackage) {
8634                // Ignore entries which are not packages
8635                continue;
8636            }
8637            parallelPackageParser.submit(file, parseFlags);
8638            fileCount++;
8639        }
8640
8641        // Process results one by one
8642        for (; fileCount > 0; fileCount--) {
8643            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8644            Throwable throwable = parseResult.throwable;
8645            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8646
8647            if (throwable == null) {
8648                // Static shared libraries have synthetic package names
8649                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8650                    renameStaticSharedLibraryPackage(parseResult.pkg);
8651                }
8652                try {
8653                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8654                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8655                                currentTime, null);
8656                    }
8657                } catch (PackageManagerException e) {
8658                    errorCode = e.error;
8659                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8660                }
8661            } else if (throwable instanceof PackageParser.PackageParserException) {
8662                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8663                        throwable;
8664                errorCode = e.error;
8665                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8666            } else {
8667                throw new IllegalStateException("Unexpected exception occurred while parsing "
8668                        + parseResult.scanFile, throwable);
8669            }
8670
8671            // Delete invalid userdata apps
8672            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8673                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8674                logCriticalInfo(Log.WARN,
8675                        "Deleting invalid package at " + parseResult.scanFile);
8676                removeCodePathLI(parseResult.scanFile);
8677            }
8678        }
8679        parallelPackageParser.close();
8680    }
8681
8682    private static File getSettingsProblemFile() {
8683        File dataDir = Environment.getDataDirectory();
8684        File systemDir = new File(dataDir, "system");
8685        File fname = new File(systemDir, "uiderrors.txt");
8686        return fname;
8687    }
8688
8689    static void reportSettingsProblem(int priority, String msg) {
8690        logCriticalInfo(priority, msg);
8691    }
8692
8693    public static void logCriticalInfo(int priority, String msg) {
8694        Slog.println(priority, TAG, msg);
8695        EventLogTags.writePmCriticalInfo(msg);
8696        try {
8697            File fname = getSettingsProblemFile();
8698            FileOutputStream out = new FileOutputStream(fname, true);
8699            PrintWriter pw = new FastPrintWriter(out);
8700            SimpleDateFormat formatter = new SimpleDateFormat();
8701            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8702            pw.println(dateString + ": " + msg);
8703            pw.close();
8704            FileUtils.setPermissions(
8705                    fname.toString(),
8706                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8707                    -1, -1);
8708        } catch (java.io.IOException e) {
8709        }
8710    }
8711
8712    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8713        if (srcFile.isDirectory()) {
8714            final File baseFile = new File(pkg.baseCodePath);
8715            long maxModifiedTime = baseFile.lastModified();
8716            if (pkg.splitCodePaths != null) {
8717                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8718                    final File splitFile = new File(pkg.splitCodePaths[i]);
8719                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8720                }
8721            }
8722            return maxModifiedTime;
8723        }
8724        return srcFile.lastModified();
8725    }
8726
8727    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8728            final int policyFlags) throws PackageManagerException {
8729        // When upgrading from pre-N MR1, verify the package time stamp using the package
8730        // directory and not the APK file.
8731        final long lastModifiedTime = mIsPreNMR1Upgrade
8732                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8733        if (ps != null
8734                && ps.codePath.equals(srcFile)
8735                && ps.timeStamp == lastModifiedTime
8736                && !isCompatSignatureUpdateNeeded(pkg)
8737                && !isRecoverSignatureUpdateNeeded(pkg)) {
8738            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8739            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8740            ArraySet<PublicKey> signingKs;
8741            synchronized (mPackages) {
8742                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8743            }
8744            if (ps.signatures.mSignatures != null
8745                    && ps.signatures.mSignatures.length != 0
8746                    && signingKs != null) {
8747                // Optimization: reuse the existing cached certificates
8748                // if the package appears to be unchanged.
8749                pkg.mSignatures = ps.signatures.mSignatures;
8750                pkg.mSigningKeys = signingKs;
8751                return;
8752            }
8753
8754            Slog.w(TAG, "PackageSetting for " + ps.name
8755                    + " is missing signatures.  Collecting certs again to recover them.");
8756        } else {
8757            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8758        }
8759
8760        try {
8761            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8762            PackageParser.collectCertificates(pkg, policyFlags);
8763        } catch (PackageParserException e) {
8764            throw PackageManagerException.from(e);
8765        } finally {
8766            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8767        }
8768    }
8769
8770    /**
8771     *  Traces a package scan.
8772     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8773     */
8774    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8775            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8776        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8777        try {
8778            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8779        } finally {
8780            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8781        }
8782    }
8783
8784    /**
8785     *  Scans a package and returns the newly parsed package.
8786     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8787     */
8788    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8789            long currentTime, UserHandle user) throws PackageManagerException {
8790        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8791        PackageParser pp = new PackageParser();
8792        pp.setSeparateProcesses(mSeparateProcesses);
8793        pp.setOnlyCoreApps(mOnlyCore);
8794        pp.setDisplayMetrics(mMetrics);
8795        pp.setCallback(mPackageParserCallback);
8796
8797        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8798            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8799        }
8800
8801        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8802        final PackageParser.Package pkg;
8803        try {
8804            pkg = pp.parsePackage(scanFile, parseFlags);
8805        } catch (PackageParserException e) {
8806            throw PackageManagerException.from(e);
8807        } finally {
8808            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8809        }
8810
8811        // Static shared libraries have synthetic package names
8812        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8813            renameStaticSharedLibraryPackage(pkg);
8814        }
8815
8816        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8817    }
8818
8819    /**
8820     *  Scans a package and returns the newly parsed package.
8821     *  @throws PackageManagerException on a parse error.
8822     */
8823    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8824            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8825            throws PackageManagerException {
8826        // If the package has children and this is the first dive in the function
8827        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8828        // packages (parent and children) would be successfully scanned before the
8829        // actual scan since scanning mutates internal state and we want to atomically
8830        // install the package and its children.
8831        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8832            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8833                scanFlags |= SCAN_CHECK_ONLY;
8834            }
8835        } else {
8836            scanFlags &= ~SCAN_CHECK_ONLY;
8837        }
8838
8839        // Scan the parent
8840        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8841                scanFlags, currentTime, user);
8842
8843        // Scan the children
8844        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8845        for (int i = 0; i < childCount; i++) {
8846            PackageParser.Package childPackage = pkg.childPackages.get(i);
8847            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8848                    currentTime, user);
8849        }
8850
8851
8852        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8853            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8854        }
8855
8856        return scannedPkg;
8857    }
8858
8859    /**
8860     *  Scans a package and returns the newly parsed package.
8861     *  @throws PackageManagerException on a parse error.
8862     */
8863    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8864            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8865            throws PackageManagerException {
8866        PackageSetting ps = null;
8867        PackageSetting updatedPkg;
8868        // reader
8869        synchronized (mPackages) {
8870            // Look to see if we already know about this package.
8871            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8872            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8873                // This package has been renamed to its original name.  Let's
8874                // use that.
8875                ps = mSettings.getPackageLPr(oldName);
8876            }
8877            // If there was no original package, see one for the real package name.
8878            if (ps == null) {
8879                ps = mSettings.getPackageLPr(pkg.packageName);
8880            }
8881            // Check to see if this package could be hiding/updating a system
8882            // package.  Must look for it either under the original or real
8883            // package name depending on our state.
8884            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8885            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8886
8887            // If this is a package we don't know about on the system partition, we
8888            // may need to remove disabled child packages on the system partition
8889            // or may need to not add child packages if the parent apk is updated
8890            // on the data partition and no longer defines this child package.
8891            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8892                // If this is a parent package for an updated system app and this system
8893                // app got an OTA update which no longer defines some of the child packages
8894                // we have to prune them from the disabled system packages.
8895                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8896                if (disabledPs != null) {
8897                    final int scannedChildCount = (pkg.childPackages != null)
8898                            ? pkg.childPackages.size() : 0;
8899                    final int disabledChildCount = disabledPs.childPackageNames != null
8900                            ? disabledPs.childPackageNames.size() : 0;
8901                    for (int i = 0; i < disabledChildCount; i++) {
8902                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8903                        boolean disabledPackageAvailable = false;
8904                        for (int j = 0; j < scannedChildCount; j++) {
8905                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8906                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8907                                disabledPackageAvailable = true;
8908                                break;
8909                            }
8910                         }
8911                         if (!disabledPackageAvailable) {
8912                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8913                         }
8914                    }
8915                }
8916            }
8917        }
8918
8919        boolean updatedPkgBetter = false;
8920        // First check if this is a system package that may involve an update
8921        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8922            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8923            // it needs to drop FLAG_PRIVILEGED.
8924            if (locationIsPrivileged(scanFile)) {
8925                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8926            } else {
8927                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8928            }
8929
8930            if (ps != null && !ps.codePath.equals(scanFile)) {
8931                // The path has changed from what was last scanned...  check the
8932                // version of the new path against what we have stored to determine
8933                // what to do.
8934                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8935                if (pkg.mVersionCode <= ps.versionCode) {
8936                    // The system package has been updated and the code path does not match
8937                    // Ignore entry. Skip it.
8938                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8939                            + " ignored: updated version " + ps.versionCode
8940                            + " better than this " + pkg.mVersionCode);
8941                    if (!updatedPkg.codePath.equals(scanFile)) {
8942                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8943                                + ps.name + " changing from " + updatedPkg.codePathString
8944                                + " to " + scanFile);
8945                        updatedPkg.codePath = scanFile;
8946                        updatedPkg.codePathString = scanFile.toString();
8947                        updatedPkg.resourcePath = scanFile;
8948                        updatedPkg.resourcePathString = scanFile.toString();
8949                    }
8950                    updatedPkg.pkg = pkg;
8951                    updatedPkg.versionCode = pkg.mVersionCode;
8952
8953                    // Update the disabled system child packages to point to the package too.
8954                    final int childCount = updatedPkg.childPackageNames != null
8955                            ? updatedPkg.childPackageNames.size() : 0;
8956                    for (int i = 0; i < childCount; i++) {
8957                        String childPackageName = updatedPkg.childPackageNames.get(i);
8958                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8959                                childPackageName);
8960                        if (updatedChildPkg != null) {
8961                            updatedChildPkg.pkg = pkg;
8962                            updatedChildPkg.versionCode = pkg.mVersionCode;
8963                        }
8964                    }
8965
8966                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8967                            + scanFile + " ignored: updated version " + ps.versionCode
8968                            + " better than this " + pkg.mVersionCode);
8969                } else {
8970                    // The current app on the system partition is better than
8971                    // what we have updated to on the data partition; switch
8972                    // back to the system partition version.
8973                    // At this point, its safely assumed that package installation for
8974                    // apps in system partition will go through. If not there won't be a working
8975                    // version of the app
8976                    // writer
8977                    synchronized (mPackages) {
8978                        // Just remove the loaded entries from package lists.
8979                        mPackages.remove(ps.name);
8980                    }
8981
8982                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8983                            + " reverting from " + ps.codePathString
8984                            + ": new version " + pkg.mVersionCode
8985                            + " better than installed " + ps.versionCode);
8986
8987                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8988                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8989                    synchronized (mInstallLock) {
8990                        args.cleanUpResourcesLI();
8991                    }
8992                    synchronized (mPackages) {
8993                        mSettings.enableSystemPackageLPw(ps.name);
8994                    }
8995                    updatedPkgBetter = true;
8996                }
8997            }
8998        }
8999
9000        if (updatedPkg != null) {
9001            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9002            // initially
9003            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9004
9005            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9006            // flag set initially
9007            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9008                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9009            }
9010        }
9011
9012        // Verify certificates against what was last scanned
9013        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9014
9015        /*
9016         * A new system app appeared, but we already had a non-system one of the
9017         * same name installed earlier.
9018         */
9019        boolean shouldHideSystemApp = false;
9020        if (updatedPkg == null && ps != null
9021                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9022            /*
9023             * Check to make sure the signatures match first. If they don't,
9024             * wipe the installed application and its data.
9025             */
9026            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9027                    != PackageManager.SIGNATURE_MATCH) {
9028                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9029                        + " signatures don't match existing userdata copy; removing");
9030                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9031                        "scanPackageInternalLI")) {
9032                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9033                }
9034                ps = null;
9035            } else {
9036                /*
9037                 * If the newly-added system app is an older version than the
9038                 * already installed version, hide it. It will be scanned later
9039                 * and re-added like an update.
9040                 */
9041                if (pkg.mVersionCode <= ps.versionCode) {
9042                    shouldHideSystemApp = true;
9043                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9044                            + " but new version " + pkg.mVersionCode + " better than installed "
9045                            + ps.versionCode + "; hiding system");
9046                } else {
9047                    /*
9048                     * The newly found system app is a newer version that the
9049                     * one previously installed. Simply remove the
9050                     * already-installed application and replace it with our own
9051                     * while keeping the application data.
9052                     */
9053                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9054                            + " reverting from " + ps.codePathString + ": new version "
9055                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9056                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9057                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9058                    synchronized (mInstallLock) {
9059                        args.cleanUpResourcesLI();
9060                    }
9061                }
9062            }
9063        }
9064
9065        // The apk is forward locked (not public) if its code and resources
9066        // are kept in different files. (except for app in either system or
9067        // vendor path).
9068        // TODO grab this value from PackageSettings
9069        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9070            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9071                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9072            }
9073        }
9074
9075        // TODO: extend to support forward-locked splits
9076        String resourcePath = null;
9077        String baseResourcePath = null;
9078        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9079            if (ps != null && ps.resourcePathString != null) {
9080                resourcePath = ps.resourcePathString;
9081                baseResourcePath = ps.resourcePathString;
9082            } else {
9083                // Should not happen at all. Just log an error.
9084                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9085            }
9086        } else {
9087            resourcePath = pkg.codePath;
9088            baseResourcePath = pkg.baseCodePath;
9089        }
9090
9091        // Set application objects path explicitly.
9092        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9093        pkg.setApplicationInfoCodePath(pkg.codePath);
9094        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9095        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9096        pkg.setApplicationInfoResourcePath(resourcePath);
9097        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9098        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9099
9100        final int userId = ((user == null) ? 0 : user.getIdentifier());
9101        if (ps != null && ps.getInstantApp(userId)) {
9102            scanFlags |= SCAN_AS_INSTANT_APP;
9103        }
9104
9105        // Note that we invoke the following method only if we are about to unpack an application
9106        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9107                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9108
9109        /*
9110         * If the system app should be overridden by a previously installed
9111         * data, hide the system app now and let the /data/app scan pick it up
9112         * again.
9113         */
9114        if (shouldHideSystemApp) {
9115            synchronized (mPackages) {
9116                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9117            }
9118        }
9119
9120        return scannedPkg;
9121    }
9122
9123    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9124        // Derive the new package synthetic package name
9125        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9126                + pkg.staticSharedLibVersion);
9127    }
9128
9129    private static String fixProcessName(String defProcessName,
9130            String processName) {
9131        if (processName == null) {
9132            return defProcessName;
9133        }
9134        return processName;
9135    }
9136
9137    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9138            throws PackageManagerException {
9139        if (pkgSetting.signatures.mSignatures != null) {
9140            // Already existing package. Make sure signatures match
9141            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9142                    == PackageManager.SIGNATURE_MATCH;
9143            if (!match) {
9144                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9145                        == PackageManager.SIGNATURE_MATCH;
9146            }
9147            if (!match) {
9148                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9149                        == PackageManager.SIGNATURE_MATCH;
9150            }
9151            if (!match) {
9152                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9153                        + pkg.packageName + " signatures do not match the "
9154                        + "previously installed version; ignoring!");
9155            }
9156        }
9157
9158        // Check for shared user signatures
9159        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9160            // Already existing package. Make sure signatures match
9161            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9162                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9163            if (!match) {
9164                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9165                        == PackageManager.SIGNATURE_MATCH;
9166            }
9167            if (!match) {
9168                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9169                        == PackageManager.SIGNATURE_MATCH;
9170            }
9171            if (!match) {
9172                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9173                        "Package " + pkg.packageName
9174                        + " has no signatures that match those in shared user "
9175                        + pkgSetting.sharedUser.name + "; ignoring!");
9176            }
9177        }
9178    }
9179
9180    /**
9181     * Enforces that only the system UID or root's UID can call a method exposed
9182     * via Binder.
9183     *
9184     * @param message used as message if SecurityException is thrown
9185     * @throws SecurityException if the caller is not system or root
9186     */
9187    private static final void enforceSystemOrRoot(String message) {
9188        final int uid = Binder.getCallingUid();
9189        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9190            throw new SecurityException(message);
9191        }
9192    }
9193
9194    @Override
9195    public void performFstrimIfNeeded() {
9196        enforceSystemOrRoot("Only the system can request fstrim");
9197
9198        // Before everything else, see whether we need to fstrim.
9199        try {
9200            IStorageManager sm = PackageHelper.getStorageManager();
9201            if (sm != null) {
9202                boolean doTrim = false;
9203                final long interval = android.provider.Settings.Global.getLong(
9204                        mContext.getContentResolver(),
9205                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9206                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9207                if (interval > 0) {
9208                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9209                    if (timeSinceLast > interval) {
9210                        doTrim = true;
9211                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9212                                + "; running immediately");
9213                    }
9214                }
9215                if (doTrim) {
9216                    final boolean dexOptDialogShown;
9217                    synchronized (mPackages) {
9218                        dexOptDialogShown = mDexOptDialogShown;
9219                    }
9220                    if (!isFirstBoot() && dexOptDialogShown) {
9221                        try {
9222                            ActivityManager.getService().showBootMessage(
9223                                    mContext.getResources().getString(
9224                                            R.string.android_upgrading_fstrim), true);
9225                        } catch (RemoteException e) {
9226                        }
9227                    }
9228                    sm.runMaintenance();
9229                }
9230            } else {
9231                Slog.e(TAG, "storageManager service unavailable!");
9232            }
9233        } catch (RemoteException e) {
9234            // Can't happen; StorageManagerService is local
9235        }
9236    }
9237
9238    @Override
9239    public void updatePackagesIfNeeded() {
9240        enforceSystemOrRoot("Only the system can request package update");
9241
9242        // We need to re-extract after an OTA.
9243        boolean causeUpgrade = isUpgrade();
9244
9245        // First boot or factory reset.
9246        // Note: we also handle devices that are upgrading to N right now as if it is their
9247        //       first boot, as they do not have profile data.
9248        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9249
9250        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9251        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9252
9253        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9254            return;
9255        }
9256
9257        List<PackageParser.Package> pkgs;
9258        synchronized (mPackages) {
9259            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9260        }
9261
9262        final long startTime = System.nanoTime();
9263        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9264                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9265                    false /* bootComplete */);
9266
9267        final int elapsedTimeSeconds =
9268                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9269
9270        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9271        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9272        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9273        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9274        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9275    }
9276
9277    /*
9278     * Return the prebuilt profile path given a package base code path.
9279     */
9280    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9281        return pkg.baseCodePath + ".prof";
9282    }
9283
9284    /**
9285     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9286     * containing statistics about the invocation. The array consists of three elements,
9287     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9288     * and {@code numberOfPackagesFailed}.
9289     */
9290    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9291            String compilerFilter, boolean bootComplete) {
9292
9293        int numberOfPackagesVisited = 0;
9294        int numberOfPackagesOptimized = 0;
9295        int numberOfPackagesSkipped = 0;
9296        int numberOfPackagesFailed = 0;
9297        final int numberOfPackagesToDexopt = pkgs.size();
9298
9299        for (PackageParser.Package pkg : pkgs) {
9300            numberOfPackagesVisited++;
9301
9302            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9303                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9304                // that are already compiled.
9305                File profileFile = new File(getPrebuildProfilePath(pkg));
9306                // Copy profile if it exists.
9307                if (profileFile.exists()) {
9308                    try {
9309                        // We could also do this lazily before calling dexopt in
9310                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9311                        // is that we don't have a good way to say "do this only once".
9312                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9313                                pkg.applicationInfo.uid, pkg.packageName)) {
9314                            Log.e(TAG, "Installer failed to copy system profile!");
9315                        }
9316                    } catch (Exception e) {
9317                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9318                                e);
9319                    }
9320                }
9321            }
9322
9323            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9324                if (DEBUG_DEXOPT) {
9325                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9326                }
9327                numberOfPackagesSkipped++;
9328                continue;
9329            }
9330
9331            if (DEBUG_DEXOPT) {
9332                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9333                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9334            }
9335
9336            if (showDialog) {
9337                try {
9338                    ActivityManager.getService().showBootMessage(
9339                            mContext.getResources().getString(R.string.android_upgrading_apk,
9340                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9341                } catch (RemoteException e) {
9342                }
9343                synchronized (mPackages) {
9344                    mDexOptDialogShown = true;
9345                }
9346            }
9347
9348            // If the OTA updates a system app which was previously preopted to a non-preopted state
9349            // the app might end up being verified at runtime. That's because by default the apps
9350            // are verify-profile but for preopted apps there's no profile.
9351            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9352            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9353            // filter (by default 'quicken').
9354            // Note that at this stage unused apps are already filtered.
9355            if (isSystemApp(pkg) &&
9356                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9357                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9358                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9359            }
9360
9361            // checkProfiles is false to avoid merging profiles during boot which
9362            // might interfere with background compilation (b/28612421).
9363            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9364            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9365            // trade-off worth doing to save boot time work.
9366            int primaryDexOptStaus = performDexOptTraced(pkg.packageName,
9367                    false /* checkProfiles */,
9368                    compilerFilter,
9369                    false /* force */,
9370                    bootComplete);
9371
9372            if (pkg.isSystemApp()) {
9373                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9374                // too much boot after an OTA.
9375                mDexManager.dexoptSecondaryDex(pkg.packageName,
9376                        compilerFilter,
9377                        false /* force */,
9378                        true /* compileOnlySharedDex */);
9379            }
9380
9381            // TODO(shubhamajmera): Record secondary dexopt stats.
9382            switch (primaryDexOptStaus) {
9383                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9384                    numberOfPackagesOptimized++;
9385                    break;
9386                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9387                    numberOfPackagesSkipped++;
9388                    break;
9389                case PackageDexOptimizer.DEX_OPT_FAILED:
9390                    numberOfPackagesFailed++;
9391                    break;
9392                default:
9393                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9394                    break;
9395            }
9396        }
9397
9398        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9399                numberOfPackagesFailed };
9400    }
9401
9402    @Override
9403    public void notifyPackageUse(String packageName, int reason) {
9404        synchronized (mPackages) {
9405            final int callingUid = Binder.getCallingUid();
9406            final int callingUserId = UserHandle.getUserId(callingUid);
9407            if (getInstantAppPackageName(callingUid) != null) {
9408                if (!isCallerSameApp(packageName, callingUid)) {
9409                    return;
9410                }
9411            } else {
9412                if (isInstantApp(packageName, callingUserId)) {
9413                    return;
9414                }
9415            }
9416            final PackageParser.Package p = mPackages.get(packageName);
9417            if (p == null) {
9418                return;
9419            }
9420            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9421        }
9422    }
9423
9424    @Override
9425    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9426        int userId = UserHandle.getCallingUserId();
9427        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9428        if (ai == null) {
9429            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9430                + loadingPackageName + ", user=" + userId);
9431            return;
9432        }
9433        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9434    }
9435
9436    @Override
9437    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9438            IDexModuleRegisterCallback callback) {
9439        int userId = UserHandle.getCallingUserId();
9440        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9441        DexManager.RegisterDexModuleResult result;
9442        if (ai == null) {
9443            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9444                     " calling user. package=" + packageName + ", user=" + userId);
9445            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9446        } else {
9447            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9448        }
9449
9450        if (callback != null) {
9451            mHandler.post(() -> {
9452                try {
9453                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9454                } catch (RemoteException e) {
9455                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9456                }
9457            });
9458        }
9459    }
9460
9461    @Override
9462    public boolean performDexOpt(String packageName,
9463            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9464        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9465            return false;
9466        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9467            return false;
9468        }
9469        int dexoptStatus = performDexOptWithStatus(
9470              packageName, checkProfiles, compileReason, force, bootComplete);
9471        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9472    }
9473
9474    /**
9475     * Perform dexopt on the given package and return one of following result:
9476     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9477     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9478     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9479     */
9480    /* package */ int performDexOptWithStatus(String packageName,
9481            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9482        return performDexOptTraced(packageName, checkProfiles,
9483                getCompilerFilterForReason(compileReason), force, bootComplete);
9484    }
9485
9486    @Override
9487    public boolean performDexOptMode(String packageName,
9488            boolean checkProfiles, String targetCompilerFilter, boolean force,
9489            boolean bootComplete) {
9490        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9491            return false;
9492        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9493            return false;
9494        }
9495        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9496                targetCompilerFilter, force, bootComplete);
9497        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9498    }
9499
9500    private int performDexOptTraced(String packageName,
9501                boolean checkProfiles, String targetCompilerFilter, boolean force,
9502                boolean bootComplete) {
9503        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9504        try {
9505            return performDexOptInternal(packageName, checkProfiles,
9506                    targetCompilerFilter, force, bootComplete);
9507        } finally {
9508            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9509        }
9510    }
9511
9512    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9513    // if the package can now be considered up to date for the given filter.
9514    private int performDexOptInternal(String packageName,
9515                boolean checkProfiles, String targetCompilerFilter, boolean force,
9516                boolean bootComplete) {
9517        PackageParser.Package p;
9518        synchronized (mPackages) {
9519            p = mPackages.get(packageName);
9520            if (p == null) {
9521                // Package could not be found. Report failure.
9522                return PackageDexOptimizer.DEX_OPT_FAILED;
9523            }
9524            mPackageUsage.maybeWriteAsync(mPackages);
9525            mCompilerStats.maybeWriteAsync();
9526        }
9527        long callingId = Binder.clearCallingIdentity();
9528        try {
9529            synchronized (mInstallLock) {
9530                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9531                        targetCompilerFilter, force, bootComplete);
9532            }
9533        } finally {
9534            Binder.restoreCallingIdentity(callingId);
9535        }
9536    }
9537
9538    public ArraySet<String> getOptimizablePackages() {
9539        ArraySet<String> pkgs = new ArraySet<String>();
9540        synchronized (mPackages) {
9541            for (PackageParser.Package p : mPackages.values()) {
9542                if (PackageDexOptimizer.canOptimizePackage(p)) {
9543                    pkgs.add(p.packageName);
9544                }
9545            }
9546        }
9547        return pkgs;
9548    }
9549
9550    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9551            boolean checkProfiles, String targetCompilerFilter,
9552            boolean force, boolean bootComplete) {
9553        // Select the dex optimizer based on the force parameter.
9554        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9555        //       allocate an object here.
9556        PackageDexOptimizer pdo = force
9557                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9558                : mPackageDexOptimizer;
9559
9560        // Dexopt all dependencies first. Note: we ignore the return value and march on
9561        // on errors.
9562        // Note that we are going to call performDexOpt on those libraries as many times as
9563        // they are referenced in packages. When we do a batch of performDexOpt (for example
9564        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9565        // and the first package that uses the library will dexopt it. The
9566        // others will see that the compiled code for the library is up to date.
9567        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9568        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9569        if (!deps.isEmpty()) {
9570            for (PackageParser.Package depPackage : deps) {
9571                // TODO: Analyze and investigate if we (should) profile libraries.
9572                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9573                        false /* checkProfiles */,
9574                        targetCompilerFilter,
9575                        getOrCreateCompilerPackageStats(depPackage),
9576                        true /* isUsedByOtherApps */,
9577                        bootComplete);
9578            }
9579        }
9580        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9581                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9582                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9583    }
9584
9585    // Performs dexopt on the used secondary dex files belonging to the given package.
9586    // Returns true if all dex files were process successfully (which could mean either dexopt or
9587    // skip). Returns false if any of the files caused errors.
9588    @Override
9589    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9590            boolean force) {
9591        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9592            return false;
9593        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9594            return false;
9595        }
9596        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force,
9597                /* compileOnlySharedDex*/ false);
9598    }
9599
9600    public boolean performDexOptSecondary(String packageName, int compileReason,
9601            boolean force) {
9602        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9603    }
9604
9605    /**
9606     * Reconcile the information we have about the secondary dex files belonging to
9607     * {@code packagName} and the actual dex files. For all dex files that were
9608     * deleted, update the internal records and delete the generated oat files.
9609     */
9610    @Override
9611    public void reconcileSecondaryDexFiles(String packageName) {
9612        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9613            return;
9614        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9615            return;
9616        }
9617        mDexManager.reconcileSecondaryDexFiles(packageName);
9618    }
9619
9620    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9621    // a reference there.
9622    /*package*/ DexManager getDexManager() {
9623        return mDexManager;
9624    }
9625
9626    /**
9627     * Execute the background dexopt job immediately.
9628     */
9629    @Override
9630    public boolean runBackgroundDexoptJob() {
9631        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9632            return false;
9633        }
9634        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9635    }
9636
9637    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9638        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9639                || p.usesStaticLibraries != null) {
9640            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9641            Set<String> collectedNames = new HashSet<>();
9642            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9643
9644            retValue.remove(p);
9645
9646            return retValue;
9647        } else {
9648            return Collections.emptyList();
9649        }
9650    }
9651
9652    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9653            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9654        if (!collectedNames.contains(p.packageName)) {
9655            collectedNames.add(p.packageName);
9656            collected.add(p);
9657
9658            if (p.usesLibraries != null) {
9659                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9660                        null, collected, collectedNames);
9661            }
9662            if (p.usesOptionalLibraries != null) {
9663                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9664                        null, collected, collectedNames);
9665            }
9666            if (p.usesStaticLibraries != null) {
9667                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9668                        p.usesStaticLibrariesVersions, collected, collectedNames);
9669            }
9670        }
9671    }
9672
9673    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9674            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9675        final int libNameCount = libs.size();
9676        for (int i = 0; i < libNameCount; i++) {
9677            String libName = libs.get(i);
9678            int version = (versions != null && versions.length == libNameCount)
9679                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9680            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9681            if (libPkg != null) {
9682                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9683            }
9684        }
9685    }
9686
9687    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9688        synchronized (mPackages) {
9689            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9690            if (libEntry != null) {
9691                return mPackages.get(libEntry.apk);
9692            }
9693            return null;
9694        }
9695    }
9696
9697    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9698        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9699        if (versionedLib == null) {
9700            return null;
9701        }
9702        return versionedLib.get(version);
9703    }
9704
9705    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9706        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9707                pkg.staticSharedLibName);
9708        if (versionedLib == null) {
9709            return null;
9710        }
9711        int previousLibVersion = -1;
9712        final int versionCount = versionedLib.size();
9713        for (int i = 0; i < versionCount; i++) {
9714            final int libVersion = versionedLib.keyAt(i);
9715            if (libVersion < pkg.staticSharedLibVersion) {
9716                previousLibVersion = Math.max(previousLibVersion, libVersion);
9717            }
9718        }
9719        if (previousLibVersion >= 0) {
9720            return versionedLib.get(previousLibVersion);
9721        }
9722        return null;
9723    }
9724
9725    public void shutdown() {
9726        mPackageUsage.writeNow(mPackages);
9727        mCompilerStats.writeNow();
9728    }
9729
9730    @Override
9731    public void dumpProfiles(String packageName) {
9732        PackageParser.Package pkg;
9733        synchronized (mPackages) {
9734            pkg = mPackages.get(packageName);
9735            if (pkg == null) {
9736                throw new IllegalArgumentException("Unknown package: " + packageName);
9737            }
9738        }
9739        /* Only the shell, root, or the app user should be able to dump profiles. */
9740        int callingUid = Binder.getCallingUid();
9741        if (callingUid != Process.SHELL_UID &&
9742            callingUid != Process.ROOT_UID &&
9743            callingUid != pkg.applicationInfo.uid) {
9744            throw new SecurityException("dumpProfiles");
9745        }
9746
9747        synchronized (mInstallLock) {
9748            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9749            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9750            try {
9751                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9752                String codePaths = TextUtils.join(";", allCodePaths);
9753                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9754            } catch (InstallerException e) {
9755                Slog.w(TAG, "Failed to dump profiles", e);
9756            }
9757            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9758        }
9759    }
9760
9761    @Override
9762    public void forceDexOpt(String packageName) {
9763        enforceSystemOrRoot("forceDexOpt");
9764
9765        PackageParser.Package pkg;
9766        synchronized (mPackages) {
9767            pkg = mPackages.get(packageName);
9768            if (pkg == null) {
9769                throw new IllegalArgumentException("Unknown package: " + packageName);
9770            }
9771        }
9772
9773        synchronized (mInstallLock) {
9774            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9775
9776            // Whoever is calling forceDexOpt wants a compiled package.
9777            // Don't use profiles since that may cause compilation to be skipped.
9778            final int res = performDexOptInternalWithDependenciesLI(pkg,
9779                    false /* checkProfiles */, getDefaultCompilerFilter(),
9780                    true /* force */,
9781                    true /* bootComplete */);
9782
9783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9784            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9785                throw new IllegalStateException("Failed to dexopt: " + res);
9786            }
9787        }
9788    }
9789
9790    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9791        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9792            Slog.w(TAG, "Unable to update from " + oldPkg.name
9793                    + " to " + newPkg.packageName
9794                    + ": old package not in system partition");
9795            return false;
9796        } else if (mPackages.get(oldPkg.name) != null) {
9797            Slog.w(TAG, "Unable to update from " + oldPkg.name
9798                    + " to " + newPkg.packageName
9799                    + ": old package still exists");
9800            return false;
9801        }
9802        return true;
9803    }
9804
9805    void removeCodePathLI(File codePath) {
9806        if (codePath.isDirectory()) {
9807            try {
9808                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9809            } catch (InstallerException e) {
9810                Slog.w(TAG, "Failed to remove code path", e);
9811            }
9812        } else {
9813            codePath.delete();
9814        }
9815    }
9816
9817    private int[] resolveUserIds(int userId) {
9818        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9819    }
9820
9821    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9822        if (pkg == null) {
9823            Slog.wtf(TAG, "Package was null!", new Throwable());
9824            return;
9825        }
9826        clearAppDataLeafLIF(pkg, userId, flags);
9827        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9828        for (int i = 0; i < childCount; i++) {
9829            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9830        }
9831    }
9832
9833    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9834        final PackageSetting ps;
9835        synchronized (mPackages) {
9836            ps = mSettings.mPackages.get(pkg.packageName);
9837        }
9838        for (int realUserId : resolveUserIds(userId)) {
9839            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9840            try {
9841                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9842                        ceDataInode);
9843            } catch (InstallerException e) {
9844                Slog.w(TAG, String.valueOf(e));
9845            }
9846        }
9847    }
9848
9849    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9850        if (pkg == null) {
9851            Slog.wtf(TAG, "Package was null!", new Throwable());
9852            return;
9853        }
9854        destroyAppDataLeafLIF(pkg, userId, flags);
9855        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9856        for (int i = 0; i < childCount; i++) {
9857            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9858        }
9859    }
9860
9861    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9862        final PackageSetting ps;
9863        synchronized (mPackages) {
9864            ps = mSettings.mPackages.get(pkg.packageName);
9865        }
9866        for (int realUserId : resolveUserIds(userId)) {
9867            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9868            try {
9869                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9870                        ceDataInode);
9871            } catch (InstallerException e) {
9872                Slog.w(TAG, String.valueOf(e));
9873            }
9874            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9875        }
9876    }
9877
9878    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9879        if (pkg == null) {
9880            Slog.wtf(TAG, "Package was null!", new Throwable());
9881            return;
9882        }
9883        destroyAppProfilesLeafLIF(pkg);
9884        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9885        for (int i = 0; i < childCount; i++) {
9886            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9887        }
9888    }
9889
9890    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9891        try {
9892            mInstaller.destroyAppProfiles(pkg.packageName);
9893        } catch (InstallerException e) {
9894            Slog.w(TAG, String.valueOf(e));
9895        }
9896    }
9897
9898    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9899        if (pkg == null) {
9900            Slog.wtf(TAG, "Package was null!", new Throwable());
9901            return;
9902        }
9903        clearAppProfilesLeafLIF(pkg);
9904        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9905        for (int i = 0; i < childCount; i++) {
9906            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9907        }
9908    }
9909
9910    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9911        try {
9912            mInstaller.clearAppProfiles(pkg.packageName);
9913        } catch (InstallerException e) {
9914            Slog.w(TAG, String.valueOf(e));
9915        }
9916    }
9917
9918    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9919            long lastUpdateTime) {
9920        // Set parent install/update time
9921        PackageSetting ps = (PackageSetting) pkg.mExtras;
9922        if (ps != null) {
9923            ps.firstInstallTime = firstInstallTime;
9924            ps.lastUpdateTime = lastUpdateTime;
9925        }
9926        // Set children install/update time
9927        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9928        for (int i = 0; i < childCount; i++) {
9929            PackageParser.Package childPkg = pkg.childPackages.get(i);
9930            ps = (PackageSetting) childPkg.mExtras;
9931            if (ps != null) {
9932                ps.firstInstallTime = firstInstallTime;
9933                ps.lastUpdateTime = lastUpdateTime;
9934            }
9935        }
9936    }
9937
9938    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9939            PackageParser.Package changingLib) {
9940        if (file.path != null) {
9941            usesLibraryFiles.add(file.path);
9942            return;
9943        }
9944        PackageParser.Package p = mPackages.get(file.apk);
9945        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9946            // If we are doing this while in the middle of updating a library apk,
9947            // then we need to make sure to use that new apk for determining the
9948            // dependencies here.  (We haven't yet finished committing the new apk
9949            // to the package manager state.)
9950            if (p == null || p.packageName.equals(changingLib.packageName)) {
9951                p = changingLib;
9952            }
9953        }
9954        if (p != null) {
9955            usesLibraryFiles.addAll(p.getAllCodePaths());
9956            if (p.usesLibraryFiles != null) {
9957                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9958            }
9959        }
9960    }
9961
9962    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9963            PackageParser.Package changingLib) throws PackageManagerException {
9964        if (pkg == null) {
9965            return;
9966        }
9967        ArraySet<String> usesLibraryFiles = null;
9968        if (pkg.usesLibraries != null) {
9969            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9970                    null, null, pkg.packageName, changingLib, true, null);
9971        }
9972        if (pkg.usesStaticLibraries != null) {
9973            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9974                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9975                    pkg.packageName, changingLib, true, usesLibraryFiles);
9976        }
9977        if (pkg.usesOptionalLibraries != null) {
9978            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9979                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9980        }
9981        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9982            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9983        } else {
9984            pkg.usesLibraryFiles = null;
9985        }
9986    }
9987
9988    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9989            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9990            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9991            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9992            throws PackageManagerException {
9993        final int libCount = requestedLibraries.size();
9994        for (int i = 0; i < libCount; i++) {
9995            final String libName = requestedLibraries.get(i);
9996            final int libVersion = requiredVersions != null ? requiredVersions[i]
9997                    : SharedLibraryInfo.VERSION_UNDEFINED;
9998            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9999            if (libEntry == null) {
10000                if (required) {
10001                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10002                            "Package " + packageName + " requires unavailable shared library "
10003                                    + libName + "; failing!");
10004                } else if (DEBUG_SHARED_LIBRARIES) {
10005                    Slog.i(TAG, "Package " + packageName
10006                            + " desires unavailable shared library "
10007                            + libName + "; ignoring!");
10008                }
10009            } else {
10010                if (requiredVersions != null && requiredCertDigests != null) {
10011                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10012                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10013                            "Package " + packageName + " requires unavailable static shared"
10014                                    + " library " + libName + " version "
10015                                    + libEntry.info.getVersion() + "; failing!");
10016                    }
10017
10018                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10019                    if (libPkg == null) {
10020                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10021                                "Package " + packageName + " requires unavailable static shared"
10022                                        + " library; failing!");
10023                    }
10024
10025                    String expectedCertDigest = requiredCertDigests[i];
10026                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10027                                libPkg.mSignatures[0]);
10028                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10029                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10030                                "Package " + packageName + " requires differently signed" +
10031                                        " static shared library; failing!");
10032                    }
10033                }
10034
10035                if (outUsedLibraries == null) {
10036                    outUsedLibraries = new ArraySet<>();
10037                }
10038                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10039            }
10040        }
10041        return outUsedLibraries;
10042    }
10043
10044    private static boolean hasString(List<String> list, List<String> which) {
10045        if (list == null) {
10046            return false;
10047        }
10048        for (int i=list.size()-1; i>=0; i--) {
10049            for (int j=which.size()-1; j>=0; j--) {
10050                if (which.get(j).equals(list.get(i))) {
10051                    return true;
10052                }
10053            }
10054        }
10055        return false;
10056    }
10057
10058    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10059            PackageParser.Package changingPkg) {
10060        ArrayList<PackageParser.Package> res = null;
10061        for (PackageParser.Package pkg : mPackages.values()) {
10062            if (changingPkg != null
10063                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10064                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10065                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10066                            changingPkg.staticSharedLibName)) {
10067                return null;
10068            }
10069            if (res == null) {
10070                res = new ArrayList<>();
10071            }
10072            res.add(pkg);
10073            try {
10074                updateSharedLibrariesLPr(pkg, changingPkg);
10075            } catch (PackageManagerException e) {
10076                // If a system app update or an app and a required lib missing we
10077                // delete the package and for updated system apps keep the data as
10078                // it is better for the user to reinstall than to be in an limbo
10079                // state. Also libs disappearing under an app should never happen
10080                // - just in case.
10081                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10082                    final int flags = pkg.isUpdatedSystemApp()
10083                            ? PackageManager.DELETE_KEEP_DATA : 0;
10084                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10085                            flags , null, true, null);
10086                }
10087                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10088            }
10089        }
10090        return res;
10091    }
10092
10093    /**
10094     * Derive the value of the {@code cpuAbiOverride} based on the provided
10095     * value and an optional stored value from the package settings.
10096     */
10097    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10098        String cpuAbiOverride = null;
10099
10100        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10101            cpuAbiOverride = null;
10102        } else if (abiOverride != null) {
10103            cpuAbiOverride = abiOverride;
10104        } else if (settings != null) {
10105            cpuAbiOverride = settings.cpuAbiOverrideString;
10106        }
10107
10108        return cpuAbiOverride;
10109    }
10110
10111    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10112            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10113                    throws PackageManagerException {
10114        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10115        // If the package has children and this is the first dive in the function
10116        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10117        // whether all packages (parent and children) would be successfully scanned
10118        // before the actual scan since scanning mutates internal state and we want
10119        // to atomically install the package and its children.
10120        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10121            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10122                scanFlags |= SCAN_CHECK_ONLY;
10123            }
10124        } else {
10125            scanFlags &= ~SCAN_CHECK_ONLY;
10126        }
10127
10128        final PackageParser.Package scannedPkg;
10129        try {
10130            // Scan the parent
10131            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10132            // Scan the children
10133            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10134            for (int i = 0; i < childCount; i++) {
10135                PackageParser.Package childPkg = pkg.childPackages.get(i);
10136                scanPackageLI(childPkg, policyFlags,
10137                        scanFlags, currentTime, user);
10138            }
10139        } finally {
10140            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10141        }
10142
10143        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10144            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10145        }
10146
10147        return scannedPkg;
10148    }
10149
10150    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10151            int scanFlags, long currentTime, @Nullable UserHandle user)
10152                    throws PackageManagerException {
10153        boolean success = false;
10154        try {
10155            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10156                    currentTime, user);
10157            success = true;
10158            return res;
10159        } finally {
10160            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10161                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10162                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10163                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10164                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10165            }
10166        }
10167    }
10168
10169    /**
10170     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10171     */
10172    private static boolean apkHasCode(String fileName) {
10173        StrictJarFile jarFile = null;
10174        try {
10175            jarFile = new StrictJarFile(fileName,
10176                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10177            return jarFile.findEntry("classes.dex") != null;
10178        } catch (IOException ignore) {
10179        } finally {
10180            try {
10181                if (jarFile != null) {
10182                    jarFile.close();
10183                }
10184            } catch (IOException ignore) {}
10185        }
10186        return false;
10187    }
10188
10189    /**
10190     * Enforces code policy for the package. This ensures that if an APK has
10191     * declared hasCode="true" in its manifest that the APK actually contains
10192     * code.
10193     *
10194     * @throws PackageManagerException If bytecode could not be found when it should exist
10195     */
10196    private static void assertCodePolicy(PackageParser.Package pkg)
10197            throws PackageManagerException {
10198        final boolean shouldHaveCode =
10199                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10200        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10201            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10202                    "Package " + pkg.baseCodePath + " code is missing");
10203        }
10204
10205        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10206            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10207                final boolean splitShouldHaveCode =
10208                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10209                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10210                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10211                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10212                }
10213            }
10214        }
10215    }
10216
10217    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10218            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10219                    throws PackageManagerException {
10220        if (DEBUG_PACKAGE_SCANNING) {
10221            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10222                Log.d(TAG, "Scanning package " + pkg.packageName);
10223        }
10224
10225        applyPolicy(pkg, policyFlags);
10226
10227        assertPackageIsValid(pkg, policyFlags, scanFlags);
10228
10229        // Initialize package source and resource directories
10230        final File scanFile = new File(pkg.codePath);
10231        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10232        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10233
10234        SharedUserSetting suid = null;
10235        PackageSetting pkgSetting = null;
10236
10237        // Getting the package setting may have a side-effect, so if we
10238        // are only checking if scan would succeed, stash a copy of the
10239        // old setting to restore at the end.
10240        PackageSetting nonMutatedPs = null;
10241
10242        // We keep references to the derived CPU Abis from settings in oder to reuse
10243        // them in the case where we're not upgrading or booting for the first time.
10244        String primaryCpuAbiFromSettings = null;
10245        String secondaryCpuAbiFromSettings = null;
10246
10247        // writer
10248        synchronized (mPackages) {
10249            if (pkg.mSharedUserId != null) {
10250                // SIDE EFFECTS; may potentially allocate a new shared user
10251                suid = mSettings.getSharedUserLPw(
10252                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10253                if (DEBUG_PACKAGE_SCANNING) {
10254                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10255                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10256                                + "): packages=" + suid.packages);
10257                }
10258            }
10259
10260            // Check if we are renaming from an original package name.
10261            PackageSetting origPackage = null;
10262            String realName = null;
10263            if (pkg.mOriginalPackages != null) {
10264                // This package may need to be renamed to a previously
10265                // installed name.  Let's check on that...
10266                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10267                if (pkg.mOriginalPackages.contains(renamed)) {
10268                    // This package had originally been installed as the
10269                    // original name, and we have already taken care of
10270                    // transitioning to the new one.  Just update the new
10271                    // one to continue using the old name.
10272                    realName = pkg.mRealPackage;
10273                    if (!pkg.packageName.equals(renamed)) {
10274                        // Callers into this function may have already taken
10275                        // care of renaming the package; only do it here if
10276                        // it is not already done.
10277                        pkg.setPackageName(renamed);
10278                    }
10279                } else {
10280                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10281                        if ((origPackage = mSettings.getPackageLPr(
10282                                pkg.mOriginalPackages.get(i))) != null) {
10283                            // We do have the package already installed under its
10284                            // original name...  should we use it?
10285                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10286                                // New package is not compatible with original.
10287                                origPackage = null;
10288                                continue;
10289                            } else if (origPackage.sharedUser != null) {
10290                                // Make sure uid is compatible between packages.
10291                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10292                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10293                                            + " to " + pkg.packageName + ": old uid "
10294                                            + origPackage.sharedUser.name
10295                                            + " differs from " + pkg.mSharedUserId);
10296                                    origPackage = null;
10297                                    continue;
10298                                }
10299                                // TODO: Add case when shared user id is added [b/28144775]
10300                            } else {
10301                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10302                                        + pkg.packageName + " to old name " + origPackage.name);
10303                            }
10304                            break;
10305                        }
10306                    }
10307                }
10308            }
10309
10310            if (mTransferedPackages.contains(pkg.packageName)) {
10311                Slog.w(TAG, "Package " + pkg.packageName
10312                        + " was transferred to another, but its .apk remains");
10313            }
10314
10315            // See comments in nonMutatedPs declaration
10316            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10317                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10318                if (foundPs != null) {
10319                    nonMutatedPs = new PackageSetting(foundPs);
10320                }
10321            }
10322
10323            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10324                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10325                if (foundPs != null) {
10326                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10327                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10328                }
10329            }
10330
10331            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10332            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10333                PackageManagerService.reportSettingsProblem(Log.WARN,
10334                        "Package " + pkg.packageName + " shared user changed from "
10335                                + (pkgSetting.sharedUser != null
10336                                        ? pkgSetting.sharedUser.name : "<nothing>")
10337                                + " to "
10338                                + (suid != null ? suid.name : "<nothing>")
10339                                + "; replacing with new");
10340                pkgSetting = null;
10341            }
10342            final PackageSetting oldPkgSetting =
10343                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10344            final PackageSetting disabledPkgSetting =
10345                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10346
10347            String[] usesStaticLibraries = null;
10348            if (pkg.usesStaticLibraries != null) {
10349                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10350                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10351            }
10352
10353            if (pkgSetting == null) {
10354                final String parentPackageName = (pkg.parentPackage != null)
10355                        ? pkg.parentPackage.packageName : null;
10356                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10357                // REMOVE SharedUserSetting from method; update in a separate call
10358                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10359                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10360                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10361                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10362                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10363                        true /*allowInstall*/, instantApp, parentPackageName,
10364                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10365                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10366                // SIDE EFFECTS; updates system state; move elsewhere
10367                if (origPackage != null) {
10368                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10369                }
10370                mSettings.addUserToSettingLPw(pkgSetting);
10371            } else {
10372                // REMOVE SharedUserSetting from method; update in a separate call.
10373                //
10374                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10375                // secondaryCpuAbi are not known at this point so we always update them
10376                // to null here, only to reset them at a later point.
10377                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10378                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10379                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10380                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10381                        UserManagerService.getInstance(), usesStaticLibraries,
10382                        pkg.usesStaticLibrariesVersions);
10383            }
10384            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10385            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10386
10387            // SIDE EFFECTS; modifies system state; move elsewhere
10388            if (pkgSetting.origPackage != null) {
10389                // If we are first transitioning from an original package,
10390                // fix up the new package's name now.  We need to do this after
10391                // looking up the package under its new name, so getPackageLP
10392                // can take care of fiddling things correctly.
10393                pkg.setPackageName(origPackage.name);
10394
10395                // File a report about this.
10396                String msg = "New package " + pkgSetting.realName
10397                        + " renamed to replace old package " + pkgSetting.name;
10398                reportSettingsProblem(Log.WARN, msg);
10399
10400                // Make a note of it.
10401                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10402                    mTransferedPackages.add(origPackage.name);
10403                }
10404
10405                // No longer need to retain this.
10406                pkgSetting.origPackage = null;
10407            }
10408
10409            // SIDE EFFECTS; modifies system state; move elsewhere
10410            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10411                // Make a note of it.
10412                mTransferedPackages.add(pkg.packageName);
10413            }
10414
10415            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10416                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10417            }
10418
10419            if ((scanFlags & SCAN_BOOTING) == 0
10420                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10421                // Check all shared libraries and map to their actual file path.
10422                // We only do this here for apps not on a system dir, because those
10423                // are the only ones that can fail an install due to this.  We
10424                // will take care of the system apps by updating all of their
10425                // library paths after the scan is done. Also during the initial
10426                // scan don't update any libs as we do this wholesale after all
10427                // apps are scanned to avoid dependency based scanning.
10428                updateSharedLibrariesLPr(pkg, null);
10429            }
10430
10431            if (mFoundPolicyFile) {
10432                SELinuxMMAC.assignSeInfoValue(pkg);
10433            }
10434            pkg.applicationInfo.uid = pkgSetting.appId;
10435            pkg.mExtras = pkgSetting;
10436
10437
10438            // Static shared libs have same package with different versions where
10439            // we internally use a synthetic package name to allow multiple versions
10440            // of the same package, therefore we need to compare signatures against
10441            // the package setting for the latest library version.
10442            PackageSetting signatureCheckPs = pkgSetting;
10443            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10444                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10445                if (libraryEntry != null) {
10446                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10447                }
10448            }
10449
10450            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10451                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10452                    // We just determined the app is signed correctly, so bring
10453                    // over the latest parsed certs.
10454                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10455                } else {
10456                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10457                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10458                                "Package " + pkg.packageName + " upgrade keys do not match the "
10459                                + "previously installed version");
10460                    } else {
10461                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10462                        String msg = "System package " + pkg.packageName
10463                                + " signature changed; retaining data.";
10464                        reportSettingsProblem(Log.WARN, msg);
10465                    }
10466                }
10467            } else {
10468                try {
10469                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10470                    verifySignaturesLP(signatureCheckPs, pkg);
10471                    // We just determined the app is signed correctly, so bring
10472                    // over the latest parsed certs.
10473                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10474                } catch (PackageManagerException e) {
10475                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10476                        throw e;
10477                    }
10478                    // The signature has changed, but this package is in the system
10479                    // image...  let's recover!
10480                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10481                    // However...  if this package is part of a shared user, but it
10482                    // doesn't match the signature of the shared user, let's fail.
10483                    // What this means is that you can't change the signatures
10484                    // associated with an overall shared user, which doesn't seem all
10485                    // that unreasonable.
10486                    if (signatureCheckPs.sharedUser != null) {
10487                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10488                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10489                            throw new PackageManagerException(
10490                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10491                                    "Signature mismatch for shared user: "
10492                                            + pkgSetting.sharedUser);
10493                        }
10494                    }
10495                    // File a report about this.
10496                    String msg = "System package " + pkg.packageName
10497                            + " signature changed; retaining data.";
10498                    reportSettingsProblem(Log.WARN, msg);
10499                }
10500            }
10501
10502            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10503                // This package wants to adopt ownership of permissions from
10504                // another package.
10505                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10506                    final String origName = pkg.mAdoptPermissions.get(i);
10507                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10508                    if (orig != null) {
10509                        if (verifyPackageUpdateLPr(orig, pkg)) {
10510                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10511                                    + pkg.packageName);
10512                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10513                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10514                        }
10515                    }
10516                }
10517            }
10518        }
10519
10520        pkg.applicationInfo.processName = fixProcessName(
10521                pkg.applicationInfo.packageName,
10522                pkg.applicationInfo.processName);
10523
10524        if (pkg != mPlatformPackage) {
10525            // Get all of our default paths setup
10526            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10527        }
10528
10529        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10530
10531        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10532            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10533                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10534                final boolean extractNativeLibs = !pkg.isLibrary();
10535                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10536                        mAppLib32InstallDir);
10537                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10538
10539                // Some system apps still use directory structure for native libraries
10540                // in which case we might end up not detecting abi solely based on apk
10541                // structure. Try to detect abi based on directory structure.
10542                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10543                        pkg.applicationInfo.primaryCpuAbi == null) {
10544                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10545                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10546                }
10547            } else {
10548                // This is not a first boot or an upgrade, don't bother deriving the
10549                // ABI during the scan. Instead, trust the value that was stored in the
10550                // package setting.
10551                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10552                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10553
10554                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10555
10556                if (DEBUG_ABI_SELECTION) {
10557                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10558                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10559                        pkg.applicationInfo.secondaryCpuAbi);
10560                }
10561            }
10562        } else {
10563            if ((scanFlags & SCAN_MOVE) != 0) {
10564                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10565                // but we already have this packages package info in the PackageSetting. We just
10566                // use that and derive the native library path based on the new codepath.
10567                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10568                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10569            }
10570
10571            // Set native library paths again. For moves, the path will be updated based on the
10572            // ABIs we've determined above. For non-moves, the path will be updated based on the
10573            // ABIs we determined during compilation, but the path will depend on the final
10574            // package path (after the rename away from the stage path).
10575            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10576        }
10577
10578        // This is a special case for the "system" package, where the ABI is
10579        // dictated by the zygote configuration (and init.rc). We should keep track
10580        // of this ABI so that we can deal with "normal" applications that run under
10581        // the same UID correctly.
10582        if (mPlatformPackage == pkg) {
10583            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10584                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10585        }
10586
10587        // If there's a mismatch between the abi-override in the package setting
10588        // and the abiOverride specified for the install. Warn about this because we
10589        // would've already compiled the app without taking the package setting into
10590        // account.
10591        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10592            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10593                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10594                        " for package " + pkg.packageName);
10595            }
10596        }
10597
10598        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10599        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10600        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10601
10602        // Copy the derived override back to the parsed package, so that we can
10603        // update the package settings accordingly.
10604        pkg.cpuAbiOverride = cpuAbiOverride;
10605
10606        if (DEBUG_ABI_SELECTION) {
10607            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10608                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10609                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10610        }
10611
10612        // Push the derived path down into PackageSettings so we know what to
10613        // clean up at uninstall time.
10614        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10615
10616        if (DEBUG_ABI_SELECTION) {
10617            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10618                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10619                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10620        }
10621
10622        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10623        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10624            // We don't do this here during boot because we can do it all
10625            // at once after scanning all existing packages.
10626            //
10627            // We also do this *before* we perform dexopt on this package, so that
10628            // we can avoid redundant dexopts, and also to make sure we've got the
10629            // code and package path correct.
10630            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10631        }
10632
10633        if (mFactoryTest && pkg.requestedPermissions.contains(
10634                android.Manifest.permission.FACTORY_TEST)) {
10635            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10636        }
10637
10638        if (isSystemApp(pkg)) {
10639            pkgSetting.isOrphaned = true;
10640        }
10641
10642        // Take care of first install / last update times.
10643        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10644        if (currentTime != 0) {
10645            if (pkgSetting.firstInstallTime == 0) {
10646                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10647            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10648                pkgSetting.lastUpdateTime = currentTime;
10649            }
10650        } else if (pkgSetting.firstInstallTime == 0) {
10651            // We need *something*.  Take time time stamp of the file.
10652            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10653        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10654            if (scanFileTime != pkgSetting.timeStamp) {
10655                // A package on the system image has changed; consider this
10656                // to be an update.
10657                pkgSetting.lastUpdateTime = scanFileTime;
10658            }
10659        }
10660        pkgSetting.setTimeStamp(scanFileTime);
10661
10662        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10663            if (nonMutatedPs != null) {
10664                synchronized (mPackages) {
10665                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10666                }
10667            }
10668        } else {
10669            final int userId = user == null ? 0 : user.getIdentifier();
10670            // Modify state for the given package setting
10671            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10672                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10673            if (pkgSetting.getInstantApp(userId)) {
10674                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10675            }
10676        }
10677        return pkg;
10678    }
10679
10680    /**
10681     * Applies policy to the parsed package based upon the given policy flags.
10682     * Ensures the package is in a good state.
10683     * <p>
10684     * Implementation detail: This method must NOT have any side effect. It would
10685     * ideally be static, but, it requires locks to read system state.
10686     */
10687    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10688        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10689            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10690            if (pkg.applicationInfo.isDirectBootAware()) {
10691                // we're direct boot aware; set for all components
10692                for (PackageParser.Service s : pkg.services) {
10693                    s.info.encryptionAware = s.info.directBootAware = true;
10694                }
10695                for (PackageParser.Provider p : pkg.providers) {
10696                    p.info.encryptionAware = p.info.directBootAware = true;
10697                }
10698                for (PackageParser.Activity a : pkg.activities) {
10699                    a.info.encryptionAware = a.info.directBootAware = true;
10700                }
10701                for (PackageParser.Activity r : pkg.receivers) {
10702                    r.info.encryptionAware = r.info.directBootAware = true;
10703                }
10704            }
10705        } else {
10706            // Only allow system apps to be flagged as core apps.
10707            pkg.coreApp = false;
10708            // clear flags not applicable to regular apps
10709            pkg.applicationInfo.privateFlags &=
10710                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10711            pkg.applicationInfo.privateFlags &=
10712                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10713        }
10714        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10715
10716        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10717            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10718        }
10719
10720        if (!isSystemApp(pkg)) {
10721            // Only system apps can use these features.
10722            pkg.mOriginalPackages = null;
10723            pkg.mRealPackage = null;
10724            pkg.mAdoptPermissions = null;
10725        }
10726    }
10727
10728    /**
10729     * Asserts the parsed package is valid according to the given policy. If the
10730     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10731     * <p>
10732     * Implementation detail: This method must NOT have any side effects. It would
10733     * ideally be static, but, it requires locks to read system state.
10734     *
10735     * @throws PackageManagerException If the package fails any of the validation checks
10736     */
10737    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10738            throws PackageManagerException {
10739        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10740            assertCodePolicy(pkg);
10741        }
10742
10743        if (pkg.applicationInfo.getCodePath() == null ||
10744                pkg.applicationInfo.getResourcePath() == null) {
10745            // Bail out. The resource and code paths haven't been set.
10746            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10747                    "Code and resource paths haven't been set correctly");
10748        }
10749
10750        // Make sure we're not adding any bogus keyset info
10751        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10752        ksms.assertScannedPackageValid(pkg);
10753
10754        synchronized (mPackages) {
10755            // The special "android" package can only be defined once
10756            if (pkg.packageName.equals("android")) {
10757                if (mAndroidApplication != null) {
10758                    Slog.w(TAG, "*************************************************");
10759                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10760                    Slog.w(TAG, " codePath=" + pkg.codePath);
10761                    Slog.w(TAG, "*************************************************");
10762                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10763                            "Core android package being redefined.  Skipping.");
10764                }
10765            }
10766
10767            // A package name must be unique; don't allow duplicates
10768            if (mPackages.containsKey(pkg.packageName)) {
10769                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10770                        "Application package " + pkg.packageName
10771                        + " already installed.  Skipping duplicate.");
10772            }
10773
10774            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10775                // Static libs have a synthetic package name containing the version
10776                // but we still want the base name to be unique.
10777                if (mPackages.containsKey(pkg.manifestPackageName)) {
10778                    throw new PackageManagerException(
10779                            "Duplicate static shared lib provider package");
10780                }
10781
10782                // Static shared libraries should have at least O target SDK
10783                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10784                    throw new PackageManagerException(
10785                            "Packages declaring static-shared libs must target O SDK or higher");
10786                }
10787
10788                // Package declaring static a shared lib cannot be instant apps
10789                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10790                    throw new PackageManagerException(
10791                            "Packages declaring static-shared libs cannot be instant apps");
10792                }
10793
10794                // Package declaring static a shared lib cannot be renamed since the package
10795                // name is synthetic and apps can't code around package manager internals.
10796                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10797                    throw new PackageManagerException(
10798                            "Packages declaring static-shared libs cannot be renamed");
10799                }
10800
10801                // Package declaring static a shared lib cannot declare child packages
10802                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10803                    throw new PackageManagerException(
10804                            "Packages declaring static-shared libs cannot have child packages");
10805                }
10806
10807                // Package declaring static a shared lib cannot declare dynamic libs
10808                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10809                    throw new PackageManagerException(
10810                            "Packages declaring static-shared libs cannot declare dynamic libs");
10811                }
10812
10813                // Package declaring static a shared lib cannot declare shared users
10814                if (pkg.mSharedUserId != null) {
10815                    throw new PackageManagerException(
10816                            "Packages declaring static-shared libs cannot declare shared users");
10817                }
10818
10819                // Static shared libs cannot declare activities
10820                if (!pkg.activities.isEmpty()) {
10821                    throw new PackageManagerException(
10822                            "Static shared libs cannot declare activities");
10823                }
10824
10825                // Static shared libs cannot declare services
10826                if (!pkg.services.isEmpty()) {
10827                    throw new PackageManagerException(
10828                            "Static shared libs cannot declare services");
10829                }
10830
10831                // Static shared libs cannot declare providers
10832                if (!pkg.providers.isEmpty()) {
10833                    throw new PackageManagerException(
10834                            "Static shared libs cannot declare content providers");
10835                }
10836
10837                // Static shared libs cannot declare receivers
10838                if (!pkg.receivers.isEmpty()) {
10839                    throw new PackageManagerException(
10840                            "Static shared libs cannot declare broadcast receivers");
10841                }
10842
10843                // Static shared libs cannot declare permission groups
10844                if (!pkg.permissionGroups.isEmpty()) {
10845                    throw new PackageManagerException(
10846                            "Static shared libs cannot declare permission groups");
10847                }
10848
10849                // Static shared libs cannot declare permissions
10850                if (!pkg.permissions.isEmpty()) {
10851                    throw new PackageManagerException(
10852                            "Static shared libs cannot declare permissions");
10853                }
10854
10855                // Static shared libs cannot declare protected broadcasts
10856                if (pkg.protectedBroadcasts != null) {
10857                    throw new PackageManagerException(
10858                            "Static shared libs cannot declare protected broadcasts");
10859                }
10860
10861                // Static shared libs cannot be overlay targets
10862                if (pkg.mOverlayTarget != null) {
10863                    throw new PackageManagerException(
10864                            "Static shared libs cannot be overlay targets");
10865                }
10866
10867                // The version codes must be ordered as lib versions
10868                int minVersionCode = Integer.MIN_VALUE;
10869                int maxVersionCode = Integer.MAX_VALUE;
10870
10871                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10872                        pkg.staticSharedLibName);
10873                if (versionedLib != null) {
10874                    final int versionCount = versionedLib.size();
10875                    for (int i = 0; i < versionCount; i++) {
10876                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10877                        final int libVersionCode = libInfo.getDeclaringPackage()
10878                                .getVersionCode();
10879                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10880                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10881                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10882                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10883                        } else {
10884                            minVersionCode = maxVersionCode = libVersionCode;
10885                            break;
10886                        }
10887                    }
10888                }
10889                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10890                    throw new PackageManagerException("Static shared"
10891                            + " lib version codes must be ordered as lib versions");
10892                }
10893            }
10894
10895            // Only privileged apps and updated privileged apps can add child packages.
10896            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10897                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10898                    throw new PackageManagerException("Only privileged apps can add child "
10899                            + "packages. Ignoring package " + pkg.packageName);
10900                }
10901                final int childCount = pkg.childPackages.size();
10902                for (int i = 0; i < childCount; i++) {
10903                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10904                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10905                            childPkg.packageName)) {
10906                        throw new PackageManagerException("Can't override child of "
10907                                + "another disabled app. Ignoring package " + pkg.packageName);
10908                    }
10909                }
10910            }
10911
10912            // If we're only installing presumed-existing packages, require that the
10913            // scanned APK is both already known and at the path previously established
10914            // for it.  Previously unknown packages we pick up normally, but if we have an
10915            // a priori expectation about this package's install presence, enforce it.
10916            // With a singular exception for new system packages. When an OTA contains
10917            // a new system package, we allow the codepath to change from a system location
10918            // to the user-installed location. If we don't allow this change, any newer,
10919            // user-installed version of the application will be ignored.
10920            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10921                if (mExpectingBetter.containsKey(pkg.packageName)) {
10922                    logCriticalInfo(Log.WARN,
10923                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10924                } else {
10925                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10926                    if (known != null) {
10927                        if (DEBUG_PACKAGE_SCANNING) {
10928                            Log.d(TAG, "Examining " + pkg.codePath
10929                                    + " and requiring known paths " + known.codePathString
10930                                    + " & " + known.resourcePathString);
10931                        }
10932                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10933                                || !pkg.applicationInfo.getResourcePath().equals(
10934                                        known.resourcePathString)) {
10935                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10936                                    "Application package " + pkg.packageName
10937                                    + " found at " + pkg.applicationInfo.getCodePath()
10938                                    + " but expected at " + known.codePathString
10939                                    + "; ignoring.");
10940                        }
10941                    }
10942                }
10943            }
10944
10945            // Verify that this new package doesn't have any content providers
10946            // that conflict with existing packages.  Only do this if the
10947            // package isn't already installed, since we don't want to break
10948            // things that are installed.
10949            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10950                final int N = pkg.providers.size();
10951                int i;
10952                for (i=0; i<N; i++) {
10953                    PackageParser.Provider p = pkg.providers.get(i);
10954                    if (p.info.authority != null) {
10955                        String names[] = p.info.authority.split(";");
10956                        for (int j = 0; j < names.length; j++) {
10957                            if (mProvidersByAuthority.containsKey(names[j])) {
10958                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10959                                final String otherPackageName =
10960                                        ((other != null && other.getComponentName() != null) ?
10961                                                other.getComponentName().getPackageName() : "?");
10962                                throw new PackageManagerException(
10963                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10964                                        "Can't install because provider name " + names[j]
10965                                                + " (in package " + pkg.applicationInfo.packageName
10966                                                + ") is already used by " + otherPackageName);
10967                            }
10968                        }
10969                    }
10970                }
10971            }
10972        }
10973    }
10974
10975    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10976            int type, String declaringPackageName, int declaringVersionCode) {
10977        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10978        if (versionedLib == null) {
10979            versionedLib = new SparseArray<>();
10980            mSharedLibraries.put(name, versionedLib);
10981            if (type == SharedLibraryInfo.TYPE_STATIC) {
10982                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10983            }
10984        } else if (versionedLib.indexOfKey(version) >= 0) {
10985            return false;
10986        }
10987        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10988                version, type, declaringPackageName, declaringVersionCode);
10989        versionedLib.put(version, libEntry);
10990        return true;
10991    }
10992
10993    private boolean removeSharedLibraryLPw(String name, int version) {
10994        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10995        if (versionedLib == null) {
10996            return false;
10997        }
10998        final int libIdx = versionedLib.indexOfKey(version);
10999        if (libIdx < 0) {
11000            return false;
11001        }
11002        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11003        versionedLib.remove(version);
11004        if (versionedLib.size() <= 0) {
11005            mSharedLibraries.remove(name);
11006            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11007                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11008                        .getPackageName());
11009            }
11010        }
11011        return true;
11012    }
11013
11014    /**
11015     * Adds a scanned package to the system. When this method is finished, the package will
11016     * be available for query, resolution, etc...
11017     */
11018    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11019            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11020        final String pkgName = pkg.packageName;
11021        if (mCustomResolverComponentName != null &&
11022                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11023            setUpCustomResolverActivity(pkg);
11024        }
11025
11026        if (pkg.packageName.equals("android")) {
11027            synchronized (mPackages) {
11028                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11029                    // Set up information for our fall-back user intent resolution activity.
11030                    mPlatformPackage = pkg;
11031                    pkg.mVersionCode = mSdkVersion;
11032                    mAndroidApplication = pkg.applicationInfo;
11033                    if (!mResolverReplaced) {
11034                        mResolveActivity.applicationInfo = mAndroidApplication;
11035                        mResolveActivity.name = ResolverActivity.class.getName();
11036                        mResolveActivity.packageName = mAndroidApplication.packageName;
11037                        mResolveActivity.processName = "system:ui";
11038                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11039                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11040                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11041                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11042                        mResolveActivity.exported = true;
11043                        mResolveActivity.enabled = true;
11044                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11045                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11046                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11047                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11048                                | ActivityInfo.CONFIG_ORIENTATION
11049                                | ActivityInfo.CONFIG_KEYBOARD
11050                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11051                        mResolveInfo.activityInfo = mResolveActivity;
11052                        mResolveInfo.priority = 0;
11053                        mResolveInfo.preferredOrder = 0;
11054                        mResolveInfo.match = 0;
11055                        mResolveComponentName = new ComponentName(
11056                                mAndroidApplication.packageName, mResolveActivity.name);
11057                    }
11058                }
11059            }
11060        }
11061
11062        ArrayList<PackageParser.Package> clientLibPkgs = null;
11063        // writer
11064        synchronized (mPackages) {
11065            boolean hasStaticSharedLibs = false;
11066
11067            // Any app can add new static shared libraries
11068            if (pkg.staticSharedLibName != null) {
11069                // Static shared libs don't allow renaming as they have synthetic package
11070                // names to allow install of multiple versions, so use name from manifest.
11071                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11072                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11073                        pkg.manifestPackageName, pkg.mVersionCode)) {
11074                    hasStaticSharedLibs = true;
11075                } else {
11076                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11077                                + pkg.staticSharedLibName + " already exists; skipping");
11078                }
11079                // Static shared libs cannot be updated once installed since they
11080                // use synthetic package name which includes the version code, so
11081                // not need to update other packages's shared lib dependencies.
11082            }
11083
11084            if (!hasStaticSharedLibs
11085                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11086                // Only system apps can add new dynamic shared libraries.
11087                if (pkg.libraryNames != null) {
11088                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11089                        String name = pkg.libraryNames.get(i);
11090                        boolean allowed = false;
11091                        if (pkg.isUpdatedSystemApp()) {
11092                            // New library entries can only be added through the
11093                            // system image.  This is important to get rid of a lot
11094                            // of nasty edge cases: for example if we allowed a non-
11095                            // system update of the app to add a library, then uninstalling
11096                            // the update would make the library go away, and assumptions
11097                            // we made such as through app install filtering would now
11098                            // have allowed apps on the device which aren't compatible
11099                            // with it.  Better to just have the restriction here, be
11100                            // conservative, and create many fewer cases that can negatively
11101                            // impact the user experience.
11102                            final PackageSetting sysPs = mSettings
11103                                    .getDisabledSystemPkgLPr(pkg.packageName);
11104                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11105                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11106                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11107                                        allowed = true;
11108                                        break;
11109                                    }
11110                                }
11111                            }
11112                        } else {
11113                            allowed = true;
11114                        }
11115                        if (allowed) {
11116                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11117                                    SharedLibraryInfo.VERSION_UNDEFINED,
11118                                    SharedLibraryInfo.TYPE_DYNAMIC,
11119                                    pkg.packageName, pkg.mVersionCode)) {
11120                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11121                                        + name + " already exists; skipping");
11122                            }
11123                        } else {
11124                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11125                                    + name + " that is not declared on system image; skipping");
11126                        }
11127                    }
11128
11129                    if ((scanFlags & SCAN_BOOTING) == 0) {
11130                        // If we are not booting, we need to update any applications
11131                        // that are clients of our shared library.  If we are booting,
11132                        // this will all be done once the scan is complete.
11133                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11134                    }
11135                }
11136            }
11137        }
11138
11139        if ((scanFlags & SCAN_BOOTING) != 0) {
11140            // No apps can run during boot scan, so they don't need to be frozen
11141        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11142            // Caller asked to not kill app, so it's probably not frozen
11143        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11144            // Caller asked us to ignore frozen check for some reason; they
11145            // probably didn't know the package name
11146        } else {
11147            // We're doing major surgery on this package, so it better be frozen
11148            // right now to keep it from launching
11149            checkPackageFrozen(pkgName);
11150        }
11151
11152        // Also need to kill any apps that are dependent on the library.
11153        if (clientLibPkgs != null) {
11154            for (int i=0; i<clientLibPkgs.size(); i++) {
11155                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11156                killApplication(clientPkg.applicationInfo.packageName,
11157                        clientPkg.applicationInfo.uid, "update lib");
11158            }
11159        }
11160
11161        // writer
11162        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11163
11164        synchronized (mPackages) {
11165            // We don't expect installation to fail beyond this point
11166
11167            // Add the new setting to mSettings
11168            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11169            // Add the new setting to mPackages
11170            mPackages.put(pkg.applicationInfo.packageName, pkg);
11171            // Make sure we don't accidentally delete its data.
11172            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11173            while (iter.hasNext()) {
11174                PackageCleanItem item = iter.next();
11175                if (pkgName.equals(item.packageName)) {
11176                    iter.remove();
11177                }
11178            }
11179
11180            // Add the package's KeySets to the global KeySetManagerService
11181            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11182            ksms.addScannedPackageLPw(pkg);
11183
11184            int N = pkg.providers.size();
11185            StringBuilder r = null;
11186            int i;
11187            for (i=0; i<N; i++) {
11188                PackageParser.Provider p = pkg.providers.get(i);
11189                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11190                        p.info.processName);
11191                mProviders.addProvider(p);
11192                p.syncable = p.info.isSyncable;
11193                if (p.info.authority != null) {
11194                    String names[] = p.info.authority.split(";");
11195                    p.info.authority = null;
11196                    for (int j = 0; j < names.length; j++) {
11197                        if (j == 1 && p.syncable) {
11198                            // We only want the first authority for a provider to possibly be
11199                            // syncable, so if we already added this provider using a different
11200                            // authority clear the syncable flag. We copy the provider before
11201                            // changing it because the mProviders object contains a reference
11202                            // to a provider that we don't want to change.
11203                            // Only do this for the second authority since the resulting provider
11204                            // object can be the same for all future authorities for this provider.
11205                            p = new PackageParser.Provider(p);
11206                            p.syncable = false;
11207                        }
11208                        if (!mProvidersByAuthority.containsKey(names[j])) {
11209                            mProvidersByAuthority.put(names[j], p);
11210                            if (p.info.authority == null) {
11211                                p.info.authority = names[j];
11212                            } else {
11213                                p.info.authority = p.info.authority + ";" + names[j];
11214                            }
11215                            if (DEBUG_PACKAGE_SCANNING) {
11216                                if (chatty)
11217                                    Log.d(TAG, "Registered content provider: " + names[j]
11218                                            + ", className = " + p.info.name + ", isSyncable = "
11219                                            + p.info.isSyncable);
11220                            }
11221                        } else {
11222                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11223                            Slog.w(TAG, "Skipping provider name " + names[j] +
11224                                    " (in package " + pkg.applicationInfo.packageName +
11225                                    "): name already used by "
11226                                    + ((other != null && other.getComponentName() != null)
11227                                            ? other.getComponentName().getPackageName() : "?"));
11228                        }
11229                    }
11230                }
11231                if (chatty) {
11232                    if (r == null) {
11233                        r = new StringBuilder(256);
11234                    } else {
11235                        r.append(' ');
11236                    }
11237                    r.append(p.info.name);
11238                }
11239            }
11240            if (r != null) {
11241                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11242            }
11243
11244            N = pkg.services.size();
11245            r = null;
11246            for (i=0; i<N; i++) {
11247                PackageParser.Service s = pkg.services.get(i);
11248                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11249                        s.info.processName);
11250                mServices.addService(s);
11251                if (chatty) {
11252                    if (r == null) {
11253                        r = new StringBuilder(256);
11254                    } else {
11255                        r.append(' ');
11256                    }
11257                    r.append(s.info.name);
11258                }
11259            }
11260            if (r != null) {
11261                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11262            }
11263
11264            N = pkg.receivers.size();
11265            r = null;
11266            for (i=0; i<N; i++) {
11267                PackageParser.Activity a = pkg.receivers.get(i);
11268                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11269                        a.info.processName);
11270                mReceivers.addActivity(a, "receiver");
11271                if (chatty) {
11272                    if (r == null) {
11273                        r = new StringBuilder(256);
11274                    } else {
11275                        r.append(' ');
11276                    }
11277                    r.append(a.info.name);
11278                }
11279            }
11280            if (r != null) {
11281                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11282            }
11283
11284            N = pkg.activities.size();
11285            r = null;
11286            for (i=0; i<N; i++) {
11287                PackageParser.Activity a = pkg.activities.get(i);
11288                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11289                        a.info.processName);
11290                mActivities.addActivity(a, "activity");
11291                if (chatty) {
11292                    if (r == null) {
11293                        r = new StringBuilder(256);
11294                    } else {
11295                        r.append(' ');
11296                    }
11297                    r.append(a.info.name);
11298                }
11299            }
11300            if (r != null) {
11301                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11302            }
11303
11304            N = pkg.permissionGroups.size();
11305            r = null;
11306            for (i=0; i<N; i++) {
11307                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11308                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11309                final String curPackageName = cur == null ? null : cur.info.packageName;
11310                // Dont allow ephemeral apps to define new permission groups.
11311                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11312                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11313                            + pg.info.packageName
11314                            + " ignored: instant apps cannot define new permission groups.");
11315                    continue;
11316                }
11317                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11318                if (cur == null || isPackageUpdate) {
11319                    mPermissionGroups.put(pg.info.name, pg);
11320                    if (chatty) {
11321                        if (r == null) {
11322                            r = new StringBuilder(256);
11323                        } else {
11324                            r.append(' ');
11325                        }
11326                        if (isPackageUpdate) {
11327                            r.append("UPD:");
11328                        }
11329                        r.append(pg.info.name);
11330                    }
11331                } else {
11332                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11333                            + pg.info.packageName + " ignored: original from "
11334                            + cur.info.packageName);
11335                    if (chatty) {
11336                        if (r == null) {
11337                            r = new StringBuilder(256);
11338                        } else {
11339                            r.append(' ');
11340                        }
11341                        r.append("DUP:");
11342                        r.append(pg.info.name);
11343                    }
11344                }
11345            }
11346            if (r != null) {
11347                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11348            }
11349
11350            N = pkg.permissions.size();
11351            r = null;
11352            for (i=0; i<N; i++) {
11353                PackageParser.Permission p = pkg.permissions.get(i);
11354
11355                // Dont allow ephemeral apps to define new permissions.
11356                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11357                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11358                            + p.info.packageName
11359                            + " ignored: instant apps cannot define new permissions.");
11360                    continue;
11361                }
11362
11363                // Assume by default that we did not install this permission into the system.
11364                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11365
11366                // Now that permission groups have a special meaning, we ignore permission
11367                // groups for legacy apps to prevent unexpected behavior. In particular,
11368                // permissions for one app being granted to someone just because they happen
11369                // to be in a group defined by another app (before this had no implications).
11370                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11371                    p.group = mPermissionGroups.get(p.info.group);
11372                    // Warn for a permission in an unknown group.
11373                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11374                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11375                                + p.info.packageName + " in an unknown group " + p.info.group);
11376                    }
11377                }
11378
11379                ArrayMap<String, BasePermission> permissionMap =
11380                        p.tree ? mSettings.mPermissionTrees
11381                                : mSettings.mPermissions;
11382                BasePermission bp = permissionMap.get(p.info.name);
11383
11384                // Allow system apps to redefine non-system permissions
11385                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11386                    final boolean currentOwnerIsSystem = (bp.perm != null
11387                            && isSystemApp(bp.perm.owner));
11388                    if (isSystemApp(p.owner)) {
11389                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11390                            // It's a built-in permission and no owner, take ownership now
11391                            bp.packageSetting = pkgSetting;
11392                            bp.perm = p;
11393                            bp.uid = pkg.applicationInfo.uid;
11394                            bp.sourcePackage = p.info.packageName;
11395                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11396                        } else if (!currentOwnerIsSystem) {
11397                            String msg = "New decl " + p.owner + " of permission  "
11398                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11399                            reportSettingsProblem(Log.WARN, msg);
11400                            bp = null;
11401                        }
11402                    }
11403                }
11404
11405                if (bp == null) {
11406                    bp = new BasePermission(p.info.name, p.info.packageName,
11407                            BasePermission.TYPE_NORMAL);
11408                    permissionMap.put(p.info.name, bp);
11409                }
11410
11411                if (bp.perm == null) {
11412                    if (bp.sourcePackage == null
11413                            || bp.sourcePackage.equals(p.info.packageName)) {
11414                        BasePermission tree = findPermissionTreeLP(p.info.name);
11415                        if (tree == null
11416                                || tree.sourcePackage.equals(p.info.packageName)) {
11417                            bp.packageSetting = pkgSetting;
11418                            bp.perm = p;
11419                            bp.uid = pkg.applicationInfo.uid;
11420                            bp.sourcePackage = p.info.packageName;
11421                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11422                            if (chatty) {
11423                                if (r == null) {
11424                                    r = new StringBuilder(256);
11425                                } else {
11426                                    r.append(' ');
11427                                }
11428                                r.append(p.info.name);
11429                            }
11430                        } else {
11431                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11432                                    + p.info.packageName + " ignored: base tree "
11433                                    + tree.name + " is from package "
11434                                    + tree.sourcePackage);
11435                        }
11436                    } else {
11437                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11438                                + p.info.packageName + " ignored: original from "
11439                                + bp.sourcePackage);
11440                    }
11441                } else if (chatty) {
11442                    if (r == null) {
11443                        r = new StringBuilder(256);
11444                    } else {
11445                        r.append(' ');
11446                    }
11447                    r.append("DUP:");
11448                    r.append(p.info.name);
11449                }
11450                if (bp.perm == p) {
11451                    bp.protectionLevel = p.info.protectionLevel;
11452                }
11453            }
11454
11455            if (r != null) {
11456                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11457            }
11458
11459            N = pkg.instrumentation.size();
11460            r = null;
11461            for (i=0; i<N; i++) {
11462                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11463                a.info.packageName = pkg.applicationInfo.packageName;
11464                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11465                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11466                a.info.splitNames = pkg.splitNames;
11467                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11468                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11469                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11470                a.info.dataDir = pkg.applicationInfo.dataDir;
11471                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11472                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11473                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11474                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11475                mInstrumentation.put(a.getComponentName(), a);
11476                if (chatty) {
11477                    if (r == null) {
11478                        r = new StringBuilder(256);
11479                    } else {
11480                        r.append(' ');
11481                    }
11482                    r.append(a.info.name);
11483                }
11484            }
11485            if (r != null) {
11486                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11487            }
11488
11489            if (pkg.protectedBroadcasts != null) {
11490                N = pkg.protectedBroadcasts.size();
11491                synchronized (mProtectedBroadcasts) {
11492                    for (i = 0; i < N; i++) {
11493                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11494                    }
11495                }
11496            }
11497        }
11498
11499        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11500    }
11501
11502    /**
11503     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11504     * is derived purely on the basis of the contents of {@code scanFile} and
11505     * {@code cpuAbiOverride}.
11506     *
11507     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11508     */
11509    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11510                                 String cpuAbiOverride, boolean extractLibs,
11511                                 File appLib32InstallDir)
11512            throws PackageManagerException {
11513        // Give ourselves some initial paths; we'll come back for another
11514        // pass once we've determined ABI below.
11515        setNativeLibraryPaths(pkg, appLib32InstallDir);
11516
11517        // We would never need to extract libs for forward-locked and external packages,
11518        // since the container service will do it for us. We shouldn't attempt to
11519        // extract libs from system app when it was not updated.
11520        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11521                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11522            extractLibs = false;
11523        }
11524
11525        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11526        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11527
11528        NativeLibraryHelper.Handle handle = null;
11529        try {
11530            handle = NativeLibraryHelper.Handle.create(pkg);
11531            // TODO(multiArch): This can be null for apps that didn't go through the
11532            // usual installation process. We can calculate it again, like we
11533            // do during install time.
11534            //
11535            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11536            // unnecessary.
11537            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11538
11539            // Null out the abis so that they can be recalculated.
11540            pkg.applicationInfo.primaryCpuAbi = null;
11541            pkg.applicationInfo.secondaryCpuAbi = null;
11542            if (isMultiArch(pkg.applicationInfo)) {
11543                // Warn if we've set an abiOverride for multi-lib packages..
11544                // By definition, we need to copy both 32 and 64 bit libraries for
11545                // such packages.
11546                if (pkg.cpuAbiOverride != null
11547                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11548                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11549                }
11550
11551                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11552                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11553                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11554                    if (extractLibs) {
11555                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11556                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11557                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11558                                useIsaSpecificSubdirs);
11559                    } else {
11560                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11561                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11562                    }
11563                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11564                }
11565
11566                // Shared library native code should be in the APK zip aligned
11567                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11568                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11569                            "Shared library native lib extraction not supported");
11570                }
11571
11572                maybeThrowExceptionForMultiArchCopy(
11573                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11574
11575                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11576                    if (extractLibs) {
11577                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11578                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11579                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11580                                useIsaSpecificSubdirs);
11581                    } else {
11582                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11583                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11584                    }
11585                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11586                }
11587
11588                maybeThrowExceptionForMultiArchCopy(
11589                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11590
11591                if (abi64 >= 0) {
11592                    // Shared library native libs should be in the APK zip aligned
11593                    if (extractLibs && pkg.isLibrary()) {
11594                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11595                                "Shared library native lib extraction not supported");
11596                    }
11597                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11598                }
11599
11600                if (abi32 >= 0) {
11601                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11602                    if (abi64 >= 0) {
11603                        if (pkg.use32bitAbi) {
11604                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11605                            pkg.applicationInfo.primaryCpuAbi = abi;
11606                        } else {
11607                            pkg.applicationInfo.secondaryCpuAbi = abi;
11608                        }
11609                    } else {
11610                        pkg.applicationInfo.primaryCpuAbi = abi;
11611                    }
11612                }
11613            } else {
11614                String[] abiList = (cpuAbiOverride != null) ?
11615                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11616
11617                // Enable gross and lame hacks for apps that are built with old
11618                // SDK tools. We must scan their APKs for renderscript bitcode and
11619                // not launch them if it's present. Don't bother checking on devices
11620                // that don't have 64 bit support.
11621                boolean needsRenderScriptOverride = false;
11622                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11623                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11624                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11625                    needsRenderScriptOverride = true;
11626                }
11627
11628                final int copyRet;
11629                if (extractLibs) {
11630                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11631                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11632                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11633                } else {
11634                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11635                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11636                }
11637                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11638
11639                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11640                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11641                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11642                }
11643
11644                if (copyRet >= 0) {
11645                    // Shared libraries that have native libs must be multi-architecture
11646                    if (pkg.isLibrary()) {
11647                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11648                                "Shared library with native libs must be multiarch");
11649                    }
11650                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11651                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11652                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11653                } else if (needsRenderScriptOverride) {
11654                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11655                }
11656            }
11657        } catch (IOException ioe) {
11658            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11659        } finally {
11660            IoUtils.closeQuietly(handle);
11661        }
11662
11663        // Now that we've calculated the ABIs and determined if it's an internal app,
11664        // we will go ahead and populate the nativeLibraryPath.
11665        setNativeLibraryPaths(pkg, appLib32InstallDir);
11666    }
11667
11668    /**
11669     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11670     * i.e, so that all packages can be run inside a single process if required.
11671     *
11672     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11673     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11674     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11675     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11676     * updating a package that belongs to a shared user.
11677     *
11678     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11679     * adds unnecessary complexity.
11680     */
11681    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11682            PackageParser.Package scannedPackage) {
11683        String requiredInstructionSet = null;
11684        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11685            requiredInstructionSet = VMRuntime.getInstructionSet(
11686                     scannedPackage.applicationInfo.primaryCpuAbi);
11687        }
11688
11689        PackageSetting requirer = null;
11690        for (PackageSetting ps : packagesForUser) {
11691            // If packagesForUser contains scannedPackage, we skip it. This will happen
11692            // when scannedPackage is an update of an existing package. Without this check,
11693            // we will never be able to change the ABI of any package belonging to a shared
11694            // user, even if it's compatible with other packages.
11695            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11696                if (ps.primaryCpuAbiString == null) {
11697                    continue;
11698                }
11699
11700                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11701                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11702                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11703                    // this but there's not much we can do.
11704                    String errorMessage = "Instruction set mismatch, "
11705                            + ((requirer == null) ? "[caller]" : requirer)
11706                            + " requires " + requiredInstructionSet + " whereas " + ps
11707                            + " requires " + instructionSet;
11708                    Slog.w(TAG, errorMessage);
11709                }
11710
11711                if (requiredInstructionSet == null) {
11712                    requiredInstructionSet = instructionSet;
11713                    requirer = ps;
11714                }
11715            }
11716        }
11717
11718        if (requiredInstructionSet != null) {
11719            String adjustedAbi;
11720            if (requirer != null) {
11721                // requirer != null implies that either scannedPackage was null or that scannedPackage
11722                // did not require an ABI, in which case we have to adjust scannedPackage to match
11723                // the ABI of the set (which is the same as requirer's ABI)
11724                adjustedAbi = requirer.primaryCpuAbiString;
11725                if (scannedPackage != null) {
11726                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11727                }
11728            } else {
11729                // requirer == null implies that we're updating all ABIs in the set to
11730                // match scannedPackage.
11731                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11732            }
11733
11734            for (PackageSetting ps : packagesForUser) {
11735                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11736                    if (ps.primaryCpuAbiString != null) {
11737                        continue;
11738                    }
11739
11740                    ps.primaryCpuAbiString = adjustedAbi;
11741                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11742                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11743                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11744                        if (DEBUG_ABI_SELECTION) {
11745                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11746                                    + " (requirer="
11747                                    + (requirer != null ? requirer.pkg : "null")
11748                                    + ", scannedPackage="
11749                                    + (scannedPackage != null ? scannedPackage : "null")
11750                                    + ")");
11751                        }
11752                        try {
11753                            mInstaller.rmdex(ps.codePathString,
11754                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11755                        } catch (InstallerException ignored) {
11756                        }
11757                    }
11758                }
11759            }
11760        }
11761    }
11762
11763    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11764        synchronized (mPackages) {
11765            mResolverReplaced = true;
11766            // Set up information for custom user intent resolution activity.
11767            mResolveActivity.applicationInfo = pkg.applicationInfo;
11768            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11769            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11770            mResolveActivity.processName = pkg.applicationInfo.packageName;
11771            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11772            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11773                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11774            mResolveActivity.theme = 0;
11775            mResolveActivity.exported = true;
11776            mResolveActivity.enabled = true;
11777            mResolveInfo.activityInfo = mResolveActivity;
11778            mResolveInfo.priority = 0;
11779            mResolveInfo.preferredOrder = 0;
11780            mResolveInfo.match = 0;
11781            mResolveComponentName = mCustomResolverComponentName;
11782            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11783                    mResolveComponentName);
11784        }
11785    }
11786
11787    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11788        if (installerActivity == null) {
11789            if (DEBUG_EPHEMERAL) {
11790                Slog.d(TAG, "Clear ephemeral installer activity");
11791            }
11792            mInstantAppInstallerActivity = null;
11793            return;
11794        }
11795
11796        if (DEBUG_EPHEMERAL) {
11797            Slog.d(TAG, "Set ephemeral installer activity: "
11798                    + installerActivity.getComponentName());
11799        }
11800        // Set up information for ephemeral installer activity
11801        mInstantAppInstallerActivity = installerActivity;
11802        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11803                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11804        mInstantAppInstallerActivity.exported = true;
11805        mInstantAppInstallerActivity.enabled = true;
11806        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11807        mInstantAppInstallerInfo.priority = 0;
11808        mInstantAppInstallerInfo.preferredOrder = 1;
11809        mInstantAppInstallerInfo.isDefault = true;
11810        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11811                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11812    }
11813
11814    private static String calculateBundledApkRoot(final String codePathString) {
11815        final File codePath = new File(codePathString);
11816        final File codeRoot;
11817        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11818            codeRoot = Environment.getRootDirectory();
11819        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11820            codeRoot = Environment.getOemDirectory();
11821        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11822            codeRoot = Environment.getVendorDirectory();
11823        } else {
11824            // Unrecognized code path; take its top real segment as the apk root:
11825            // e.g. /something/app/blah.apk => /something
11826            try {
11827                File f = codePath.getCanonicalFile();
11828                File parent = f.getParentFile();    // non-null because codePath is a file
11829                File tmp;
11830                while ((tmp = parent.getParentFile()) != null) {
11831                    f = parent;
11832                    parent = tmp;
11833                }
11834                codeRoot = f;
11835                Slog.w(TAG, "Unrecognized code path "
11836                        + codePath + " - using " + codeRoot);
11837            } catch (IOException e) {
11838                // Can't canonicalize the code path -- shenanigans?
11839                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11840                return Environment.getRootDirectory().getPath();
11841            }
11842        }
11843        return codeRoot.getPath();
11844    }
11845
11846    /**
11847     * Derive and set the location of native libraries for the given package,
11848     * which varies depending on where and how the package was installed.
11849     */
11850    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11851        final ApplicationInfo info = pkg.applicationInfo;
11852        final String codePath = pkg.codePath;
11853        final File codeFile = new File(codePath);
11854        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11855        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11856
11857        info.nativeLibraryRootDir = null;
11858        info.nativeLibraryRootRequiresIsa = false;
11859        info.nativeLibraryDir = null;
11860        info.secondaryNativeLibraryDir = null;
11861
11862        if (isApkFile(codeFile)) {
11863            // Monolithic install
11864            if (bundledApp) {
11865                // If "/system/lib64/apkname" exists, assume that is the per-package
11866                // native library directory to use; otherwise use "/system/lib/apkname".
11867                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11868                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11869                        getPrimaryInstructionSet(info));
11870
11871                // This is a bundled system app so choose the path based on the ABI.
11872                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11873                // is just the default path.
11874                final String apkName = deriveCodePathName(codePath);
11875                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11876                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11877                        apkName).getAbsolutePath();
11878
11879                if (info.secondaryCpuAbi != null) {
11880                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11881                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11882                            secondaryLibDir, apkName).getAbsolutePath();
11883                }
11884            } else if (asecApp) {
11885                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11886                        .getAbsolutePath();
11887            } else {
11888                final String apkName = deriveCodePathName(codePath);
11889                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11890                        .getAbsolutePath();
11891            }
11892
11893            info.nativeLibraryRootRequiresIsa = false;
11894            info.nativeLibraryDir = info.nativeLibraryRootDir;
11895        } else {
11896            // Cluster install
11897            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11898            info.nativeLibraryRootRequiresIsa = true;
11899
11900            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11901                    getPrimaryInstructionSet(info)).getAbsolutePath();
11902
11903            if (info.secondaryCpuAbi != null) {
11904                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11905                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11906            }
11907        }
11908    }
11909
11910    /**
11911     * Calculate the abis and roots for a bundled app. These can uniquely
11912     * be determined from the contents of the system partition, i.e whether
11913     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11914     * of this information, and instead assume that the system was built
11915     * sensibly.
11916     */
11917    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11918                                           PackageSetting pkgSetting) {
11919        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11920
11921        // If "/system/lib64/apkname" exists, assume that is the per-package
11922        // native library directory to use; otherwise use "/system/lib/apkname".
11923        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11924        setBundledAppAbi(pkg, apkRoot, apkName);
11925        // pkgSetting might be null during rescan following uninstall of updates
11926        // to a bundled app, so accommodate that possibility.  The settings in
11927        // that case will be established later from the parsed package.
11928        //
11929        // If the settings aren't null, sync them up with what we've just derived.
11930        // note that apkRoot isn't stored in the package settings.
11931        if (pkgSetting != null) {
11932            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11933            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11934        }
11935    }
11936
11937    /**
11938     * Deduces the ABI of a bundled app and sets the relevant fields on the
11939     * parsed pkg object.
11940     *
11941     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11942     *        under which system libraries are installed.
11943     * @param apkName the name of the installed package.
11944     */
11945    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11946        final File codeFile = new File(pkg.codePath);
11947
11948        final boolean has64BitLibs;
11949        final boolean has32BitLibs;
11950        if (isApkFile(codeFile)) {
11951            // Monolithic install
11952            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11953            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11954        } else {
11955            // Cluster install
11956            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11957            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11958                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11959                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11960                has64BitLibs = (new File(rootDir, isa)).exists();
11961            } else {
11962                has64BitLibs = false;
11963            }
11964            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11965                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11966                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11967                has32BitLibs = (new File(rootDir, isa)).exists();
11968            } else {
11969                has32BitLibs = false;
11970            }
11971        }
11972
11973        if (has64BitLibs && !has32BitLibs) {
11974            // The package has 64 bit libs, but not 32 bit libs. Its primary
11975            // ABI should be 64 bit. We can safely assume here that the bundled
11976            // native libraries correspond to the most preferred ABI in the list.
11977
11978            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11979            pkg.applicationInfo.secondaryCpuAbi = null;
11980        } else if (has32BitLibs && !has64BitLibs) {
11981            // The package has 32 bit libs but not 64 bit libs. Its primary
11982            // ABI should be 32 bit.
11983
11984            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11985            pkg.applicationInfo.secondaryCpuAbi = null;
11986        } else if (has32BitLibs && has64BitLibs) {
11987            // The application has both 64 and 32 bit bundled libraries. We check
11988            // here that the app declares multiArch support, and warn if it doesn't.
11989            //
11990            // We will be lenient here and record both ABIs. The primary will be the
11991            // ABI that's higher on the list, i.e, a device that's configured to prefer
11992            // 64 bit apps will see a 64 bit primary ABI,
11993
11994            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11995                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11996            }
11997
11998            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11999                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12000                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12001            } else {
12002                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12003                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12004            }
12005        } else {
12006            pkg.applicationInfo.primaryCpuAbi = null;
12007            pkg.applicationInfo.secondaryCpuAbi = null;
12008        }
12009    }
12010
12011    private void killApplication(String pkgName, int appId, String reason) {
12012        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12013    }
12014
12015    private void killApplication(String pkgName, int appId, int userId, String reason) {
12016        // Request the ActivityManager to kill the process(only for existing packages)
12017        // so that we do not end up in a confused state while the user is still using the older
12018        // version of the application while the new one gets installed.
12019        final long token = Binder.clearCallingIdentity();
12020        try {
12021            IActivityManager am = ActivityManager.getService();
12022            if (am != null) {
12023                try {
12024                    am.killApplication(pkgName, appId, userId, reason);
12025                } catch (RemoteException e) {
12026                }
12027            }
12028        } finally {
12029            Binder.restoreCallingIdentity(token);
12030        }
12031    }
12032
12033    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12034        // Remove the parent package setting
12035        PackageSetting ps = (PackageSetting) pkg.mExtras;
12036        if (ps != null) {
12037            removePackageLI(ps, chatty);
12038        }
12039        // Remove the child package setting
12040        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12041        for (int i = 0; i < childCount; i++) {
12042            PackageParser.Package childPkg = pkg.childPackages.get(i);
12043            ps = (PackageSetting) childPkg.mExtras;
12044            if (ps != null) {
12045                removePackageLI(ps, chatty);
12046            }
12047        }
12048    }
12049
12050    void removePackageLI(PackageSetting ps, boolean chatty) {
12051        if (DEBUG_INSTALL) {
12052            if (chatty)
12053                Log.d(TAG, "Removing package " + ps.name);
12054        }
12055
12056        // writer
12057        synchronized (mPackages) {
12058            mPackages.remove(ps.name);
12059            final PackageParser.Package pkg = ps.pkg;
12060            if (pkg != null) {
12061                cleanPackageDataStructuresLILPw(pkg, chatty);
12062            }
12063        }
12064    }
12065
12066    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12067        if (DEBUG_INSTALL) {
12068            if (chatty)
12069                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12070        }
12071
12072        // writer
12073        synchronized (mPackages) {
12074            // Remove the parent package
12075            mPackages.remove(pkg.applicationInfo.packageName);
12076            cleanPackageDataStructuresLILPw(pkg, chatty);
12077
12078            // Remove the child packages
12079            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12080            for (int i = 0; i < childCount; i++) {
12081                PackageParser.Package childPkg = pkg.childPackages.get(i);
12082                mPackages.remove(childPkg.applicationInfo.packageName);
12083                cleanPackageDataStructuresLILPw(childPkg, chatty);
12084            }
12085        }
12086    }
12087
12088    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12089        int N = pkg.providers.size();
12090        StringBuilder r = null;
12091        int i;
12092        for (i=0; i<N; i++) {
12093            PackageParser.Provider p = pkg.providers.get(i);
12094            mProviders.removeProvider(p);
12095            if (p.info.authority == null) {
12096
12097                /* There was another ContentProvider with this authority when
12098                 * this app was installed so this authority is null,
12099                 * Ignore it as we don't have to unregister the provider.
12100                 */
12101                continue;
12102            }
12103            String names[] = p.info.authority.split(";");
12104            for (int j = 0; j < names.length; j++) {
12105                if (mProvidersByAuthority.get(names[j]) == p) {
12106                    mProvidersByAuthority.remove(names[j]);
12107                    if (DEBUG_REMOVE) {
12108                        if (chatty)
12109                            Log.d(TAG, "Unregistered content provider: " + names[j]
12110                                    + ", className = " + p.info.name + ", isSyncable = "
12111                                    + p.info.isSyncable);
12112                    }
12113                }
12114            }
12115            if (DEBUG_REMOVE && chatty) {
12116                if (r == null) {
12117                    r = new StringBuilder(256);
12118                } else {
12119                    r.append(' ');
12120                }
12121                r.append(p.info.name);
12122            }
12123        }
12124        if (r != null) {
12125            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12126        }
12127
12128        N = pkg.services.size();
12129        r = null;
12130        for (i=0; i<N; i++) {
12131            PackageParser.Service s = pkg.services.get(i);
12132            mServices.removeService(s);
12133            if (chatty) {
12134                if (r == null) {
12135                    r = new StringBuilder(256);
12136                } else {
12137                    r.append(' ');
12138                }
12139                r.append(s.info.name);
12140            }
12141        }
12142        if (r != null) {
12143            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12144        }
12145
12146        N = pkg.receivers.size();
12147        r = null;
12148        for (i=0; i<N; i++) {
12149            PackageParser.Activity a = pkg.receivers.get(i);
12150            mReceivers.removeActivity(a, "receiver");
12151            if (DEBUG_REMOVE && chatty) {
12152                if (r == null) {
12153                    r = new StringBuilder(256);
12154                } else {
12155                    r.append(' ');
12156                }
12157                r.append(a.info.name);
12158            }
12159        }
12160        if (r != null) {
12161            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12162        }
12163
12164        N = pkg.activities.size();
12165        r = null;
12166        for (i=0; i<N; i++) {
12167            PackageParser.Activity a = pkg.activities.get(i);
12168            mActivities.removeActivity(a, "activity");
12169            if (DEBUG_REMOVE && chatty) {
12170                if (r == null) {
12171                    r = new StringBuilder(256);
12172                } else {
12173                    r.append(' ');
12174                }
12175                r.append(a.info.name);
12176            }
12177        }
12178        if (r != null) {
12179            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12180        }
12181
12182        N = pkg.permissions.size();
12183        r = null;
12184        for (i=0; i<N; i++) {
12185            PackageParser.Permission p = pkg.permissions.get(i);
12186            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12187            if (bp == null) {
12188                bp = mSettings.mPermissionTrees.get(p.info.name);
12189            }
12190            if (bp != null && bp.perm == p) {
12191                bp.perm = null;
12192                if (DEBUG_REMOVE && chatty) {
12193                    if (r == null) {
12194                        r = new StringBuilder(256);
12195                    } else {
12196                        r.append(' ');
12197                    }
12198                    r.append(p.info.name);
12199                }
12200            }
12201            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12202                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12203                if (appOpPkgs != null) {
12204                    appOpPkgs.remove(pkg.packageName);
12205                }
12206            }
12207        }
12208        if (r != null) {
12209            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12210        }
12211
12212        N = pkg.requestedPermissions.size();
12213        r = null;
12214        for (i=0; i<N; i++) {
12215            String perm = pkg.requestedPermissions.get(i);
12216            BasePermission bp = mSettings.mPermissions.get(perm);
12217            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12218                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12219                if (appOpPkgs != null) {
12220                    appOpPkgs.remove(pkg.packageName);
12221                    if (appOpPkgs.isEmpty()) {
12222                        mAppOpPermissionPackages.remove(perm);
12223                    }
12224                }
12225            }
12226        }
12227        if (r != null) {
12228            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12229        }
12230
12231        N = pkg.instrumentation.size();
12232        r = null;
12233        for (i=0; i<N; i++) {
12234            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12235            mInstrumentation.remove(a.getComponentName());
12236            if (DEBUG_REMOVE && chatty) {
12237                if (r == null) {
12238                    r = new StringBuilder(256);
12239                } else {
12240                    r.append(' ');
12241                }
12242                r.append(a.info.name);
12243            }
12244        }
12245        if (r != null) {
12246            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12247        }
12248
12249        r = null;
12250        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12251            // Only system apps can hold shared libraries.
12252            if (pkg.libraryNames != null) {
12253                for (i = 0; i < pkg.libraryNames.size(); i++) {
12254                    String name = pkg.libraryNames.get(i);
12255                    if (removeSharedLibraryLPw(name, 0)) {
12256                        if (DEBUG_REMOVE && chatty) {
12257                            if (r == null) {
12258                                r = new StringBuilder(256);
12259                            } else {
12260                                r.append(' ');
12261                            }
12262                            r.append(name);
12263                        }
12264                    }
12265                }
12266            }
12267        }
12268
12269        r = null;
12270
12271        // Any package can hold static shared libraries.
12272        if (pkg.staticSharedLibName != null) {
12273            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12274                if (DEBUG_REMOVE && chatty) {
12275                    if (r == null) {
12276                        r = new StringBuilder(256);
12277                    } else {
12278                        r.append(' ');
12279                    }
12280                    r.append(pkg.staticSharedLibName);
12281                }
12282            }
12283        }
12284
12285        if (r != null) {
12286            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12287        }
12288    }
12289
12290    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12291        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12292            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12293                return true;
12294            }
12295        }
12296        return false;
12297    }
12298
12299    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12300    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12301    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12302
12303    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12304        // Update the parent permissions
12305        updatePermissionsLPw(pkg.packageName, pkg, flags);
12306        // Update the child permissions
12307        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12308        for (int i = 0; i < childCount; i++) {
12309            PackageParser.Package childPkg = pkg.childPackages.get(i);
12310            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12311        }
12312    }
12313
12314    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12315            int flags) {
12316        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12317        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12318    }
12319
12320    private void updatePermissionsLPw(String changingPkg,
12321            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12322        // Make sure there are no dangling permission trees.
12323        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12324        while (it.hasNext()) {
12325            final BasePermission bp = it.next();
12326            if (bp.packageSetting == null) {
12327                // We may not yet have parsed the package, so just see if
12328                // we still know about its settings.
12329                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12330            }
12331            if (bp.packageSetting == null) {
12332                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12333                        + " from package " + bp.sourcePackage);
12334                it.remove();
12335            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12336                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12337                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12338                            + " from package " + bp.sourcePackage);
12339                    flags |= UPDATE_PERMISSIONS_ALL;
12340                    it.remove();
12341                }
12342            }
12343        }
12344
12345        // Make sure all dynamic permissions have been assigned to a package,
12346        // and make sure there are no dangling permissions.
12347        it = mSettings.mPermissions.values().iterator();
12348        while (it.hasNext()) {
12349            final BasePermission bp = it.next();
12350            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12351                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12352                        + bp.name + " pkg=" + bp.sourcePackage
12353                        + " info=" + bp.pendingInfo);
12354                if (bp.packageSetting == null && bp.pendingInfo != null) {
12355                    final BasePermission tree = findPermissionTreeLP(bp.name);
12356                    if (tree != null && tree.perm != null) {
12357                        bp.packageSetting = tree.packageSetting;
12358                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12359                                new PermissionInfo(bp.pendingInfo));
12360                        bp.perm.info.packageName = tree.perm.info.packageName;
12361                        bp.perm.info.name = bp.name;
12362                        bp.uid = tree.uid;
12363                    }
12364                }
12365            }
12366            if (bp.packageSetting == null) {
12367                // We may not yet have parsed the package, so just see if
12368                // we still know about its settings.
12369                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12370            }
12371            if (bp.packageSetting == null) {
12372                Slog.w(TAG, "Removing dangling permission: " + bp.name
12373                        + " from package " + bp.sourcePackage);
12374                it.remove();
12375            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12376                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12377                    Slog.i(TAG, "Removing old permission: " + bp.name
12378                            + " from package " + bp.sourcePackage);
12379                    flags |= UPDATE_PERMISSIONS_ALL;
12380                    it.remove();
12381                }
12382            }
12383        }
12384
12385        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12386        // Now update the permissions for all packages, in particular
12387        // replace the granted permissions of the system packages.
12388        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12389            for (PackageParser.Package pkg : mPackages.values()) {
12390                if (pkg != pkgInfo) {
12391                    // Only replace for packages on requested volume
12392                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12393                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12394                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12395                    grantPermissionsLPw(pkg, replace, changingPkg);
12396                }
12397            }
12398        }
12399
12400        if (pkgInfo != null) {
12401            // Only replace for packages on requested volume
12402            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12403            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12404                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12405            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12406        }
12407        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12408    }
12409
12410    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12411            String packageOfInterest) {
12412        // IMPORTANT: There are two types of permissions: install and runtime.
12413        // Install time permissions are granted when the app is installed to
12414        // all device users and users added in the future. Runtime permissions
12415        // are granted at runtime explicitly to specific users. Normal and signature
12416        // protected permissions are install time permissions. Dangerous permissions
12417        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12418        // otherwise they are runtime permissions. This function does not manage
12419        // runtime permissions except for the case an app targeting Lollipop MR1
12420        // being upgraded to target a newer SDK, in which case dangerous permissions
12421        // are transformed from install time to runtime ones.
12422
12423        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12424        if (ps == null) {
12425            return;
12426        }
12427
12428        PermissionsState permissionsState = ps.getPermissionsState();
12429        PermissionsState origPermissions = permissionsState;
12430
12431        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12432
12433        boolean runtimePermissionsRevoked = false;
12434        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12435
12436        boolean changedInstallPermission = false;
12437
12438        if (replace) {
12439            ps.installPermissionsFixed = false;
12440            if (!ps.isSharedUser()) {
12441                origPermissions = new PermissionsState(permissionsState);
12442                permissionsState.reset();
12443            } else {
12444                // We need to know only about runtime permission changes since the
12445                // calling code always writes the install permissions state but
12446                // the runtime ones are written only if changed. The only cases of
12447                // changed runtime permissions here are promotion of an install to
12448                // runtime and revocation of a runtime from a shared user.
12449                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12450                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12451                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12452                    runtimePermissionsRevoked = true;
12453                }
12454            }
12455        }
12456
12457        permissionsState.setGlobalGids(mGlobalGids);
12458
12459        final int N = pkg.requestedPermissions.size();
12460        for (int i=0; i<N; i++) {
12461            final String name = pkg.requestedPermissions.get(i);
12462            final BasePermission bp = mSettings.mPermissions.get(name);
12463            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12464                    >= Build.VERSION_CODES.M;
12465
12466            if (DEBUG_INSTALL) {
12467                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12468            }
12469
12470            if (bp == null || bp.packageSetting == null) {
12471                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12472                    if (DEBUG_PERMISSIONS) {
12473                        Slog.i(TAG, "Unknown permission " + name
12474                                + " in package " + pkg.packageName);
12475                    }
12476                }
12477                continue;
12478            }
12479
12480
12481            // Limit ephemeral apps to ephemeral allowed permissions.
12482            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12483                if (DEBUG_PERMISSIONS) {
12484                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12485                            + pkg.packageName);
12486                }
12487                continue;
12488            }
12489
12490            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12491                if (DEBUG_PERMISSIONS) {
12492                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12493                            + pkg.packageName);
12494                }
12495                continue;
12496            }
12497
12498            final String perm = bp.name;
12499            boolean allowedSig = false;
12500            int grant = GRANT_DENIED;
12501
12502            // Keep track of app op permissions.
12503            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12504                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12505                if (pkgs == null) {
12506                    pkgs = new ArraySet<>();
12507                    mAppOpPermissionPackages.put(bp.name, pkgs);
12508                }
12509                pkgs.add(pkg.packageName);
12510            }
12511
12512            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12513            switch (level) {
12514                case PermissionInfo.PROTECTION_NORMAL: {
12515                    // For all apps normal permissions are install time ones.
12516                    grant = GRANT_INSTALL;
12517                } break;
12518
12519                case PermissionInfo.PROTECTION_DANGEROUS: {
12520                    // If a permission review is required for legacy apps we represent
12521                    // their permissions as always granted runtime ones since we need
12522                    // to keep the review required permission flag per user while an
12523                    // install permission's state is shared across all users.
12524                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12525                        // For legacy apps dangerous permissions are install time ones.
12526                        grant = GRANT_INSTALL;
12527                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12528                        // For legacy apps that became modern, install becomes runtime.
12529                        grant = GRANT_UPGRADE;
12530                    } else if (mPromoteSystemApps
12531                            && isSystemApp(ps)
12532                            && mExistingSystemPackages.contains(ps.name)) {
12533                        // For legacy system apps, install becomes runtime.
12534                        // We cannot check hasInstallPermission() for system apps since those
12535                        // permissions were granted implicitly and not persisted pre-M.
12536                        grant = GRANT_UPGRADE;
12537                    } else {
12538                        // For modern apps keep runtime permissions unchanged.
12539                        grant = GRANT_RUNTIME;
12540                    }
12541                } break;
12542
12543                case PermissionInfo.PROTECTION_SIGNATURE: {
12544                    // For all apps signature permissions are install time ones.
12545                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12546                    if (allowedSig) {
12547                        grant = GRANT_INSTALL;
12548                    }
12549                } break;
12550            }
12551
12552            if (DEBUG_PERMISSIONS) {
12553                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12554            }
12555
12556            if (grant != GRANT_DENIED) {
12557                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12558                    // If this is an existing, non-system package, then
12559                    // we can't add any new permissions to it.
12560                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12561                        // Except...  if this is a permission that was added
12562                        // to the platform (note: need to only do this when
12563                        // updating the platform).
12564                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12565                            grant = GRANT_DENIED;
12566                        }
12567                    }
12568                }
12569
12570                switch (grant) {
12571                    case GRANT_INSTALL: {
12572                        // Revoke this as runtime permission to handle the case of
12573                        // a runtime permission being downgraded to an install one.
12574                        // Also in permission review mode we keep dangerous permissions
12575                        // for legacy apps
12576                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12577                            if (origPermissions.getRuntimePermissionState(
12578                                    bp.name, userId) != null) {
12579                                // Revoke the runtime permission and clear the flags.
12580                                origPermissions.revokeRuntimePermission(bp, userId);
12581                                origPermissions.updatePermissionFlags(bp, userId,
12582                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12583                                // If we revoked a permission permission, we have to write.
12584                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12585                                        changedRuntimePermissionUserIds, userId);
12586                            }
12587                        }
12588                        // Grant an install permission.
12589                        if (permissionsState.grantInstallPermission(bp) !=
12590                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12591                            changedInstallPermission = true;
12592                        }
12593                    } break;
12594
12595                    case GRANT_RUNTIME: {
12596                        // Grant previously granted runtime permissions.
12597                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12598                            PermissionState permissionState = origPermissions
12599                                    .getRuntimePermissionState(bp.name, userId);
12600                            int flags = permissionState != null
12601                                    ? permissionState.getFlags() : 0;
12602                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12603                                // Don't propagate the permission in a permission review mode if
12604                                // the former was revoked, i.e. marked to not propagate on upgrade.
12605                                // Note that in a permission review mode install permissions are
12606                                // represented as constantly granted runtime ones since we need to
12607                                // keep a per user state associated with the permission. Also the
12608                                // revoke on upgrade flag is no longer applicable and is reset.
12609                                final boolean revokeOnUpgrade = (flags & PackageManager
12610                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12611                                if (revokeOnUpgrade) {
12612                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12613                                    // Since we changed the flags, we have to write.
12614                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12615                                            changedRuntimePermissionUserIds, userId);
12616                                }
12617                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12618                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12619                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12620                                        // If we cannot put the permission as it was,
12621                                        // we have to write.
12622                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12623                                                changedRuntimePermissionUserIds, userId);
12624                                    }
12625                                }
12626
12627                                // If the app supports runtime permissions no need for a review.
12628                                if (mPermissionReviewRequired
12629                                        && appSupportsRuntimePermissions
12630                                        && (flags & PackageManager
12631                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12632                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12633                                    // Since we changed the flags, we have to write.
12634                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12635                                            changedRuntimePermissionUserIds, userId);
12636                                }
12637                            } else if (mPermissionReviewRequired
12638                                    && !appSupportsRuntimePermissions) {
12639                                // For legacy apps that need a permission review, every new
12640                                // runtime permission is granted but it is pending a review.
12641                                // We also need to review only platform defined runtime
12642                                // permissions as these are the only ones the platform knows
12643                                // how to disable the API to simulate revocation as legacy
12644                                // apps don't expect to run with revoked permissions.
12645                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12646                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12647                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12648                                        // We changed the flags, hence have to write.
12649                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12650                                                changedRuntimePermissionUserIds, userId);
12651                                    }
12652                                }
12653                                if (permissionsState.grantRuntimePermission(bp, userId)
12654                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12655                                    // We changed the permission, hence have to write.
12656                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12657                                            changedRuntimePermissionUserIds, userId);
12658                                }
12659                            }
12660                            // Propagate the permission flags.
12661                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12662                        }
12663                    } break;
12664
12665                    case GRANT_UPGRADE: {
12666                        // Grant runtime permissions for a previously held install permission.
12667                        PermissionState permissionState = origPermissions
12668                                .getInstallPermissionState(bp.name);
12669                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12670
12671                        if (origPermissions.revokeInstallPermission(bp)
12672                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12673                            // We will be transferring the permission flags, so clear them.
12674                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12675                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12676                            changedInstallPermission = true;
12677                        }
12678
12679                        // If the permission is not to be promoted to runtime we ignore it and
12680                        // also its other flags as they are not applicable to install permissions.
12681                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12682                            for (int userId : currentUserIds) {
12683                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12684                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12685                                    // Transfer the permission flags.
12686                                    permissionsState.updatePermissionFlags(bp, userId,
12687                                            flags, flags);
12688                                    // If we granted the permission, we have to write.
12689                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12690                                            changedRuntimePermissionUserIds, userId);
12691                                }
12692                            }
12693                        }
12694                    } break;
12695
12696                    default: {
12697                        if (packageOfInterest == null
12698                                || packageOfInterest.equals(pkg.packageName)) {
12699                            if (DEBUG_PERMISSIONS) {
12700                                Slog.i(TAG, "Not granting permission " + perm
12701                                        + " to package " + pkg.packageName
12702                                        + " because it was previously installed without");
12703                            }
12704                        }
12705                    } break;
12706                }
12707            } else {
12708                if (permissionsState.revokeInstallPermission(bp) !=
12709                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12710                    // Also drop the permission flags.
12711                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12712                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12713                    changedInstallPermission = true;
12714                    Slog.i(TAG, "Un-granting permission " + perm
12715                            + " from package " + pkg.packageName
12716                            + " (protectionLevel=" + bp.protectionLevel
12717                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12718                            + ")");
12719                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12720                    // Don't print warning for app op permissions, since it is fine for them
12721                    // not to be granted, there is a UI for the user to decide.
12722                    if (DEBUG_PERMISSIONS
12723                            && (packageOfInterest == null
12724                                    || packageOfInterest.equals(pkg.packageName))) {
12725                        Slog.i(TAG, "Not granting permission " + perm
12726                                + " to package " + pkg.packageName
12727                                + " (protectionLevel=" + bp.protectionLevel
12728                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12729                                + ")");
12730                    }
12731                }
12732            }
12733        }
12734
12735        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12736                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12737            // This is the first that we have heard about this package, so the
12738            // permissions we have now selected are fixed until explicitly
12739            // changed.
12740            ps.installPermissionsFixed = true;
12741        }
12742
12743        // Persist the runtime permissions state for users with changes. If permissions
12744        // were revoked because no app in the shared user declares them we have to
12745        // write synchronously to avoid losing runtime permissions state.
12746        for (int userId : changedRuntimePermissionUserIds) {
12747            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12748        }
12749    }
12750
12751    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12752        boolean allowed = false;
12753        final int NP = PackageParser.NEW_PERMISSIONS.length;
12754        for (int ip=0; ip<NP; ip++) {
12755            final PackageParser.NewPermissionInfo npi
12756                    = PackageParser.NEW_PERMISSIONS[ip];
12757            if (npi.name.equals(perm)
12758                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12759                allowed = true;
12760                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12761                        + pkg.packageName);
12762                break;
12763            }
12764        }
12765        return allowed;
12766    }
12767
12768    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12769            BasePermission bp, PermissionsState origPermissions) {
12770        boolean privilegedPermission = (bp.protectionLevel
12771                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12772        boolean privappPermissionsDisable =
12773                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12774        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12775        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12776        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12777                && !platformPackage && platformPermission) {
12778            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12779                    .getPrivAppPermissions(pkg.packageName);
12780            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12781            if (!whitelisted) {
12782                Slog.w(TAG, "Privileged permission " + perm + " for package "
12783                        + pkg.packageName + " - not in privapp-permissions whitelist");
12784                // Only report violations for apps on system image
12785                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12786                    if (mPrivappPermissionsViolations == null) {
12787                        mPrivappPermissionsViolations = new ArraySet<>();
12788                    }
12789                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12790                }
12791                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12792                    return false;
12793                }
12794            }
12795        }
12796        boolean allowed = (compareSignatures(
12797                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12798                        == PackageManager.SIGNATURE_MATCH)
12799                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12800                        == PackageManager.SIGNATURE_MATCH);
12801        if (!allowed && privilegedPermission) {
12802            if (isSystemApp(pkg)) {
12803                // For updated system applications, a system permission
12804                // is granted only if it had been defined by the original application.
12805                if (pkg.isUpdatedSystemApp()) {
12806                    final PackageSetting sysPs = mSettings
12807                            .getDisabledSystemPkgLPr(pkg.packageName);
12808                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12809                        // If the original was granted this permission, we take
12810                        // that grant decision as read and propagate it to the
12811                        // update.
12812                        if (sysPs.isPrivileged()) {
12813                            allowed = true;
12814                        }
12815                    } else {
12816                        // The system apk may have been updated with an older
12817                        // version of the one on the data partition, but which
12818                        // granted a new system permission that it didn't have
12819                        // before.  In this case we do want to allow the app to
12820                        // now get the new permission if the ancestral apk is
12821                        // privileged to get it.
12822                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12823                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12824                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12825                                    allowed = true;
12826                                    break;
12827                                }
12828                            }
12829                        }
12830                        // Also if a privileged parent package on the system image or any of
12831                        // its children requested a privileged permission, the updated child
12832                        // packages can also get the permission.
12833                        if (pkg.parentPackage != null) {
12834                            final PackageSetting disabledSysParentPs = mSettings
12835                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12836                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12837                                    && disabledSysParentPs.isPrivileged()) {
12838                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12839                                    allowed = true;
12840                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12841                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12842                                    for (int i = 0; i < count; i++) {
12843                                        PackageParser.Package disabledSysChildPkg =
12844                                                disabledSysParentPs.pkg.childPackages.get(i);
12845                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12846                                                perm)) {
12847                                            allowed = true;
12848                                            break;
12849                                        }
12850                                    }
12851                                }
12852                            }
12853                        }
12854                    }
12855                } else {
12856                    allowed = isPrivilegedApp(pkg);
12857                }
12858            }
12859        }
12860        if (!allowed) {
12861            if (!allowed && (bp.protectionLevel
12862                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12863                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12864                // If this was a previously normal/dangerous permission that got moved
12865                // to a system permission as part of the runtime permission redesign, then
12866                // we still want to blindly grant it to old apps.
12867                allowed = true;
12868            }
12869            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12870                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12871                // If this permission is to be granted to the system installer and
12872                // this app is an installer, then it gets the permission.
12873                allowed = true;
12874            }
12875            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12876                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12877                // If this permission is to be granted to the system verifier and
12878                // this app is a verifier, then it gets the permission.
12879                allowed = true;
12880            }
12881            if (!allowed && (bp.protectionLevel
12882                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12883                    && isSystemApp(pkg)) {
12884                // Any pre-installed system app is allowed to get this permission.
12885                allowed = true;
12886            }
12887            if (!allowed && (bp.protectionLevel
12888                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12889                // For development permissions, a development permission
12890                // is granted only if it was already granted.
12891                allowed = origPermissions.hasInstallPermission(perm);
12892            }
12893            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12894                    && pkg.packageName.equals(mSetupWizardPackage)) {
12895                // If this permission is to be granted to the system setup wizard and
12896                // this app is a setup wizard, then it gets the permission.
12897                allowed = true;
12898            }
12899        }
12900        return allowed;
12901    }
12902
12903    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12904        final int permCount = pkg.requestedPermissions.size();
12905        for (int j = 0; j < permCount; j++) {
12906            String requestedPermission = pkg.requestedPermissions.get(j);
12907            if (permission.equals(requestedPermission)) {
12908                return true;
12909            }
12910        }
12911        return false;
12912    }
12913
12914    final class ActivityIntentResolver
12915            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12916        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12917                boolean defaultOnly, int userId) {
12918            if (!sUserManager.exists(userId)) return null;
12919            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12920            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12921        }
12922
12923        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12924                int userId) {
12925            if (!sUserManager.exists(userId)) return null;
12926            mFlags = flags;
12927            return super.queryIntent(intent, resolvedType,
12928                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12929                    userId);
12930        }
12931
12932        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12933                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12934            if (!sUserManager.exists(userId)) return null;
12935            if (packageActivities == null) {
12936                return null;
12937            }
12938            mFlags = flags;
12939            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12940            final int N = packageActivities.size();
12941            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12942                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12943
12944            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12945            for (int i = 0; i < N; ++i) {
12946                intentFilters = packageActivities.get(i).intents;
12947                if (intentFilters != null && intentFilters.size() > 0) {
12948                    PackageParser.ActivityIntentInfo[] array =
12949                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12950                    intentFilters.toArray(array);
12951                    listCut.add(array);
12952                }
12953            }
12954            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12955        }
12956
12957        /**
12958         * Finds a privileged activity that matches the specified activity names.
12959         */
12960        private PackageParser.Activity findMatchingActivity(
12961                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12962            for (PackageParser.Activity sysActivity : activityList) {
12963                if (sysActivity.info.name.equals(activityInfo.name)) {
12964                    return sysActivity;
12965                }
12966                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12967                    return sysActivity;
12968                }
12969                if (sysActivity.info.targetActivity != null) {
12970                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12971                        return sysActivity;
12972                    }
12973                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12974                        return sysActivity;
12975                    }
12976                }
12977            }
12978            return null;
12979        }
12980
12981        public class IterGenerator<E> {
12982            public Iterator<E> generate(ActivityIntentInfo info) {
12983                return null;
12984            }
12985        }
12986
12987        public class ActionIterGenerator extends IterGenerator<String> {
12988            @Override
12989            public Iterator<String> generate(ActivityIntentInfo info) {
12990                return info.actionsIterator();
12991            }
12992        }
12993
12994        public class CategoriesIterGenerator extends IterGenerator<String> {
12995            @Override
12996            public Iterator<String> generate(ActivityIntentInfo info) {
12997                return info.categoriesIterator();
12998            }
12999        }
13000
13001        public class SchemesIterGenerator extends IterGenerator<String> {
13002            @Override
13003            public Iterator<String> generate(ActivityIntentInfo info) {
13004                return info.schemesIterator();
13005            }
13006        }
13007
13008        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13009            @Override
13010            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13011                return info.authoritiesIterator();
13012            }
13013        }
13014
13015        /**
13016         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13017         * MODIFIED. Do not pass in a list that should not be changed.
13018         */
13019        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13020                IterGenerator<T> generator, Iterator<T> searchIterator) {
13021            // loop through the set of actions; every one must be found in the intent filter
13022            while (searchIterator.hasNext()) {
13023                // we must have at least one filter in the list to consider a match
13024                if (intentList.size() == 0) {
13025                    break;
13026                }
13027
13028                final T searchAction = searchIterator.next();
13029
13030                // loop through the set of intent filters
13031                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13032                while (intentIter.hasNext()) {
13033                    final ActivityIntentInfo intentInfo = intentIter.next();
13034                    boolean selectionFound = false;
13035
13036                    // loop through the intent filter's selection criteria; at least one
13037                    // of them must match the searched criteria
13038                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13039                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13040                        final T intentSelection = intentSelectionIter.next();
13041                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13042                            selectionFound = true;
13043                            break;
13044                        }
13045                    }
13046
13047                    // the selection criteria wasn't found in this filter's set; this filter
13048                    // is not a potential match
13049                    if (!selectionFound) {
13050                        intentIter.remove();
13051                    }
13052                }
13053            }
13054        }
13055
13056        private boolean isProtectedAction(ActivityIntentInfo filter) {
13057            final Iterator<String> actionsIter = filter.actionsIterator();
13058            while (actionsIter != null && actionsIter.hasNext()) {
13059                final String filterAction = actionsIter.next();
13060                if (PROTECTED_ACTIONS.contains(filterAction)) {
13061                    return true;
13062                }
13063            }
13064            return false;
13065        }
13066
13067        /**
13068         * Adjusts the priority of the given intent filter according to policy.
13069         * <p>
13070         * <ul>
13071         * <li>The priority for non privileged applications is capped to '0'</li>
13072         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13073         * <li>The priority for unbundled updates to privileged applications is capped to the
13074         *      priority defined on the system partition</li>
13075         * </ul>
13076         * <p>
13077         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13078         * allowed to obtain any priority on any action.
13079         */
13080        private void adjustPriority(
13081                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13082            // nothing to do; priority is fine as-is
13083            if (intent.getPriority() <= 0) {
13084                return;
13085            }
13086
13087            final ActivityInfo activityInfo = intent.activity.info;
13088            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13089
13090            final boolean privilegedApp =
13091                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13092            if (!privilegedApp) {
13093                // non-privileged applications can never define a priority >0
13094                if (DEBUG_FILTERS) {
13095                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13096                            + " package: " + applicationInfo.packageName
13097                            + " activity: " + intent.activity.className
13098                            + " origPrio: " + intent.getPriority());
13099                }
13100                intent.setPriority(0);
13101                return;
13102            }
13103
13104            if (systemActivities == null) {
13105                // the system package is not disabled; we're parsing the system partition
13106                if (isProtectedAction(intent)) {
13107                    if (mDeferProtectedFilters) {
13108                        // We can't deal with these just yet. No component should ever obtain a
13109                        // >0 priority for a protected actions, with ONE exception -- the setup
13110                        // wizard. The setup wizard, however, cannot be known until we're able to
13111                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13112                        // until all intent filters have been processed. Chicken, meet egg.
13113                        // Let the filter temporarily have a high priority and rectify the
13114                        // priorities after all system packages have been scanned.
13115                        mProtectedFilters.add(intent);
13116                        if (DEBUG_FILTERS) {
13117                            Slog.i(TAG, "Protected action; save for later;"
13118                                    + " package: " + applicationInfo.packageName
13119                                    + " activity: " + intent.activity.className
13120                                    + " origPrio: " + intent.getPriority());
13121                        }
13122                        return;
13123                    } else {
13124                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13125                            Slog.i(TAG, "No setup wizard;"
13126                                + " All protected intents capped to priority 0");
13127                        }
13128                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13129                            if (DEBUG_FILTERS) {
13130                                Slog.i(TAG, "Found setup wizard;"
13131                                    + " allow priority " + intent.getPriority() + ";"
13132                                    + " package: " + intent.activity.info.packageName
13133                                    + " activity: " + intent.activity.className
13134                                    + " priority: " + intent.getPriority());
13135                            }
13136                            // setup wizard gets whatever it wants
13137                            return;
13138                        }
13139                        if (DEBUG_FILTERS) {
13140                            Slog.i(TAG, "Protected action; cap priority to 0;"
13141                                    + " package: " + intent.activity.info.packageName
13142                                    + " activity: " + intent.activity.className
13143                                    + " origPrio: " + intent.getPriority());
13144                        }
13145                        intent.setPriority(0);
13146                        return;
13147                    }
13148                }
13149                // privileged apps on the system image get whatever priority they request
13150                return;
13151            }
13152
13153            // privileged app unbundled update ... try to find the same activity
13154            final PackageParser.Activity foundActivity =
13155                    findMatchingActivity(systemActivities, activityInfo);
13156            if (foundActivity == null) {
13157                // this is a new activity; it cannot obtain >0 priority
13158                if (DEBUG_FILTERS) {
13159                    Slog.i(TAG, "New activity; cap priority to 0;"
13160                            + " package: " + applicationInfo.packageName
13161                            + " activity: " + intent.activity.className
13162                            + " origPrio: " + intent.getPriority());
13163                }
13164                intent.setPriority(0);
13165                return;
13166            }
13167
13168            // found activity, now check for filter equivalence
13169
13170            // a shallow copy is enough; we modify the list, not its contents
13171            final List<ActivityIntentInfo> intentListCopy =
13172                    new ArrayList<>(foundActivity.intents);
13173            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13174
13175            // find matching action subsets
13176            final Iterator<String> actionsIterator = intent.actionsIterator();
13177            if (actionsIterator != null) {
13178                getIntentListSubset(
13179                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13180                if (intentListCopy.size() == 0) {
13181                    // no more intents to match; we're not equivalent
13182                    if (DEBUG_FILTERS) {
13183                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13184                                + " package: " + applicationInfo.packageName
13185                                + " activity: " + intent.activity.className
13186                                + " origPrio: " + intent.getPriority());
13187                    }
13188                    intent.setPriority(0);
13189                    return;
13190                }
13191            }
13192
13193            // find matching category subsets
13194            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13195            if (categoriesIterator != null) {
13196                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13197                        categoriesIterator);
13198                if (intentListCopy.size() == 0) {
13199                    // no more intents to match; we're not equivalent
13200                    if (DEBUG_FILTERS) {
13201                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13202                                + " package: " + applicationInfo.packageName
13203                                + " activity: " + intent.activity.className
13204                                + " origPrio: " + intent.getPriority());
13205                    }
13206                    intent.setPriority(0);
13207                    return;
13208                }
13209            }
13210
13211            // find matching schemes subsets
13212            final Iterator<String> schemesIterator = intent.schemesIterator();
13213            if (schemesIterator != null) {
13214                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13215                        schemesIterator);
13216                if (intentListCopy.size() == 0) {
13217                    // no more intents to match; we're not equivalent
13218                    if (DEBUG_FILTERS) {
13219                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13220                                + " package: " + applicationInfo.packageName
13221                                + " activity: " + intent.activity.className
13222                                + " origPrio: " + intent.getPriority());
13223                    }
13224                    intent.setPriority(0);
13225                    return;
13226                }
13227            }
13228
13229            // find matching authorities subsets
13230            final Iterator<IntentFilter.AuthorityEntry>
13231                    authoritiesIterator = intent.authoritiesIterator();
13232            if (authoritiesIterator != null) {
13233                getIntentListSubset(intentListCopy,
13234                        new AuthoritiesIterGenerator(),
13235                        authoritiesIterator);
13236                if (intentListCopy.size() == 0) {
13237                    // no more intents to match; we're not equivalent
13238                    if (DEBUG_FILTERS) {
13239                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13240                                + " package: " + applicationInfo.packageName
13241                                + " activity: " + intent.activity.className
13242                                + " origPrio: " + intent.getPriority());
13243                    }
13244                    intent.setPriority(0);
13245                    return;
13246                }
13247            }
13248
13249            // we found matching filter(s); app gets the max priority of all intents
13250            int cappedPriority = 0;
13251            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13252                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13253            }
13254            if (intent.getPriority() > cappedPriority) {
13255                if (DEBUG_FILTERS) {
13256                    Slog.i(TAG, "Found matching filter(s);"
13257                            + " cap priority to " + cappedPriority + ";"
13258                            + " package: " + applicationInfo.packageName
13259                            + " activity: " + intent.activity.className
13260                            + " origPrio: " + intent.getPriority());
13261                }
13262                intent.setPriority(cappedPriority);
13263                return;
13264            }
13265            // all this for nothing; the requested priority was <= what was on the system
13266        }
13267
13268        public final void addActivity(PackageParser.Activity a, String type) {
13269            mActivities.put(a.getComponentName(), a);
13270            if (DEBUG_SHOW_INFO)
13271                Log.v(
13272                TAG, "  " + type + " " +
13273                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13274            if (DEBUG_SHOW_INFO)
13275                Log.v(TAG, "    Class=" + a.info.name);
13276            final int NI = a.intents.size();
13277            for (int j=0; j<NI; j++) {
13278                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13279                if ("activity".equals(type)) {
13280                    final PackageSetting ps =
13281                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13282                    final List<PackageParser.Activity> systemActivities =
13283                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13284                    adjustPriority(systemActivities, intent);
13285                }
13286                if (DEBUG_SHOW_INFO) {
13287                    Log.v(TAG, "    IntentFilter:");
13288                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13289                }
13290                if (!intent.debugCheck()) {
13291                    Log.w(TAG, "==> For Activity " + a.info.name);
13292                }
13293                addFilter(intent);
13294            }
13295        }
13296
13297        public final void removeActivity(PackageParser.Activity a, String type) {
13298            mActivities.remove(a.getComponentName());
13299            if (DEBUG_SHOW_INFO) {
13300                Log.v(TAG, "  " + type + " "
13301                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13302                                : a.info.name) + ":");
13303                Log.v(TAG, "    Class=" + a.info.name);
13304            }
13305            final int NI = a.intents.size();
13306            for (int j=0; j<NI; j++) {
13307                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13308                if (DEBUG_SHOW_INFO) {
13309                    Log.v(TAG, "    IntentFilter:");
13310                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13311                }
13312                removeFilter(intent);
13313            }
13314        }
13315
13316        @Override
13317        protected boolean allowFilterResult(
13318                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13319            ActivityInfo filterAi = filter.activity.info;
13320            for (int i=dest.size()-1; i>=0; i--) {
13321                ActivityInfo destAi = dest.get(i).activityInfo;
13322                if (destAi.name == filterAi.name
13323                        && destAi.packageName == filterAi.packageName) {
13324                    return false;
13325                }
13326            }
13327            return true;
13328        }
13329
13330        @Override
13331        protected ActivityIntentInfo[] newArray(int size) {
13332            return new ActivityIntentInfo[size];
13333        }
13334
13335        @Override
13336        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13337            if (!sUserManager.exists(userId)) return true;
13338            PackageParser.Package p = filter.activity.owner;
13339            if (p != null) {
13340                PackageSetting ps = (PackageSetting)p.mExtras;
13341                if (ps != null) {
13342                    // System apps are never considered stopped for purposes of
13343                    // filtering, because there may be no way for the user to
13344                    // actually re-launch them.
13345                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13346                            && ps.getStopped(userId);
13347                }
13348            }
13349            return false;
13350        }
13351
13352        @Override
13353        protected boolean isPackageForFilter(String packageName,
13354                PackageParser.ActivityIntentInfo info) {
13355            return packageName.equals(info.activity.owner.packageName);
13356        }
13357
13358        @Override
13359        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13360                int match, int userId) {
13361            if (!sUserManager.exists(userId)) return null;
13362            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13363                return null;
13364            }
13365            final PackageParser.Activity activity = info.activity;
13366            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13367            if (ps == null) {
13368                return null;
13369            }
13370            final PackageUserState userState = ps.readUserState(userId);
13371            ActivityInfo ai =
13372                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13373            if (ai == null) {
13374                return null;
13375            }
13376            final boolean matchExplicitlyVisibleOnly =
13377                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13378            final boolean matchVisibleToInstantApp =
13379                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13380            final boolean componentVisible =
13381                    matchVisibleToInstantApp
13382                    && info.isVisibleToInstantApp()
13383                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13384            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13385            // throw out filters that aren't visible to ephemeral apps
13386            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13387                return null;
13388            }
13389            // throw out instant app filters if we're not explicitly requesting them
13390            if (!matchInstantApp && userState.instantApp) {
13391                return null;
13392            }
13393            // throw out instant app filters if updates are available; will trigger
13394            // instant app resolution
13395            if (userState.instantApp && ps.isUpdateAvailable()) {
13396                return null;
13397            }
13398            final ResolveInfo res = new ResolveInfo();
13399            res.activityInfo = ai;
13400            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13401                res.filter = info;
13402            }
13403            if (info != null) {
13404                res.handleAllWebDataURI = info.handleAllWebDataURI();
13405            }
13406            res.priority = info.getPriority();
13407            res.preferredOrder = activity.owner.mPreferredOrder;
13408            //System.out.println("Result: " + res.activityInfo.className +
13409            //                   " = " + res.priority);
13410            res.match = match;
13411            res.isDefault = info.hasDefault;
13412            res.labelRes = info.labelRes;
13413            res.nonLocalizedLabel = info.nonLocalizedLabel;
13414            if (userNeedsBadging(userId)) {
13415                res.noResourceId = true;
13416            } else {
13417                res.icon = info.icon;
13418            }
13419            res.iconResourceId = info.icon;
13420            res.system = res.activityInfo.applicationInfo.isSystemApp();
13421            res.isInstantAppAvailable = userState.instantApp;
13422            return res;
13423        }
13424
13425        @Override
13426        protected void sortResults(List<ResolveInfo> results) {
13427            Collections.sort(results, mResolvePrioritySorter);
13428        }
13429
13430        @Override
13431        protected void dumpFilter(PrintWriter out, String prefix,
13432                PackageParser.ActivityIntentInfo filter) {
13433            out.print(prefix); out.print(
13434                    Integer.toHexString(System.identityHashCode(filter.activity)));
13435                    out.print(' ');
13436                    filter.activity.printComponentShortName(out);
13437                    out.print(" filter ");
13438                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13439        }
13440
13441        @Override
13442        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13443            return filter.activity;
13444        }
13445
13446        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13447            PackageParser.Activity activity = (PackageParser.Activity)label;
13448            out.print(prefix); out.print(
13449                    Integer.toHexString(System.identityHashCode(activity)));
13450                    out.print(' ');
13451                    activity.printComponentShortName(out);
13452            if (count > 1) {
13453                out.print(" ("); out.print(count); out.print(" filters)");
13454            }
13455            out.println();
13456        }
13457
13458        // Keys are String (activity class name), values are Activity.
13459        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13460                = new ArrayMap<ComponentName, PackageParser.Activity>();
13461        private int mFlags;
13462    }
13463
13464    private final class ServiceIntentResolver
13465            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13466        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13467                boolean defaultOnly, int userId) {
13468            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13469            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13470        }
13471
13472        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13473                int userId) {
13474            if (!sUserManager.exists(userId)) return null;
13475            mFlags = flags;
13476            return super.queryIntent(intent, resolvedType,
13477                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13478                    userId);
13479        }
13480
13481        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13482                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13483            if (!sUserManager.exists(userId)) return null;
13484            if (packageServices == null) {
13485                return null;
13486            }
13487            mFlags = flags;
13488            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13489            final int N = packageServices.size();
13490            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13491                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13492
13493            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13494            for (int i = 0; i < N; ++i) {
13495                intentFilters = packageServices.get(i).intents;
13496                if (intentFilters != null && intentFilters.size() > 0) {
13497                    PackageParser.ServiceIntentInfo[] array =
13498                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13499                    intentFilters.toArray(array);
13500                    listCut.add(array);
13501                }
13502            }
13503            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13504        }
13505
13506        public final void addService(PackageParser.Service s) {
13507            mServices.put(s.getComponentName(), s);
13508            if (DEBUG_SHOW_INFO) {
13509                Log.v(TAG, "  "
13510                        + (s.info.nonLocalizedLabel != null
13511                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13512                Log.v(TAG, "    Class=" + s.info.name);
13513            }
13514            final int NI = s.intents.size();
13515            int j;
13516            for (j=0; j<NI; j++) {
13517                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13518                if (DEBUG_SHOW_INFO) {
13519                    Log.v(TAG, "    IntentFilter:");
13520                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13521                }
13522                if (!intent.debugCheck()) {
13523                    Log.w(TAG, "==> For Service " + s.info.name);
13524                }
13525                addFilter(intent);
13526            }
13527        }
13528
13529        public final void removeService(PackageParser.Service s) {
13530            mServices.remove(s.getComponentName());
13531            if (DEBUG_SHOW_INFO) {
13532                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13533                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13534                Log.v(TAG, "    Class=" + s.info.name);
13535            }
13536            final int NI = s.intents.size();
13537            int j;
13538            for (j=0; j<NI; j++) {
13539                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13540                if (DEBUG_SHOW_INFO) {
13541                    Log.v(TAG, "    IntentFilter:");
13542                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13543                }
13544                removeFilter(intent);
13545            }
13546        }
13547
13548        @Override
13549        protected boolean allowFilterResult(
13550                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13551            ServiceInfo filterSi = filter.service.info;
13552            for (int i=dest.size()-1; i>=0; i--) {
13553                ServiceInfo destAi = dest.get(i).serviceInfo;
13554                if (destAi.name == filterSi.name
13555                        && destAi.packageName == filterSi.packageName) {
13556                    return false;
13557                }
13558            }
13559            return true;
13560        }
13561
13562        @Override
13563        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13564            return new PackageParser.ServiceIntentInfo[size];
13565        }
13566
13567        @Override
13568        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13569            if (!sUserManager.exists(userId)) return true;
13570            PackageParser.Package p = filter.service.owner;
13571            if (p != null) {
13572                PackageSetting ps = (PackageSetting)p.mExtras;
13573                if (ps != null) {
13574                    // System apps are never considered stopped for purposes of
13575                    // filtering, because there may be no way for the user to
13576                    // actually re-launch them.
13577                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13578                            && ps.getStopped(userId);
13579                }
13580            }
13581            return false;
13582        }
13583
13584        @Override
13585        protected boolean isPackageForFilter(String packageName,
13586                PackageParser.ServiceIntentInfo info) {
13587            return packageName.equals(info.service.owner.packageName);
13588        }
13589
13590        @Override
13591        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13592                int match, int userId) {
13593            if (!sUserManager.exists(userId)) return null;
13594            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13595            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13596                return null;
13597            }
13598            final PackageParser.Service service = info.service;
13599            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13600            if (ps == null) {
13601                return null;
13602            }
13603            final PackageUserState userState = ps.readUserState(userId);
13604            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13605                    userState, userId);
13606            if (si == null) {
13607                return null;
13608            }
13609            final boolean matchVisibleToInstantApp =
13610                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13611            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13612            // throw out filters that aren't visible to ephemeral apps
13613            if (matchVisibleToInstantApp
13614                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13615                return null;
13616            }
13617            // throw out ephemeral filters if we're not explicitly requesting them
13618            if (!isInstantApp && userState.instantApp) {
13619                return null;
13620            }
13621            // throw out instant app filters if updates are available; will trigger
13622            // instant app resolution
13623            if (userState.instantApp && ps.isUpdateAvailable()) {
13624                return null;
13625            }
13626            final ResolveInfo res = new ResolveInfo();
13627            res.serviceInfo = si;
13628            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13629                res.filter = filter;
13630            }
13631            res.priority = info.getPriority();
13632            res.preferredOrder = service.owner.mPreferredOrder;
13633            res.match = match;
13634            res.isDefault = info.hasDefault;
13635            res.labelRes = info.labelRes;
13636            res.nonLocalizedLabel = info.nonLocalizedLabel;
13637            res.icon = info.icon;
13638            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13639            return res;
13640        }
13641
13642        @Override
13643        protected void sortResults(List<ResolveInfo> results) {
13644            Collections.sort(results, mResolvePrioritySorter);
13645        }
13646
13647        @Override
13648        protected void dumpFilter(PrintWriter out, String prefix,
13649                PackageParser.ServiceIntentInfo filter) {
13650            out.print(prefix); out.print(
13651                    Integer.toHexString(System.identityHashCode(filter.service)));
13652                    out.print(' ');
13653                    filter.service.printComponentShortName(out);
13654                    out.print(" filter ");
13655                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13656        }
13657
13658        @Override
13659        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13660            return filter.service;
13661        }
13662
13663        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13664            PackageParser.Service service = (PackageParser.Service)label;
13665            out.print(prefix); out.print(
13666                    Integer.toHexString(System.identityHashCode(service)));
13667                    out.print(' ');
13668                    service.printComponentShortName(out);
13669            if (count > 1) {
13670                out.print(" ("); out.print(count); out.print(" filters)");
13671            }
13672            out.println();
13673        }
13674
13675//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13676//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13677//            final List<ResolveInfo> retList = Lists.newArrayList();
13678//            while (i.hasNext()) {
13679//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13680//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13681//                    retList.add(resolveInfo);
13682//                }
13683//            }
13684//            return retList;
13685//        }
13686
13687        // Keys are String (activity class name), values are Activity.
13688        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13689                = new ArrayMap<ComponentName, PackageParser.Service>();
13690        private int mFlags;
13691    }
13692
13693    private final class ProviderIntentResolver
13694            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13695        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13696                boolean defaultOnly, int userId) {
13697            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13698            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13699        }
13700
13701        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13702                int userId) {
13703            if (!sUserManager.exists(userId))
13704                return null;
13705            mFlags = flags;
13706            return super.queryIntent(intent, resolvedType,
13707                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13708                    userId);
13709        }
13710
13711        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13712                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13713            if (!sUserManager.exists(userId))
13714                return null;
13715            if (packageProviders == null) {
13716                return null;
13717            }
13718            mFlags = flags;
13719            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13720            final int N = packageProviders.size();
13721            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13722                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13723
13724            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13725            for (int i = 0; i < N; ++i) {
13726                intentFilters = packageProviders.get(i).intents;
13727                if (intentFilters != null && intentFilters.size() > 0) {
13728                    PackageParser.ProviderIntentInfo[] array =
13729                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13730                    intentFilters.toArray(array);
13731                    listCut.add(array);
13732                }
13733            }
13734            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13735        }
13736
13737        public final void addProvider(PackageParser.Provider p) {
13738            if (mProviders.containsKey(p.getComponentName())) {
13739                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13740                return;
13741            }
13742
13743            mProviders.put(p.getComponentName(), p);
13744            if (DEBUG_SHOW_INFO) {
13745                Log.v(TAG, "  "
13746                        + (p.info.nonLocalizedLabel != null
13747                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13748                Log.v(TAG, "    Class=" + p.info.name);
13749            }
13750            final int NI = p.intents.size();
13751            int j;
13752            for (j = 0; j < NI; j++) {
13753                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13754                if (DEBUG_SHOW_INFO) {
13755                    Log.v(TAG, "    IntentFilter:");
13756                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13757                }
13758                if (!intent.debugCheck()) {
13759                    Log.w(TAG, "==> For Provider " + p.info.name);
13760                }
13761                addFilter(intent);
13762            }
13763        }
13764
13765        public final void removeProvider(PackageParser.Provider p) {
13766            mProviders.remove(p.getComponentName());
13767            if (DEBUG_SHOW_INFO) {
13768                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13769                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13770                Log.v(TAG, "    Class=" + p.info.name);
13771            }
13772            final int NI = p.intents.size();
13773            int j;
13774            for (j = 0; j < NI; j++) {
13775                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13776                if (DEBUG_SHOW_INFO) {
13777                    Log.v(TAG, "    IntentFilter:");
13778                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13779                }
13780                removeFilter(intent);
13781            }
13782        }
13783
13784        @Override
13785        protected boolean allowFilterResult(
13786                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13787            ProviderInfo filterPi = filter.provider.info;
13788            for (int i = dest.size() - 1; i >= 0; i--) {
13789                ProviderInfo destPi = dest.get(i).providerInfo;
13790                if (destPi.name == filterPi.name
13791                        && destPi.packageName == filterPi.packageName) {
13792                    return false;
13793                }
13794            }
13795            return true;
13796        }
13797
13798        @Override
13799        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13800            return new PackageParser.ProviderIntentInfo[size];
13801        }
13802
13803        @Override
13804        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13805            if (!sUserManager.exists(userId))
13806                return true;
13807            PackageParser.Package p = filter.provider.owner;
13808            if (p != null) {
13809                PackageSetting ps = (PackageSetting) p.mExtras;
13810                if (ps != null) {
13811                    // System apps are never considered stopped for purposes of
13812                    // filtering, because there may be no way for the user to
13813                    // actually re-launch them.
13814                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13815                            && ps.getStopped(userId);
13816                }
13817            }
13818            return false;
13819        }
13820
13821        @Override
13822        protected boolean isPackageForFilter(String packageName,
13823                PackageParser.ProviderIntentInfo info) {
13824            return packageName.equals(info.provider.owner.packageName);
13825        }
13826
13827        @Override
13828        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13829                int match, int userId) {
13830            if (!sUserManager.exists(userId))
13831                return null;
13832            final PackageParser.ProviderIntentInfo info = filter;
13833            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13834                return null;
13835            }
13836            final PackageParser.Provider provider = info.provider;
13837            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13838            if (ps == null) {
13839                return null;
13840            }
13841            final PackageUserState userState = ps.readUserState(userId);
13842            final boolean matchVisibleToInstantApp =
13843                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13844            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13845            // throw out filters that aren't visible to instant applications
13846            if (matchVisibleToInstantApp
13847                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13848                return null;
13849            }
13850            // throw out instant application filters if we're not explicitly requesting them
13851            if (!isInstantApp && userState.instantApp) {
13852                return null;
13853            }
13854            // throw out instant application filters if updates are available; will trigger
13855            // instant application resolution
13856            if (userState.instantApp && ps.isUpdateAvailable()) {
13857                return null;
13858            }
13859            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13860                    userState, userId);
13861            if (pi == null) {
13862                return null;
13863            }
13864            final ResolveInfo res = new ResolveInfo();
13865            res.providerInfo = pi;
13866            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13867                res.filter = filter;
13868            }
13869            res.priority = info.getPriority();
13870            res.preferredOrder = provider.owner.mPreferredOrder;
13871            res.match = match;
13872            res.isDefault = info.hasDefault;
13873            res.labelRes = info.labelRes;
13874            res.nonLocalizedLabel = info.nonLocalizedLabel;
13875            res.icon = info.icon;
13876            res.system = res.providerInfo.applicationInfo.isSystemApp();
13877            return res;
13878        }
13879
13880        @Override
13881        protected void sortResults(List<ResolveInfo> results) {
13882            Collections.sort(results, mResolvePrioritySorter);
13883        }
13884
13885        @Override
13886        protected void dumpFilter(PrintWriter out, String prefix,
13887                PackageParser.ProviderIntentInfo filter) {
13888            out.print(prefix);
13889            out.print(
13890                    Integer.toHexString(System.identityHashCode(filter.provider)));
13891            out.print(' ');
13892            filter.provider.printComponentShortName(out);
13893            out.print(" filter ");
13894            out.println(Integer.toHexString(System.identityHashCode(filter)));
13895        }
13896
13897        @Override
13898        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13899            return filter.provider;
13900        }
13901
13902        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13903            PackageParser.Provider provider = (PackageParser.Provider)label;
13904            out.print(prefix); out.print(
13905                    Integer.toHexString(System.identityHashCode(provider)));
13906                    out.print(' ');
13907                    provider.printComponentShortName(out);
13908            if (count > 1) {
13909                out.print(" ("); out.print(count); out.print(" filters)");
13910            }
13911            out.println();
13912        }
13913
13914        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13915                = new ArrayMap<ComponentName, PackageParser.Provider>();
13916        private int mFlags;
13917    }
13918
13919    static final class EphemeralIntentResolver
13920            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13921        /**
13922         * The result that has the highest defined order. Ordering applies on a
13923         * per-package basis. Mapping is from package name to Pair of order and
13924         * EphemeralResolveInfo.
13925         * <p>
13926         * NOTE: This is implemented as a field variable for convenience and efficiency.
13927         * By having a field variable, we're able to track filter ordering as soon as
13928         * a non-zero order is defined. Otherwise, multiple loops across the result set
13929         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13930         * this needs to be contained entirely within {@link #filterResults}.
13931         */
13932        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13933
13934        @Override
13935        protected AuxiliaryResolveInfo[] newArray(int size) {
13936            return new AuxiliaryResolveInfo[size];
13937        }
13938
13939        @Override
13940        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13941            return true;
13942        }
13943
13944        @Override
13945        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13946                int userId) {
13947            if (!sUserManager.exists(userId)) {
13948                return null;
13949            }
13950            final String packageName = responseObj.resolveInfo.getPackageName();
13951            final Integer order = responseObj.getOrder();
13952            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13953                    mOrderResult.get(packageName);
13954            // ordering is enabled and this item's order isn't high enough
13955            if (lastOrderResult != null && lastOrderResult.first >= order) {
13956                return null;
13957            }
13958            final InstantAppResolveInfo res = responseObj.resolveInfo;
13959            if (order > 0) {
13960                // non-zero order, enable ordering
13961                mOrderResult.put(packageName, new Pair<>(order, res));
13962            }
13963            return responseObj;
13964        }
13965
13966        @Override
13967        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13968            // only do work if ordering is enabled [most of the time it won't be]
13969            if (mOrderResult.size() == 0) {
13970                return;
13971            }
13972            int resultSize = results.size();
13973            for (int i = 0; i < resultSize; i++) {
13974                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13975                final String packageName = info.getPackageName();
13976                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13977                if (savedInfo == null) {
13978                    // package doesn't having ordering
13979                    continue;
13980                }
13981                if (savedInfo.second == info) {
13982                    // circled back to the highest ordered item; remove from order list
13983                    mOrderResult.remove(savedInfo);
13984                    if (mOrderResult.size() == 0) {
13985                        // no more ordered items
13986                        break;
13987                    }
13988                    continue;
13989                }
13990                // item has a worse order, remove it from the result list
13991                results.remove(i);
13992                resultSize--;
13993                i--;
13994            }
13995        }
13996    }
13997
13998    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13999            new Comparator<ResolveInfo>() {
14000        public int compare(ResolveInfo r1, ResolveInfo r2) {
14001            int v1 = r1.priority;
14002            int v2 = r2.priority;
14003            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14004            if (v1 != v2) {
14005                return (v1 > v2) ? -1 : 1;
14006            }
14007            v1 = r1.preferredOrder;
14008            v2 = r2.preferredOrder;
14009            if (v1 != v2) {
14010                return (v1 > v2) ? -1 : 1;
14011            }
14012            if (r1.isDefault != r2.isDefault) {
14013                return r1.isDefault ? -1 : 1;
14014            }
14015            v1 = r1.match;
14016            v2 = r2.match;
14017            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14018            if (v1 != v2) {
14019                return (v1 > v2) ? -1 : 1;
14020            }
14021            if (r1.system != r2.system) {
14022                return r1.system ? -1 : 1;
14023            }
14024            if (r1.activityInfo != null) {
14025                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14026            }
14027            if (r1.serviceInfo != null) {
14028                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14029            }
14030            if (r1.providerInfo != null) {
14031                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14032            }
14033            return 0;
14034        }
14035    };
14036
14037    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14038            new Comparator<ProviderInfo>() {
14039        public int compare(ProviderInfo p1, ProviderInfo p2) {
14040            final int v1 = p1.initOrder;
14041            final int v2 = p2.initOrder;
14042            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14043        }
14044    };
14045
14046    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14047            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14048            final int[] userIds) {
14049        mHandler.post(new Runnable() {
14050            @Override
14051            public void run() {
14052                try {
14053                    final IActivityManager am = ActivityManager.getService();
14054                    if (am == null) return;
14055                    final int[] resolvedUserIds;
14056                    if (userIds == null) {
14057                        resolvedUserIds = am.getRunningUserIds();
14058                    } else {
14059                        resolvedUserIds = userIds;
14060                    }
14061                    for (int id : resolvedUserIds) {
14062                        final Intent intent = new Intent(action,
14063                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14064                        if (extras != null) {
14065                            intent.putExtras(extras);
14066                        }
14067                        if (targetPkg != null) {
14068                            intent.setPackage(targetPkg);
14069                        }
14070                        // Modify the UID when posting to other users
14071                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14072                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14073                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14074                            intent.putExtra(Intent.EXTRA_UID, uid);
14075                        }
14076                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14077                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14078                        if (DEBUG_BROADCASTS) {
14079                            RuntimeException here = new RuntimeException("here");
14080                            here.fillInStackTrace();
14081                            Slog.d(TAG, "Sending to user " + id + ": "
14082                                    + intent.toShortString(false, true, false, false)
14083                                    + " " + intent.getExtras(), here);
14084                        }
14085                        am.broadcastIntent(null, intent, null, finishedReceiver,
14086                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14087                                null, finishedReceiver != null, false, id);
14088                    }
14089                } catch (RemoteException ex) {
14090                }
14091            }
14092        });
14093    }
14094
14095    /**
14096     * Check if the external storage media is available. This is true if there
14097     * is a mounted external storage medium or if the external storage is
14098     * emulated.
14099     */
14100    private boolean isExternalMediaAvailable() {
14101        return mMediaMounted || Environment.isExternalStorageEmulated();
14102    }
14103
14104    @Override
14105    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14106        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14107            return null;
14108        }
14109        // writer
14110        synchronized (mPackages) {
14111            if (!isExternalMediaAvailable()) {
14112                // If the external storage is no longer mounted at this point,
14113                // the caller may not have been able to delete all of this
14114                // packages files and can not delete any more.  Bail.
14115                return null;
14116            }
14117            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14118            if (lastPackage != null) {
14119                pkgs.remove(lastPackage);
14120            }
14121            if (pkgs.size() > 0) {
14122                return pkgs.get(0);
14123            }
14124        }
14125        return null;
14126    }
14127
14128    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14129        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14130                userId, andCode ? 1 : 0, packageName);
14131        if (mSystemReady) {
14132            msg.sendToTarget();
14133        } else {
14134            if (mPostSystemReadyMessages == null) {
14135                mPostSystemReadyMessages = new ArrayList<>();
14136            }
14137            mPostSystemReadyMessages.add(msg);
14138        }
14139    }
14140
14141    void startCleaningPackages() {
14142        // reader
14143        if (!isExternalMediaAvailable()) {
14144            return;
14145        }
14146        synchronized (mPackages) {
14147            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14148                return;
14149            }
14150        }
14151        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14152        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14153        IActivityManager am = ActivityManager.getService();
14154        if (am != null) {
14155            int dcsUid = -1;
14156            synchronized (mPackages) {
14157                if (!mDefaultContainerWhitelisted) {
14158                    mDefaultContainerWhitelisted = true;
14159                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14160                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14161                }
14162            }
14163            try {
14164                if (dcsUid > 0) {
14165                    am.backgroundWhitelistUid(dcsUid);
14166                }
14167                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14168                        UserHandle.USER_SYSTEM);
14169            } catch (RemoteException e) {
14170            }
14171        }
14172    }
14173
14174    @Override
14175    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14176            int installFlags, String installerPackageName, int userId) {
14177        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14178
14179        final int callingUid = Binder.getCallingUid();
14180        enforceCrossUserPermission(callingUid, userId,
14181                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14182
14183        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14184            try {
14185                if (observer != null) {
14186                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14187                }
14188            } catch (RemoteException re) {
14189            }
14190            return;
14191        }
14192
14193        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14194            installFlags |= PackageManager.INSTALL_FROM_ADB;
14195
14196        } else {
14197            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14198            // about installerPackageName.
14199
14200            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14201            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14202        }
14203
14204        UserHandle user;
14205        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14206            user = UserHandle.ALL;
14207        } else {
14208            user = new UserHandle(userId);
14209        }
14210
14211        // Only system components can circumvent runtime permissions when installing.
14212        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14213                && mContext.checkCallingOrSelfPermission(Manifest.permission
14214                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14215            throw new SecurityException("You need the "
14216                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14217                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14218        }
14219
14220        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14221                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14222            throw new IllegalArgumentException(
14223                    "New installs into ASEC containers no longer supported");
14224        }
14225
14226        final File originFile = new File(originPath);
14227        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14228
14229        final Message msg = mHandler.obtainMessage(INIT_COPY);
14230        final VerificationInfo verificationInfo = new VerificationInfo(
14231                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14232        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14233                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14234                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14235                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14236        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14237        msg.obj = params;
14238
14239        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14240                System.identityHashCode(msg.obj));
14241        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14242                System.identityHashCode(msg.obj));
14243
14244        mHandler.sendMessage(msg);
14245    }
14246
14247
14248    /**
14249     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14250     * it is acting on behalf on an enterprise or the user).
14251     *
14252     * Note that the ordering of the conditionals in this method is important. The checks we perform
14253     * are as follows, in this order:
14254     *
14255     * 1) If the install is being performed by a system app, we can trust the app to have set the
14256     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14257     *    what it is.
14258     * 2) If the install is being performed by a device or profile owner app, the install reason
14259     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14260     *    set the install reason correctly. If the app targets an older SDK version where install
14261     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14262     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14263     * 3) In all other cases, the install is being performed by a regular app that is neither part
14264     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14265     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14266     *    set to enterprise policy and if so, change it to unknown instead.
14267     */
14268    private int fixUpInstallReason(String installerPackageName, int installerUid,
14269            int installReason) {
14270        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14271                == PERMISSION_GRANTED) {
14272            // If the install is being performed by a system app, we trust that app to have set the
14273            // install reason correctly.
14274            return installReason;
14275        }
14276
14277        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14278            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14279        if (dpm != null) {
14280            ComponentName owner = null;
14281            try {
14282                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14283                if (owner == null) {
14284                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14285                }
14286            } catch (RemoteException e) {
14287            }
14288            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14289                // If the install is being performed by a device or profile owner, the install
14290                // reason should be enterprise policy.
14291                return PackageManager.INSTALL_REASON_POLICY;
14292            }
14293        }
14294
14295        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14296            // If the install is being performed by a regular app (i.e. neither system app nor
14297            // device or profile owner), we have no reason to believe that the app is acting on
14298            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14299            // change it to unknown instead.
14300            return PackageManager.INSTALL_REASON_UNKNOWN;
14301        }
14302
14303        // If the install is being performed by a regular app and the install reason was set to any
14304        // value but enterprise policy, leave the install reason unchanged.
14305        return installReason;
14306    }
14307
14308    void installStage(String packageName, File stagedDir, String stagedCid,
14309            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14310            String installerPackageName, int installerUid, UserHandle user,
14311            Certificate[][] certificates) {
14312        if (DEBUG_EPHEMERAL) {
14313            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14314                Slog.d(TAG, "Ephemeral install of " + packageName);
14315            }
14316        }
14317        final VerificationInfo verificationInfo = new VerificationInfo(
14318                sessionParams.originatingUri, sessionParams.referrerUri,
14319                sessionParams.originatingUid, installerUid);
14320
14321        final OriginInfo origin;
14322        if (stagedDir != null) {
14323            origin = OriginInfo.fromStagedFile(stagedDir);
14324        } else {
14325            origin = OriginInfo.fromStagedContainer(stagedCid);
14326        }
14327
14328        final Message msg = mHandler.obtainMessage(INIT_COPY);
14329        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14330                sessionParams.installReason);
14331        final InstallParams params = new InstallParams(origin, null, observer,
14332                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14333                verificationInfo, user, sessionParams.abiOverride,
14334                sessionParams.grantedRuntimePermissions, certificates, installReason);
14335        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14336        msg.obj = params;
14337
14338        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14339                System.identityHashCode(msg.obj));
14340        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14341                System.identityHashCode(msg.obj));
14342
14343        mHandler.sendMessage(msg);
14344    }
14345
14346    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14347            int userId) {
14348        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14349        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14350
14351        // Send a session commit broadcast
14352        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14353        info.installReason = pkgSetting.getInstallReason(userId);
14354        info.appPackageName = packageName;
14355        sendSessionCommitBroadcast(info, userId);
14356    }
14357
14358    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14359        if (ArrayUtils.isEmpty(userIds)) {
14360            return;
14361        }
14362        Bundle extras = new Bundle(1);
14363        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14364        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14365
14366        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14367                packageName, extras, 0, null, null, userIds);
14368        if (isSystem) {
14369            mHandler.post(() -> {
14370                        for (int userId : userIds) {
14371                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14372                        }
14373                    }
14374            );
14375        }
14376    }
14377
14378    /**
14379     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14380     * automatically without needing an explicit launch.
14381     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14382     */
14383    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14384        // If user is not running, the app didn't miss any broadcast
14385        if (!mUserManagerInternal.isUserRunning(userId)) {
14386            return;
14387        }
14388        final IActivityManager am = ActivityManager.getService();
14389        try {
14390            // Deliver LOCKED_BOOT_COMPLETED first
14391            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14392                    .setPackage(packageName);
14393            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14394            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14395                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14396
14397            // Deliver BOOT_COMPLETED only if user is unlocked
14398            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14399                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14400                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14401                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14402            }
14403        } catch (RemoteException e) {
14404            throw e.rethrowFromSystemServer();
14405        }
14406    }
14407
14408    @Override
14409    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14410            int userId) {
14411        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14412        PackageSetting pkgSetting;
14413        final int callingUid = Binder.getCallingUid();
14414        enforceCrossUserPermission(callingUid, userId,
14415                true /* requireFullPermission */, true /* checkShell */,
14416                "setApplicationHiddenSetting for user " + userId);
14417
14418        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14419            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14420            return false;
14421        }
14422
14423        long callingId = Binder.clearCallingIdentity();
14424        try {
14425            boolean sendAdded = false;
14426            boolean sendRemoved = false;
14427            // writer
14428            synchronized (mPackages) {
14429                pkgSetting = mSettings.mPackages.get(packageName);
14430                if (pkgSetting == null) {
14431                    return false;
14432                }
14433                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14434                    return false;
14435                }
14436                // Do not allow "android" is being disabled
14437                if ("android".equals(packageName)) {
14438                    Slog.w(TAG, "Cannot hide package: android");
14439                    return false;
14440                }
14441                // Cannot hide static shared libs as they are considered
14442                // a part of the using app (emulating static linking). Also
14443                // static libs are installed always on internal storage.
14444                PackageParser.Package pkg = mPackages.get(packageName);
14445                if (pkg != null && pkg.staticSharedLibName != null) {
14446                    Slog.w(TAG, "Cannot hide package: " + packageName
14447                            + " providing static shared library: "
14448                            + pkg.staticSharedLibName);
14449                    return false;
14450                }
14451                // Only allow protected packages to hide themselves.
14452                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14453                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14454                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14455                    return false;
14456                }
14457
14458                if (pkgSetting.getHidden(userId) != hidden) {
14459                    pkgSetting.setHidden(hidden, userId);
14460                    mSettings.writePackageRestrictionsLPr(userId);
14461                    if (hidden) {
14462                        sendRemoved = true;
14463                    } else {
14464                        sendAdded = true;
14465                    }
14466                }
14467            }
14468            if (sendAdded) {
14469                sendPackageAddedForUser(packageName, pkgSetting, userId);
14470                return true;
14471            }
14472            if (sendRemoved) {
14473                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14474                        "hiding pkg");
14475                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14476                return true;
14477            }
14478        } finally {
14479            Binder.restoreCallingIdentity(callingId);
14480        }
14481        return false;
14482    }
14483
14484    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14485            int userId) {
14486        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14487        info.removedPackage = packageName;
14488        info.installerPackageName = pkgSetting.installerPackageName;
14489        info.removedUsers = new int[] {userId};
14490        info.broadcastUsers = new int[] {userId};
14491        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14492        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14493    }
14494
14495    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14496        if (pkgList.length > 0) {
14497            Bundle extras = new Bundle(1);
14498            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14499
14500            sendPackageBroadcast(
14501                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14502                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14503                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14504                    new int[] {userId});
14505        }
14506    }
14507
14508    /**
14509     * Returns true if application is not found or there was an error. Otherwise it returns
14510     * the hidden state of the package for the given user.
14511     */
14512    @Override
14513    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14514        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14515        final int callingUid = Binder.getCallingUid();
14516        enforceCrossUserPermission(callingUid, userId,
14517                true /* requireFullPermission */, false /* checkShell */,
14518                "getApplicationHidden for user " + userId);
14519        PackageSetting ps;
14520        long callingId = Binder.clearCallingIdentity();
14521        try {
14522            // writer
14523            synchronized (mPackages) {
14524                ps = mSettings.mPackages.get(packageName);
14525                if (ps == null) {
14526                    return true;
14527                }
14528                if (filterAppAccessLPr(ps, callingUid, userId)) {
14529                    return true;
14530                }
14531                return ps.getHidden(userId);
14532            }
14533        } finally {
14534            Binder.restoreCallingIdentity(callingId);
14535        }
14536    }
14537
14538    /**
14539     * @hide
14540     */
14541    @Override
14542    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14543            int installReason) {
14544        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14545                null);
14546        PackageSetting pkgSetting;
14547        final int callingUid = Binder.getCallingUid();
14548        enforceCrossUserPermission(callingUid, userId,
14549                true /* requireFullPermission */, true /* checkShell */,
14550                "installExistingPackage for user " + userId);
14551        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14552            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14553        }
14554
14555        long callingId = Binder.clearCallingIdentity();
14556        try {
14557            boolean installed = false;
14558            final boolean instantApp =
14559                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14560            final boolean fullApp =
14561                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14562
14563            // writer
14564            synchronized (mPackages) {
14565                pkgSetting = mSettings.mPackages.get(packageName);
14566                if (pkgSetting == null) {
14567                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14568                }
14569                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14570                    // only allow the existing package to be used if it's installed as a full
14571                    // application for at least one user
14572                    boolean installAllowed = false;
14573                    for (int checkUserId : sUserManager.getUserIds()) {
14574                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14575                        if (installAllowed) {
14576                            break;
14577                        }
14578                    }
14579                    if (!installAllowed) {
14580                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14581                    }
14582                }
14583                if (!pkgSetting.getInstalled(userId)) {
14584                    pkgSetting.setInstalled(true, userId);
14585                    pkgSetting.setHidden(false, userId);
14586                    pkgSetting.setInstallReason(installReason, userId);
14587                    mSettings.writePackageRestrictionsLPr(userId);
14588                    mSettings.writeKernelMappingLPr(pkgSetting);
14589                    installed = true;
14590                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14591                    // upgrade app from instant to full; we don't allow app downgrade
14592                    installed = true;
14593                }
14594                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14595            }
14596
14597            if (installed) {
14598                if (pkgSetting.pkg != null) {
14599                    synchronized (mInstallLock) {
14600                        // We don't need to freeze for a brand new install
14601                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14602                    }
14603                }
14604                sendPackageAddedForUser(packageName, pkgSetting, userId);
14605                synchronized (mPackages) {
14606                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14607                }
14608            }
14609        } finally {
14610            Binder.restoreCallingIdentity(callingId);
14611        }
14612
14613        return PackageManager.INSTALL_SUCCEEDED;
14614    }
14615
14616    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14617            boolean instantApp, boolean fullApp) {
14618        // no state specified; do nothing
14619        if (!instantApp && !fullApp) {
14620            return;
14621        }
14622        if (userId != UserHandle.USER_ALL) {
14623            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14624                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14625            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14626                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14627            }
14628        } else {
14629            for (int currentUserId : sUserManager.getUserIds()) {
14630                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14631                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14632                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14633                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14634                }
14635            }
14636        }
14637    }
14638
14639    boolean isUserRestricted(int userId, String restrictionKey) {
14640        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14641        if (restrictions.getBoolean(restrictionKey, false)) {
14642            Log.w(TAG, "User is restricted: " + restrictionKey);
14643            return true;
14644        }
14645        return false;
14646    }
14647
14648    @Override
14649    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14650            int userId) {
14651        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14652        final int callingUid = Binder.getCallingUid();
14653        enforceCrossUserPermission(callingUid, userId,
14654                true /* requireFullPermission */, true /* checkShell */,
14655                "setPackagesSuspended for user " + userId);
14656
14657        if (ArrayUtils.isEmpty(packageNames)) {
14658            return packageNames;
14659        }
14660
14661        // List of package names for whom the suspended state has changed.
14662        List<String> changedPackages = new ArrayList<>(packageNames.length);
14663        // List of package names for whom the suspended state is not set as requested in this
14664        // method.
14665        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14666        long callingId = Binder.clearCallingIdentity();
14667        try {
14668            for (int i = 0; i < packageNames.length; i++) {
14669                String packageName = packageNames[i];
14670                boolean changed = false;
14671                final int appId;
14672                synchronized (mPackages) {
14673                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14674                    if (pkgSetting == null
14675                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14676                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14677                                + "\". Skipping suspending/un-suspending.");
14678                        unactionedPackages.add(packageName);
14679                        continue;
14680                    }
14681                    appId = pkgSetting.appId;
14682                    if (pkgSetting.getSuspended(userId) != suspended) {
14683                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14684                            unactionedPackages.add(packageName);
14685                            continue;
14686                        }
14687                        pkgSetting.setSuspended(suspended, userId);
14688                        mSettings.writePackageRestrictionsLPr(userId);
14689                        changed = true;
14690                        changedPackages.add(packageName);
14691                    }
14692                }
14693
14694                if (changed && suspended) {
14695                    killApplication(packageName, UserHandle.getUid(userId, appId),
14696                            "suspending package");
14697                }
14698            }
14699        } finally {
14700            Binder.restoreCallingIdentity(callingId);
14701        }
14702
14703        if (!changedPackages.isEmpty()) {
14704            sendPackagesSuspendedForUser(changedPackages.toArray(
14705                    new String[changedPackages.size()]), userId, suspended);
14706        }
14707
14708        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14709    }
14710
14711    @Override
14712    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14713        final int callingUid = Binder.getCallingUid();
14714        enforceCrossUserPermission(callingUid, userId,
14715                true /* requireFullPermission */, false /* checkShell */,
14716                "isPackageSuspendedForUser for user " + userId);
14717        synchronized (mPackages) {
14718            final PackageSetting ps = mSettings.mPackages.get(packageName);
14719            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14720                throw new IllegalArgumentException("Unknown target package: " + packageName);
14721            }
14722            return ps.getSuspended(userId);
14723        }
14724    }
14725
14726    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14727        if (isPackageDeviceAdmin(packageName, userId)) {
14728            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14729                    + "\": has an active device admin");
14730            return false;
14731        }
14732
14733        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14734        if (packageName.equals(activeLauncherPackageName)) {
14735            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14736                    + "\": contains the active launcher");
14737            return false;
14738        }
14739
14740        if (packageName.equals(mRequiredInstallerPackage)) {
14741            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14742                    + "\": required for package installation");
14743            return false;
14744        }
14745
14746        if (packageName.equals(mRequiredUninstallerPackage)) {
14747            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14748                    + "\": required for package uninstallation");
14749            return false;
14750        }
14751
14752        if (packageName.equals(mRequiredVerifierPackage)) {
14753            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14754                    + "\": required for package verification");
14755            return false;
14756        }
14757
14758        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14759            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14760                    + "\": is the default dialer");
14761            return false;
14762        }
14763
14764        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14765            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14766                    + "\": protected package");
14767            return false;
14768        }
14769
14770        // Cannot suspend static shared libs as they are considered
14771        // a part of the using app (emulating static linking). Also
14772        // static libs are installed always on internal storage.
14773        PackageParser.Package pkg = mPackages.get(packageName);
14774        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14775            Slog.w(TAG, "Cannot suspend package: " + packageName
14776                    + " providing static shared library: "
14777                    + pkg.staticSharedLibName);
14778            return false;
14779        }
14780
14781        return true;
14782    }
14783
14784    private String getActiveLauncherPackageName(int userId) {
14785        Intent intent = new Intent(Intent.ACTION_MAIN);
14786        intent.addCategory(Intent.CATEGORY_HOME);
14787        ResolveInfo resolveInfo = resolveIntent(
14788                intent,
14789                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14790                PackageManager.MATCH_DEFAULT_ONLY,
14791                userId);
14792
14793        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14794    }
14795
14796    private String getDefaultDialerPackageName(int userId) {
14797        synchronized (mPackages) {
14798            return mSettings.getDefaultDialerPackageNameLPw(userId);
14799        }
14800    }
14801
14802    @Override
14803    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14804        mContext.enforceCallingOrSelfPermission(
14805                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14806                "Only package verification agents can verify applications");
14807
14808        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14809        final PackageVerificationResponse response = new PackageVerificationResponse(
14810                verificationCode, Binder.getCallingUid());
14811        msg.arg1 = id;
14812        msg.obj = response;
14813        mHandler.sendMessage(msg);
14814    }
14815
14816    @Override
14817    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14818            long millisecondsToDelay) {
14819        mContext.enforceCallingOrSelfPermission(
14820                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14821                "Only package verification agents can extend verification timeouts");
14822
14823        final PackageVerificationState state = mPendingVerification.get(id);
14824        final PackageVerificationResponse response = new PackageVerificationResponse(
14825                verificationCodeAtTimeout, Binder.getCallingUid());
14826
14827        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14828            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14829        }
14830        if (millisecondsToDelay < 0) {
14831            millisecondsToDelay = 0;
14832        }
14833        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14834                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14835            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14836        }
14837
14838        if ((state != null) && !state.timeoutExtended()) {
14839            state.extendTimeout();
14840
14841            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14842            msg.arg1 = id;
14843            msg.obj = response;
14844            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14845        }
14846    }
14847
14848    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14849            int verificationCode, UserHandle user) {
14850        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14851        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14852        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14853        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14854        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14855
14856        mContext.sendBroadcastAsUser(intent, user,
14857                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14858    }
14859
14860    private ComponentName matchComponentForVerifier(String packageName,
14861            List<ResolveInfo> receivers) {
14862        ActivityInfo targetReceiver = null;
14863
14864        final int NR = receivers.size();
14865        for (int i = 0; i < NR; i++) {
14866            final ResolveInfo info = receivers.get(i);
14867            if (info.activityInfo == null) {
14868                continue;
14869            }
14870
14871            if (packageName.equals(info.activityInfo.packageName)) {
14872                targetReceiver = info.activityInfo;
14873                break;
14874            }
14875        }
14876
14877        if (targetReceiver == null) {
14878            return null;
14879        }
14880
14881        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14882    }
14883
14884    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14885            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14886        if (pkgInfo.verifiers.length == 0) {
14887            return null;
14888        }
14889
14890        final int N = pkgInfo.verifiers.length;
14891        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14892        for (int i = 0; i < N; i++) {
14893            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14894
14895            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14896                    receivers);
14897            if (comp == null) {
14898                continue;
14899            }
14900
14901            final int verifierUid = getUidForVerifier(verifierInfo);
14902            if (verifierUid == -1) {
14903                continue;
14904            }
14905
14906            if (DEBUG_VERIFY) {
14907                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14908                        + " with the correct signature");
14909            }
14910            sufficientVerifiers.add(comp);
14911            verificationState.addSufficientVerifier(verifierUid);
14912        }
14913
14914        return sufficientVerifiers;
14915    }
14916
14917    private int getUidForVerifier(VerifierInfo verifierInfo) {
14918        synchronized (mPackages) {
14919            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14920            if (pkg == null) {
14921                return -1;
14922            } else if (pkg.mSignatures.length != 1) {
14923                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14924                        + " has more than one signature; ignoring");
14925                return -1;
14926            }
14927
14928            /*
14929             * If the public key of the package's signature does not match
14930             * our expected public key, then this is a different package and
14931             * we should skip.
14932             */
14933
14934            final byte[] expectedPublicKey;
14935            try {
14936                final Signature verifierSig = pkg.mSignatures[0];
14937                final PublicKey publicKey = verifierSig.getPublicKey();
14938                expectedPublicKey = publicKey.getEncoded();
14939            } catch (CertificateException e) {
14940                return -1;
14941            }
14942
14943            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14944
14945            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14946                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14947                        + " does not have the expected public key; ignoring");
14948                return -1;
14949            }
14950
14951            return pkg.applicationInfo.uid;
14952        }
14953    }
14954
14955    @Override
14956    public void finishPackageInstall(int token, boolean didLaunch) {
14957        enforceSystemOrRoot("Only the system is allowed to finish installs");
14958
14959        if (DEBUG_INSTALL) {
14960            Slog.v(TAG, "BM finishing package install for " + token);
14961        }
14962        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14963
14964        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14965        mHandler.sendMessage(msg);
14966    }
14967
14968    /**
14969     * Get the verification agent timeout.  Used for both the APK verifier and the
14970     * intent filter verifier.
14971     *
14972     * @return verification timeout in milliseconds
14973     */
14974    private long getVerificationTimeout() {
14975        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14976                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14977                DEFAULT_VERIFICATION_TIMEOUT);
14978    }
14979
14980    /**
14981     * Get the default verification agent response code.
14982     *
14983     * @return default verification response code
14984     */
14985    private int getDefaultVerificationResponse(UserHandle user) {
14986        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14987            return PackageManager.VERIFICATION_REJECT;
14988        }
14989        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14990                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14991                DEFAULT_VERIFICATION_RESPONSE);
14992    }
14993
14994    /**
14995     * Check whether or not package verification has been enabled.
14996     *
14997     * @return true if verification should be performed
14998     */
14999    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15000        if (!DEFAULT_VERIFY_ENABLE) {
15001            return false;
15002        }
15003
15004        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15005
15006        // Check if installing from ADB
15007        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15008            // Do not run verification in a test harness environment
15009            if (ActivityManager.isRunningInTestHarness()) {
15010                return false;
15011            }
15012            if (ensureVerifyAppsEnabled) {
15013                return true;
15014            }
15015            // Check if the developer does not want package verification for ADB installs
15016            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15017                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15018                return false;
15019            }
15020        } else {
15021            // only when not installed from ADB, skip verification for instant apps when
15022            // the installer and verifier are the same.
15023            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15024                if (mInstantAppInstallerActivity != null
15025                        && mInstantAppInstallerActivity.packageName.equals(
15026                                mRequiredVerifierPackage)) {
15027                    try {
15028                        mContext.getSystemService(AppOpsManager.class)
15029                                .checkPackage(installerUid, mRequiredVerifierPackage);
15030                        if (DEBUG_VERIFY) {
15031                            Slog.i(TAG, "disable verification for instant app");
15032                        }
15033                        return false;
15034                    } catch (SecurityException ignore) { }
15035                }
15036            }
15037        }
15038
15039        if (ensureVerifyAppsEnabled) {
15040            return true;
15041        }
15042
15043        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15044                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15045    }
15046
15047    @Override
15048    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15049            throws RemoteException {
15050        mContext.enforceCallingOrSelfPermission(
15051                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15052                "Only intentfilter verification agents can verify applications");
15053
15054        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15055        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15056                Binder.getCallingUid(), verificationCode, failedDomains);
15057        msg.arg1 = id;
15058        msg.obj = response;
15059        mHandler.sendMessage(msg);
15060    }
15061
15062    @Override
15063    public int getIntentVerificationStatus(String packageName, int userId) {
15064        final int callingUid = Binder.getCallingUid();
15065        if (getInstantAppPackageName(callingUid) != null) {
15066            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15067        }
15068        synchronized (mPackages) {
15069            final PackageSetting ps = mSettings.mPackages.get(packageName);
15070            if (ps == null
15071                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15072                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15073            }
15074            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15075        }
15076    }
15077
15078    @Override
15079    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15080        mContext.enforceCallingOrSelfPermission(
15081                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15082
15083        boolean result = false;
15084        synchronized (mPackages) {
15085            final PackageSetting ps = mSettings.mPackages.get(packageName);
15086            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15087                return false;
15088            }
15089            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15090        }
15091        if (result) {
15092            scheduleWritePackageRestrictionsLocked(userId);
15093        }
15094        return result;
15095    }
15096
15097    @Override
15098    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15099            String packageName) {
15100        final int callingUid = Binder.getCallingUid();
15101        if (getInstantAppPackageName(callingUid) != null) {
15102            return ParceledListSlice.emptyList();
15103        }
15104        synchronized (mPackages) {
15105            final PackageSetting ps = mSettings.mPackages.get(packageName);
15106            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15107                return ParceledListSlice.emptyList();
15108            }
15109            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15110        }
15111    }
15112
15113    @Override
15114    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15115        if (TextUtils.isEmpty(packageName)) {
15116            return ParceledListSlice.emptyList();
15117        }
15118        final int callingUid = Binder.getCallingUid();
15119        final int callingUserId = UserHandle.getUserId(callingUid);
15120        synchronized (mPackages) {
15121            PackageParser.Package pkg = mPackages.get(packageName);
15122            if (pkg == null || pkg.activities == null) {
15123                return ParceledListSlice.emptyList();
15124            }
15125            if (pkg.mExtras == null) {
15126                return ParceledListSlice.emptyList();
15127            }
15128            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15129            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15130                return ParceledListSlice.emptyList();
15131            }
15132            final int count = pkg.activities.size();
15133            ArrayList<IntentFilter> result = new ArrayList<>();
15134            for (int n=0; n<count; n++) {
15135                PackageParser.Activity activity = pkg.activities.get(n);
15136                if (activity.intents != null && activity.intents.size() > 0) {
15137                    result.addAll(activity.intents);
15138                }
15139            }
15140            return new ParceledListSlice<>(result);
15141        }
15142    }
15143
15144    @Override
15145    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15146        mContext.enforceCallingOrSelfPermission(
15147                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15148
15149        synchronized (mPackages) {
15150            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15151            if (packageName != null) {
15152                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15153                        packageName, userId);
15154            }
15155            return result;
15156        }
15157    }
15158
15159    @Override
15160    public String getDefaultBrowserPackageName(int userId) {
15161        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15162            return null;
15163        }
15164        synchronized (mPackages) {
15165            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15166        }
15167    }
15168
15169    /**
15170     * Get the "allow unknown sources" setting.
15171     *
15172     * @return the current "allow unknown sources" setting
15173     */
15174    private int getUnknownSourcesSettings() {
15175        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15176                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15177                -1);
15178    }
15179
15180    @Override
15181    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15182        final int callingUid = Binder.getCallingUid();
15183        if (getInstantAppPackageName(callingUid) != null) {
15184            return;
15185        }
15186        // writer
15187        synchronized (mPackages) {
15188            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15189            if (targetPackageSetting == null
15190                    || filterAppAccessLPr(
15191                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15192                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15193            }
15194
15195            PackageSetting installerPackageSetting;
15196            if (installerPackageName != null) {
15197                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15198                if (installerPackageSetting == null) {
15199                    throw new IllegalArgumentException("Unknown installer package: "
15200                            + installerPackageName);
15201                }
15202            } else {
15203                installerPackageSetting = null;
15204            }
15205
15206            Signature[] callerSignature;
15207            Object obj = mSettings.getUserIdLPr(callingUid);
15208            if (obj != null) {
15209                if (obj instanceof SharedUserSetting) {
15210                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15211                } else if (obj instanceof PackageSetting) {
15212                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15213                } else {
15214                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15215                }
15216            } else {
15217                throw new SecurityException("Unknown calling UID: " + callingUid);
15218            }
15219
15220            // Verify: can't set installerPackageName to a package that is
15221            // not signed with the same cert as the caller.
15222            if (installerPackageSetting != null) {
15223                if (compareSignatures(callerSignature,
15224                        installerPackageSetting.signatures.mSignatures)
15225                        != PackageManager.SIGNATURE_MATCH) {
15226                    throw new SecurityException(
15227                            "Caller does not have same cert as new installer package "
15228                            + installerPackageName);
15229                }
15230            }
15231
15232            // Verify: if target already has an installer package, it must
15233            // be signed with the same cert as the caller.
15234            if (targetPackageSetting.installerPackageName != null) {
15235                PackageSetting setting = mSettings.mPackages.get(
15236                        targetPackageSetting.installerPackageName);
15237                // If the currently set package isn't valid, then it's always
15238                // okay to change it.
15239                if (setting != null) {
15240                    if (compareSignatures(callerSignature,
15241                            setting.signatures.mSignatures)
15242                            != PackageManager.SIGNATURE_MATCH) {
15243                        throw new SecurityException(
15244                                "Caller does not have same cert as old installer package "
15245                                + targetPackageSetting.installerPackageName);
15246                    }
15247                }
15248            }
15249
15250            // Okay!
15251            targetPackageSetting.installerPackageName = installerPackageName;
15252            if (installerPackageName != null) {
15253                mSettings.mInstallerPackages.add(installerPackageName);
15254            }
15255            scheduleWriteSettingsLocked();
15256        }
15257    }
15258
15259    @Override
15260    public void setApplicationCategoryHint(String packageName, int categoryHint,
15261            String callerPackageName) {
15262        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15263            throw new SecurityException("Instant applications don't have access to this method");
15264        }
15265        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15266                callerPackageName);
15267        synchronized (mPackages) {
15268            PackageSetting ps = mSettings.mPackages.get(packageName);
15269            if (ps == null) {
15270                throw new IllegalArgumentException("Unknown target package " + packageName);
15271            }
15272            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15273                throw new IllegalArgumentException("Unknown target package " + packageName);
15274            }
15275            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15276                throw new IllegalArgumentException("Calling package " + callerPackageName
15277                        + " is not installer for " + packageName);
15278            }
15279
15280            if (ps.categoryHint != categoryHint) {
15281                ps.categoryHint = categoryHint;
15282                scheduleWriteSettingsLocked();
15283            }
15284        }
15285    }
15286
15287    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15288        // Queue up an async operation since the package installation may take a little while.
15289        mHandler.post(new Runnable() {
15290            public void run() {
15291                mHandler.removeCallbacks(this);
15292                 // Result object to be returned
15293                PackageInstalledInfo res = new PackageInstalledInfo();
15294                res.setReturnCode(currentStatus);
15295                res.uid = -1;
15296                res.pkg = null;
15297                res.removedInfo = null;
15298                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15299                    args.doPreInstall(res.returnCode);
15300                    synchronized (mInstallLock) {
15301                        installPackageTracedLI(args, res);
15302                    }
15303                    args.doPostInstall(res.returnCode, res.uid);
15304                }
15305
15306                // A restore should be performed at this point if (a) the install
15307                // succeeded, (b) the operation is not an update, and (c) the new
15308                // package has not opted out of backup participation.
15309                final boolean update = res.removedInfo != null
15310                        && res.removedInfo.removedPackage != null;
15311                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15312                boolean doRestore = !update
15313                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15314
15315                // Set up the post-install work request bookkeeping.  This will be used
15316                // and cleaned up by the post-install event handling regardless of whether
15317                // there's a restore pass performed.  Token values are >= 1.
15318                int token;
15319                if (mNextInstallToken < 0) mNextInstallToken = 1;
15320                token = mNextInstallToken++;
15321
15322                PostInstallData data = new PostInstallData(args, res);
15323                mRunningInstalls.put(token, data);
15324                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15325
15326                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15327                    // Pass responsibility to the Backup Manager.  It will perform a
15328                    // restore if appropriate, then pass responsibility back to the
15329                    // Package Manager to run the post-install observer callbacks
15330                    // and broadcasts.
15331                    IBackupManager bm = IBackupManager.Stub.asInterface(
15332                            ServiceManager.getService(Context.BACKUP_SERVICE));
15333                    if (bm != null) {
15334                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15335                                + " to BM for possible restore");
15336                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15337                        try {
15338                            // TODO: http://b/22388012
15339                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15340                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15341                            } else {
15342                                doRestore = false;
15343                            }
15344                        } catch (RemoteException e) {
15345                            // can't happen; the backup manager is local
15346                        } catch (Exception e) {
15347                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15348                            doRestore = false;
15349                        }
15350                    } else {
15351                        Slog.e(TAG, "Backup Manager not found!");
15352                        doRestore = false;
15353                    }
15354                }
15355
15356                if (!doRestore) {
15357                    // No restore possible, or the Backup Manager was mysteriously not
15358                    // available -- just fire the post-install work request directly.
15359                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15360
15361                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15362
15363                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15364                    mHandler.sendMessage(msg);
15365                }
15366            }
15367        });
15368    }
15369
15370    /**
15371     * Callback from PackageSettings whenever an app is first transitioned out of the
15372     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15373     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15374     * here whether the app is the target of an ongoing install, and only send the
15375     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15376     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15377     * handling.
15378     */
15379    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15380        // Serialize this with the rest of the install-process message chain.  In the
15381        // restore-at-install case, this Runnable will necessarily run before the
15382        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15383        // are coherent.  In the non-restore case, the app has already completed install
15384        // and been launched through some other means, so it is not in a problematic
15385        // state for observers to see the FIRST_LAUNCH signal.
15386        mHandler.post(new Runnable() {
15387            @Override
15388            public void run() {
15389                for (int i = 0; i < mRunningInstalls.size(); i++) {
15390                    final PostInstallData data = mRunningInstalls.valueAt(i);
15391                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15392                        continue;
15393                    }
15394                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15395                        // right package; but is it for the right user?
15396                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15397                            if (userId == data.res.newUsers[uIndex]) {
15398                                if (DEBUG_BACKUP) {
15399                                    Slog.i(TAG, "Package " + pkgName
15400                                            + " being restored so deferring FIRST_LAUNCH");
15401                                }
15402                                return;
15403                            }
15404                        }
15405                    }
15406                }
15407                // didn't find it, so not being restored
15408                if (DEBUG_BACKUP) {
15409                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15410                }
15411                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15412            }
15413        });
15414    }
15415
15416    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15417        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15418                installerPkg, null, userIds);
15419    }
15420
15421    private abstract class HandlerParams {
15422        private static final int MAX_RETRIES = 4;
15423
15424        /**
15425         * Number of times startCopy() has been attempted and had a non-fatal
15426         * error.
15427         */
15428        private int mRetries = 0;
15429
15430        /** User handle for the user requesting the information or installation. */
15431        private final UserHandle mUser;
15432        String traceMethod;
15433        int traceCookie;
15434
15435        HandlerParams(UserHandle user) {
15436            mUser = user;
15437        }
15438
15439        UserHandle getUser() {
15440            return mUser;
15441        }
15442
15443        HandlerParams setTraceMethod(String traceMethod) {
15444            this.traceMethod = traceMethod;
15445            return this;
15446        }
15447
15448        HandlerParams setTraceCookie(int traceCookie) {
15449            this.traceCookie = traceCookie;
15450            return this;
15451        }
15452
15453        final boolean startCopy() {
15454            boolean res;
15455            try {
15456                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15457
15458                if (++mRetries > MAX_RETRIES) {
15459                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15460                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15461                    handleServiceError();
15462                    return false;
15463                } else {
15464                    handleStartCopy();
15465                    res = true;
15466                }
15467            } catch (RemoteException e) {
15468                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15469                mHandler.sendEmptyMessage(MCS_RECONNECT);
15470                res = false;
15471            }
15472            handleReturnCode();
15473            return res;
15474        }
15475
15476        final void serviceError() {
15477            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15478            handleServiceError();
15479            handleReturnCode();
15480        }
15481
15482        abstract void handleStartCopy() throws RemoteException;
15483        abstract void handleServiceError();
15484        abstract void handleReturnCode();
15485    }
15486
15487    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15488        for (File path : paths) {
15489            try {
15490                mcs.clearDirectory(path.getAbsolutePath());
15491            } catch (RemoteException e) {
15492            }
15493        }
15494    }
15495
15496    static class OriginInfo {
15497        /**
15498         * Location where install is coming from, before it has been
15499         * copied/renamed into place. This could be a single monolithic APK
15500         * file, or a cluster directory. This location may be untrusted.
15501         */
15502        final File file;
15503        final String cid;
15504
15505        /**
15506         * Flag indicating that {@link #file} or {@link #cid} has already been
15507         * staged, meaning downstream users don't need to defensively copy the
15508         * contents.
15509         */
15510        final boolean staged;
15511
15512        /**
15513         * Flag indicating that {@link #file} or {@link #cid} is an already
15514         * installed app that is being moved.
15515         */
15516        final boolean existing;
15517
15518        final String resolvedPath;
15519        final File resolvedFile;
15520
15521        static OriginInfo fromNothing() {
15522            return new OriginInfo(null, null, false, false);
15523        }
15524
15525        static OriginInfo fromUntrustedFile(File file) {
15526            return new OriginInfo(file, null, false, false);
15527        }
15528
15529        static OriginInfo fromExistingFile(File file) {
15530            return new OriginInfo(file, null, false, true);
15531        }
15532
15533        static OriginInfo fromStagedFile(File file) {
15534            return new OriginInfo(file, null, true, false);
15535        }
15536
15537        static OriginInfo fromStagedContainer(String cid) {
15538            return new OriginInfo(null, cid, true, false);
15539        }
15540
15541        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15542            this.file = file;
15543            this.cid = cid;
15544            this.staged = staged;
15545            this.existing = existing;
15546
15547            if (cid != null) {
15548                resolvedPath = PackageHelper.getSdDir(cid);
15549                resolvedFile = new File(resolvedPath);
15550            } else if (file != null) {
15551                resolvedPath = file.getAbsolutePath();
15552                resolvedFile = file;
15553            } else {
15554                resolvedPath = null;
15555                resolvedFile = null;
15556            }
15557        }
15558    }
15559
15560    static class MoveInfo {
15561        final int moveId;
15562        final String fromUuid;
15563        final String toUuid;
15564        final String packageName;
15565        final String dataAppName;
15566        final int appId;
15567        final String seinfo;
15568        final int targetSdkVersion;
15569
15570        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15571                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15572            this.moveId = moveId;
15573            this.fromUuid = fromUuid;
15574            this.toUuid = toUuid;
15575            this.packageName = packageName;
15576            this.dataAppName = dataAppName;
15577            this.appId = appId;
15578            this.seinfo = seinfo;
15579            this.targetSdkVersion = targetSdkVersion;
15580        }
15581    }
15582
15583    static class VerificationInfo {
15584        /** A constant used to indicate that a uid value is not present. */
15585        public static final int NO_UID = -1;
15586
15587        /** URI referencing where the package was downloaded from. */
15588        final Uri originatingUri;
15589
15590        /** HTTP referrer URI associated with the originatingURI. */
15591        final Uri referrer;
15592
15593        /** UID of the application that the install request originated from. */
15594        final int originatingUid;
15595
15596        /** UID of application requesting the install */
15597        final int installerUid;
15598
15599        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15600            this.originatingUri = originatingUri;
15601            this.referrer = referrer;
15602            this.originatingUid = originatingUid;
15603            this.installerUid = installerUid;
15604        }
15605    }
15606
15607    class InstallParams extends HandlerParams {
15608        final OriginInfo origin;
15609        final MoveInfo move;
15610        final IPackageInstallObserver2 observer;
15611        int installFlags;
15612        final String installerPackageName;
15613        final String volumeUuid;
15614        private InstallArgs mArgs;
15615        private int mRet;
15616        final String packageAbiOverride;
15617        final String[] grantedRuntimePermissions;
15618        final VerificationInfo verificationInfo;
15619        final Certificate[][] certificates;
15620        final int installReason;
15621
15622        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15623                int installFlags, String installerPackageName, String volumeUuid,
15624                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15625                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15626            super(user);
15627            this.origin = origin;
15628            this.move = move;
15629            this.observer = observer;
15630            this.installFlags = installFlags;
15631            this.installerPackageName = installerPackageName;
15632            this.volumeUuid = volumeUuid;
15633            this.verificationInfo = verificationInfo;
15634            this.packageAbiOverride = packageAbiOverride;
15635            this.grantedRuntimePermissions = grantedPermissions;
15636            this.certificates = certificates;
15637            this.installReason = installReason;
15638        }
15639
15640        @Override
15641        public String toString() {
15642            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15643                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15644        }
15645
15646        private int installLocationPolicy(PackageInfoLite pkgLite) {
15647            String packageName = pkgLite.packageName;
15648            int installLocation = pkgLite.installLocation;
15649            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15650            // reader
15651            synchronized (mPackages) {
15652                // Currently installed package which the new package is attempting to replace or
15653                // null if no such package is installed.
15654                PackageParser.Package installedPkg = mPackages.get(packageName);
15655                // Package which currently owns the data which the new package will own if installed.
15656                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15657                // will be null whereas dataOwnerPkg will contain information about the package
15658                // which was uninstalled while keeping its data.
15659                PackageParser.Package dataOwnerPkg = installedPkg;
15660                if (dataOwnerPkg  == null) {
15661                    PackageSetting ps = mSettings.mPackages.get(packageName);
15662                    if (ps != null) {
15663                        dataOwnerPkg = ps.pkg;
15664                    }
15665                }
15666
15667                if (dataOwnerPkg != null) {
15668                    // If installed, the package will get access to data left on the device by its
15669                    // predecessor. As a security measure, this is permited only if this is not a
15670                    // version downgrade or if the predecessor package is marked as debuggable and
15671                    // a downgrade is explicitly requested.
15672                    //
15673                    // On debuggable platform builds, downgrades are permitted even for
15674                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15675                    // not offer security guarantees and thus it's OK to disable some security
15676                    // mechanisms to make debugging/testing easier on those builds. However, even on
15677                    // debuggable builds downgrades of packages are permitted only if requested via
15678                    // installFlags. This is because we aim to keep the behavior of debuggable
15679                    // platform builds as close as possible to the behavior of non-debuggable
15680                    // platform builds.
15681                    final boolean downgradeRequested =
15682                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15683                    final boolean packageDebuggable =
15684                                (dataOwnerPkg.applicationInfo.flags
15685                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15686                    final boolean downgradePermitted =
15687                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15688                    if (!downgradePermitted) {
15689                        try {
15690                            checkDowngrade(dataOwnerPkg, pkgLite);
15691                        } catch (PackageManagerException e) {
15692                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15693                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15694                        }
15695                    }
15696                }
15697
15698                if (installedPkg != null) {
15699                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15700                        // Check for updated system application.
15701                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15702                            if (onSd) {
15703                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15704                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15705                            }
15706                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15707                        } else {
15708                            if (onSd) {
15709                                // Install flag overrides everything.
15710                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15711                            }
15712                            // If current upgrade specifies particular preference
15713                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15714                                // Application explicitly specified internal.
15715                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15716                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15717                                // App explictly prefers external. Let policy decide
15718                            } else {
15719                                // Prefer previous location
15720                                if (isExternal(installedPkg)) {
15721                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15722                                }
15723                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15724                            }
15725                        }
15726                    } else {
15727                        // Invalid install. Return error code
15728                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15729                    }
15730                }
15731            }
15732            // All the special cases have been taken care of.
15733            // Return result based on recommended install location.
15734            if (onSd) {
15735                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15736            }
15737            return pkgLite.recommendedInstallLocation;
15738        }
15739
15740        /*
15741         * Invoke remote method to get package information and install
15742         * location values. Override install location based on default
15743         * policy if needed and then create install arguments based
15744         * on the install location.
15745         */
15746        public void handleStartCopy() throws RemoteException {
15747            int ret = PackageManager.INSTALL_SUCCEEDED;
15748
15749            // If we're already staged, we've firmly committed to an install location
15750            if (origin.staged) {
15751                if (origin.file != null) {
15752                    installFlags |= PackageManager.INSTALL_INTERNAL;
15753                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15754                } else if (origin.cid != null) {
15755                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15756                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15757                } else {
15758                    throw new IllegalStateException("Invalid stage location");
15759                }
15760            }
15761
15762            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15763            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15764            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15765            PackageInfoLite pkgLite = null;
15766
15767            if (onInt && onSd) {
15768                // Check if both bits are set.
15769                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15770                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15771            } else if (onSd && ephemeral) {
15772                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15773                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15774            } else {
15775                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15776                        packageAbiOverride);
15777
15778                if (DEBUG_EPHEMERAL && ephemeral) {
15779                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15780                }
15781
15782                /*
15783                 * If we have too little free space, try to free cache
15784                 * before giving up.
15785                 */
15786                if (!origin.staged && pkgLite.recommendedInstallLocation
15787                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15788                    // TODO: focus freeing disk space on the target device
15789                    final StorageManager storage = StorageManager.from(mContext);
15790                    final long lowThreshold = storage.getStorageLowBytes(
15791                            Environment.getDataDirectory());
15792
15793                    final long sizeBytes = mContainerService.calculateInstalledSize(
15794                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15795
15796                    try {
15797                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15798                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15799                                installFlags, packageAbiOverride);
15800                    } catch (InstallerException e) {
15801                        Slog.w(TAG, "Failed to free cache", e);
15802                    }
15803
15804                    /*
15805                     * The cache free must have deleted the file we
15806                     * downloaded to install.
15807                     *
15808                     * TODO: fix the "freeCache" call to not delete
15809                     *       the file we care about.
15810                     */
15811                    if (pkgLite.recommendedInstallLocation
15812                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15813                        pkgLite.recommendedInstallLocation
15814                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15815                    }
15816                }
15817            }
15818
15819            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15820                int loc = pkgLite.recommendedInstallLocation;
15821                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15822                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15823                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15824                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15825                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15826                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15827                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15828                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15829                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15830                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15831                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15832                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15833                } else {
15834                    // Override with defaults if needed.
15835                    loc = installLocationPolicy(pkgLite);
15836                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15837                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15838                    } else if (!onSd && !onInt) {
15839                        // Override install location with flags
15840                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15841                            // Set the flag to install on external media.
15842                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15843                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15844                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15845                            if (DEBUG_EPHEMERAL) {
15846                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15847                            }
15848                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15849                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15850                                    |PackageManager.INSTALL_INTERNAL);
15851                        } else {
15852                            // Make sure the flag for installing on external
15853                            // media is unset
15854                            installFlags |= PackageManager.INSTALL_INTERNAL;
15855                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15856                        }
15857                    }
15858                }
15859            }
15860
15861            final InstallArgs args = createInstallArgs(this);
15862            mArgs = args;
15863
15864            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15865                // TODO: http://b/22976637
15866                // Apps installed for "all" users use the device owner to verify the app
15867                UserHandle verifierUser = getUser();
15868                if (verifierUser == UserHandle.ALL) {
15869                    verifierUser = UserHandle.SYSTEM;
15870                }
15871
15872                /*
15873                 * Determine if we have any installed package verifiers. If we
15874                 * do, then we'll defer to them to verify the packages.
15875                 */
15876                final int requiredUid = mRequiredVerifierPackage == null ? -1
15877                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15878                                verifierUser.getIdentifier());
15879                final int installerUid =
15880                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15881                if (!origin.existing && requiredUid != -1
15882                        && isVerificationEnabled(
15883                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15884                    final Intent verification = new Intent(
15885                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15886                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15887                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15888                            PACKAGE_MIME_TYPE);
15889                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15890
15891                    // Query all live verifiers based on current user state
15892                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15893                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15894
15895                    if (DEBUG_VERIFY) {
15896                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15897                                + verification.toString() + " with " + pkgLite.verifiers.length
15898                                + " optional verifiers");
15899                    }
15900
15901                    final int verificationId = mPendingVerificationToken++;
15902
15903                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15904
15905                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15906                            installerPackageName);
15907
15908                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15909                            installFlags);
15910
15911                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15912                            pkgLite.packageName);
15913
15914                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15915                            pkgLite.versionCode);
15916
15917                    if (verificationInfo != null) {
15918                        if (verificationInfo.originatingUri != null) {
15919                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15920                                    verificationInfo.originatingUri);
15921                        }
15922                        if (verificationInfo.referrer != null) {
15923                            verification.putExtra(Intent.EXTRA_REFERRER,
15924                                    verificationInfo.referrer);
15925                        }
15926                        if (verificationInfo.originatingUid >= 0) {
15927                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15928                                    verificationInfo.originatingUid);
15929                        }
15930                        if (verificationInfo.installerUid >= 0) {
15931                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15932                                    verificationInfo.installerUid);
15933                        }
15934                    }
15935
15936                    final PackageVerificationState verificationState = new PackageVerificationState(
15937                            requiredUid, args);
15938
15939                    mPendingVerification.append(verificationId, verificationState);
15940
15941                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15942                            receivers, verificationState);
15943
15944                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15945                    final long idleDuration = getVerificationTimeout();
15946
15947                    /*
15948                     * If any sufficient verifiers were listed in the package
15949                     * manifest, attempt to ask them.
15950                     */
15951                    if (sufficientVerifiers != null) {
15952                        final int N = sufficientVerifiers.size();
15953                        if (N == 0) {
15954                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15955                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15956                        } else {
15957                            for (int i = 0; i < N; i++) {
15958                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15959                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15960                                        verifierComponent.getPackageName(), idleDuration,
15961                                        verifierUser.getIdentifier(), false, "package verifier");
15962
15963                                final Intent sufficientIntent = new Intent(verification);
15964                                sufficientIntent.setComponent(verifierComponent);
15965                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15966                            }
15967                        }
15968                    }
15969
15970                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15971                            mRequiredVerifierPackage, receivers);
15972                    if (ret == PackageManager.INSTALL_SUCCEEDED
15973                            && mRequiredVerifierPackage != null) {
15974                        Trace.asyncTraceBegin(
15975                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15976                        /*
15977                         * Send the intent to the required verification agent,
15978                         * but only start the verification timeout after the
15979                         * target BroadcastReceivers have run.
15980                         */
15981                        verification.setComponent(requiredVerifierComponent);
15982                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15983                                mRequiredVerifierPackage, idleDuration,
15984                                verifierUser.getIdentifier(), false, "package verifier");
15985                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15986                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15987                                new BroadcastReceiver() {
15988                                    @Override
15989                                    public void onReceive(Context context, Intent intent) {
15990                                        final Message msg = mHandler
15991                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15992                                        msg.arg1 = verificationId;
15993                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15994                                    }
15995                                }, null, 0, null, null);
15996
15997                        /*
15998                         * We don't want the copy to proceed until verification
15999                         * succeeds, so null out this field.
16000                         */
16001                        mArgs = null;
16002                    }
16003                } else {
16004                    /*
16005                     * No package verification is enabled, so immediately start
16006                     * the remote call to initiate copy using temporary file.
16007                     */
16008                    ret = args.copyApk(mContainerService, true);
16009                }
16010            }
16011
16012            mRet = ret;
16013        }
16014
16015        @Override
16016        void handleReturnCode() {
16017            // If mArgs is null, then MCS couldn't be reached. When it
16018            // reconnects, it will try again to install. At that point, this
16019            // will succeed.
16020            if (mArgs != null) {
16021                processPendingInstall(mArgs, mRet);
16022            }
16023        }
16024
16025        @Override
16026        void handleServiceError() {
16027            mArgs = createInstallArgs(this);
16028            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16029        }
16030
16031        public boolean isForwardLocked() {
16032            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16033        }
16034    }
16035
16036    /**
16037     * Used during creation of InstallArgs
16038     *
16039     * @param installFlags package installation flags
16040     * @return true if should be installed on external storage
16041     */
16042    private static boolean installOnExternalAsec(int installFlags) {
16043        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16044            return false;
16045        }
16046        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16047            return true;
16048        }
16049        return false;
16050    }
16051
16052    /**
16053     * Used during creation of InstallArgs
16054     *
16055     * @param installFlags package installation flags
16056     * @return true if should be installed as forward locked
16057     */
16058    private static boolean installForwardLocked(int installFlags) {
16059        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16060    }
16061
16062    private InstallArgs createInstallArgs(InstallParams params) {
16063        if (params.move != null) {
16064            return new MoveInstallArgs(params);
16065        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16066            return new AsecInstallArgs(params);
16067        } else {
16068            return new FileInstallArgs(params);
16069        }
16070    }
16071
16072    /**
16073     * Create args that describe an existing installed package. Typically used
16074     * when cleaning up old installs, or used as a move source.
16075     */
16076    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16077            String resourcePath, String[] instructionSets) {
16078        final boolean isInAsec;
16079        if (installOnExternalAsec(installFlags)) {
16080            /* Apps on SD card are always in ASEC containers. */
16081            isInAsec = true;
16082        } else if (installForwardLocked(installFlags)
16083                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16084            /*
16085             * Forward-locked apps are only in ASEC containers if they're the
16086             * new style
16087             */
16088            isInAsec = true;
16089        } else {
16090            isInAsec = false;
16091        }
16092
16093        if (isInAsec) {
16094            return new AsecInstallArgs(codePath, instructionSets,
16095                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16096        } else {
16097            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16098        }
16099    }
16100
16101    static abstract class InstallArgs {
16102        /** @see InstallParams#origin */
16103        final OriginInfo origin;
16104        /** @see InstallParams#move */
16105        final MoveInfo move;
16106
16107        final IPackageInstallObserver2 observer;
16108        // Always refers to PackageManager flags only
16109        final int installFlags;
16110        final String installerPackageName;
16111        final String volumeUuid;
16112        final UserHandle user;
16113        final String abiOverride;
16114        final String[] installGrantPermissions;
16115        /** If non-null, drop an async trace when the install completes */
16116        final String traceMethod;
16117        final int traceCookie;
16118        final Certificate[][] certificates;
16119        final int installReason;
16120
16121        // The list of instruction sets supported by this app. This is currently
16122        // only used during the rmdex() phase to clean up resources. We can get rid of this
16123        // if we move dex files under the common app path.
16124        /* nullable */ String[] instructionSets;
16125
16126        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16127                int installFlags, String installerPackageName, String volumeUuid,
16128                UserHandle user, String[] instructionSets,
16129                String abiOverride, String[] installGrantPermissions,
16130                String traceMethod, int traceCookie, Certificate[][] certificates,
16131                int installReason) {
16132            this.origin = origin;
16133            this.move = move;
16134            this.installFlags = installFlags;
16135            this.observer = observer;
16136            this.installerPackageName = installerPackageName;
16137            this.volumeUuid = volumeUuid;
16138            this.user = user;
16139            this.instructionSets = instructionSets;
16140            this.abiOverride = abiOverride;
16141            this.installGrantPermissions = installGrantPermissions;
16142            this.traceMethod = traceMethod;
16143            this.traceCookie = traceCookie;
16144            this.certificates = certificates;
16145            this.installReason = installReason;
16146        }
16147
16148        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16149        abstract int doPreInstall(int status);
16150
16151        /**
16152         * Rename package into final resting place. All paths on the given
16153         * scanned package should be updated to reflect the rename.
16154         */
16155        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16156        abstract int doPostInstall(int status, int uid);
16157
16158        /** @see PackageSettingBase#codePathString */
16159        abstract String getCodePath();
16160        /** @see PackageSettingBase#resourcePathString */
16161        abstract String getResourcePath();
16162
16163        // Need installer lock especially for dex file removal.
16164        abstract void cleanUpResourcesLI();
16165        abstract boolean doPostDeleteLI(boolean delete);
16166
16167        /**
16168         * Called before the source arguments are copied. This is used mostly
16169         * for MoveParams when it needs to read the source file to put it in the
16170         * destination.
16171         */
16172        int doPreCopy() {
16173            return PackageManager.INSTALL_SUCCEEDED;
16174        }
16175
16176        /**
16177         * Called after the source arguments are copied. This is used mostly for
16178         * MoveParams when it needs to read the source file to put it in the
16179         * destination.
16180         */
16181        int doPostCopy(int uid) {
16182            return PackageManager.INSTALL_SUCCEEDED;
16183        }
16184
16185        protected boolean isFwdLocked() {
16186            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16187        }
16188
16189        protected boolean isExternalAsec() {
16190            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16191        }
16192
16193        protected boolean isEphemeral() {
16194            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16195        }
16196
16197        UserHandle getUser() {
16198            return user;
16199        }
16200    }
16201
16202    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16203        if (!allCodePaths.isEmpty()) {
16204            if (instructionSets == null) {
16205                throw new IllegalStateException("instructionSet == null");
16206            }
16207            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16208            for (String codePath : allCodePaths) {
16209                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16210                    try {
16211                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16212                    } catch (InstallerException ignored) {
16213                    }
16214                }
16215            }
16216        }
16217    }
16218
16219    /**
16220     * Logic to handle installation of non-ASEC applications, including copying
16221     * and renaming logic.
16222     */
16223    class FileInstallArgs extends InstallArgs {
16224        private File codeFile;
16225        private File resourceFile;
16226
16227        // Example topology:
16228        // /data/app/com.example/base.apk
16229        // /data/app/com.example/split_foo.apk
16230        // /data/app/com.example/lib/arm/libfoo.so
16231        // /data/app/com.example/lib/arm64/libfoo.so
16232        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16233
16234        /** New install */
16235        FileInstallArgs(InstallParams params) {
16236            super(params.origin, params.move, params.observer, params.installFlags,
16237                    params.installerPackageName, params.volumeUuid,
16238                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16239                    params.grantedRuntimePermissions,
16240                    params.traceMethod, params.traceCookie, params.certificates,
16241                    params.installReason);
16242            if (isFwdLocked()) {
16243                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16244            }
16245        }
16246
16247        /** Existing install */
16248        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16249            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16250                    null, null, null, 0, null /*certificates*/,
16251                    PackageManager.INSTALL_REASON_UNKNOWN);
16252            this.codeFile = (codePath != null) ? new File(codePath) : null;
16253            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16254        }
16255
16256        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16257            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16258            try {
16259                return doCopyApk(imcs, temp);
16260            } finally {
16261                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16262            }
16263        }
16264
16265        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16266            if (origin.staged) {
16267                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16268                codeFile = origin.file;
16269                resourceFile = origin.file;
16270                return PackageManager.INSTALL_SUCCEEDED;
16271            }
16272
16273            try {
16274                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16275                final File tempDir =
16276                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16277                codeFile = tempDir;
16278                resourceFile = tempDir;
16279            } catch (IOException e) {
16280                Slog.w(TAG, "Failed to create copy file: " + e);
16281                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16282            }
16283
16284            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16285                @Override
16286                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16287                    if (!FileUtils.isValidExtFilename(name)) {
16288                        throw new IllegalArgumentException("Invalid filename: " + name);
16289                    }
16290                    try {
16291                        final File file = new File(codeFile, name);
16292                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16293                                O_RDWR | O_CREAT, 0644);
16294                        Os.chmod(file.getAbsolutePath(), 0644);
16295                        return new ParcelFileDescriptor(fd);
16296                    } catch (ErrnoException e) {
16297                        throw new RemoteException("Failed to open: " + e.getMessage());
16298                    }
16299                }
16300            };
16301
16302            int ret = PackageManager.INSTALL_SUCCEEDED;
16303            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16304            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16305                Slog.e(TAG, "Failed to copy package");
16306                return ret;
16307            }
16308
16309            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16310            NativeLibraryHelper.Handle handle = null;
16311            try {
16312                handle = NativeLibraryHelper.Handle.create(codeFile);
16313                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16314                        abiOverride);
16315            } catch (IOException e) {
16316                Slog.e(TAG, "Copying native libraries failed", e);
16317                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16318            } finally {
16319                IoUtils.closeQuietly(handle);
16320            }
16321
16322            return ret;
16323        }
16324
16325        int doPreInstall(int status) {
16326            if (status != PackageManager.INSTALL_SUCCEEDED) {
16327                cleanUp();
16328            }
16329            return status;
16330        }
16331
16332        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16333            if (status != PackageManager.INSTALL_SUCCEEDED) {
16334                cleanUp();
16335                return false;
16336            }
16337
16338            final File targetDir = codeFile.getParentFile();
16339            final File beforeCodeFile = codeFile;
16340            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16341
16342            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16343            try {
16344                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16345            } catch (ErrnoException e) {
16346                Slog.w(TAG, "Failed to rename", e);
16347                return false;
16348            }
16349
16350            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16351                Slog.w(TAG, "Failed to restorecon");
16352                return false;
16353            }
16354
16355            // Reflect the rename internally
16356            codeFile = afterCodeFile;
16357            resourceFile = afterCodeFile;
16358
16359            // Reflect the rename in scanned details
16360            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16361            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16362                    afterCodeFile, pkg.baseCodePath));
16363            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16364                    afterCodeFile, pkg.splitCodePaths));
16365
16366            // Reflect the rename in app info
16367            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16368            pkg.setApplicationInfoCodePath(pkg.codePath);
16369            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16370            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16371            pkg.setApplicationInfoResourcePath(pkg.codePath);
16372            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16373            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16374
16375            return true;
16376        }
16377
16378        int doPostInstall(int status, int uid) {
16379            if (status != PackageManager.INSTALL_SUCCEEDED) {
16380                cleanUp();
16381            }
16382            return status;
16383        }
16384
16385        @Override
16386        String getCodePath() {
16387            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16388        }
16389
16390        @Override
16391        String getResourcePath() {
16392            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16393        }
16394
16395        private boolean cleanUp() {
16396            if (codeFile == null || !codeFile.exists()) {
16397                return false;
16398            }
16399
16400            removeCodePathLI(codeFile);
16401
16402            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16403                resourceFile.delete();
16404            }
16405
16406            return true;
16407        }
16408
16409        void cleanUpResourcesLI() {
16410            // Try enumerating all code paths before deleting
16411            List<String> allCodePaths = Collections.EMPTY_LIST;
16412            if (codeFile != null && codeFile.exists()) {
16413                try {
16414                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16415                    allCodePaths = pkg.getAllCodePaths();
16416                } catch (PackageParserException e) {
16417                    // Ignored; we tried our best
16418                }
16419            }
16420
16421            cleanUp();
16422            removeDexFiles(allCodePaths, instructionSets);
16423        }
16424
16425        boolean doPostDeleteLI(boolean delete) {
16426            // XXX err, shouldn't we respect the delete flag?
16427            cleanUpResourcesLI();
16428            return true;
16429        }
16430    }
16431
16432    private boolean isAsecExternal(String cid) {
16433        final String asecPath = PackageHelper.getSdFilesystem(cid);
16434        return !asecPath.startsWith(mAsecInternalPath);
16435    }
16436
16437    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16438            PackageManagerException {
16439        if (copyRet < 0) {
16440            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16441                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16442                throw new PackageManagerException(copyRet, message);
16443            }
16444        }
16445    }
16446
16447    /**
16448     * Extract the StorageManagerService "container ID" from the full code path of an
16449     * .apk.
16450     */
16451    static String cidFromCodePath(String fullCodePath) {
16452        int eidx = fullCodePath.lastIndexOf("/");
16453        String subStr1 = fullCodePath.substring(0, eidx);
16454        int sidx = subStr1.lastIndexOf("/");
16455        return subStr1.substring(sidx+1, eidx);
16456    }
16457
16458    /**
16459     * Logic to handle installation of ASEC applications, including copying and
16460     * renaming logic.
16461     */
16462    class AsecInstallArgs extends InstallArgs {
16463        static final String RES_FILE_NAME = "pkg.apk";
16464        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16465
16466        String cid;
16467        String packagePath;
16468        String resourcePath;
16469
16470        /** New install */
16471        AsecInstallArgs(InstallParams params) {
16472            super(params.origin, params.move, params.observer, params.installFlags,
16473                    params.installerPackageName, params.volumeUuid,
16474                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16475                    params.grantedRuntimePermissions,
16476                    params.traceMethod, params.traceCookie, params.certificates,
16477                    params.installReason);
16478        }
16479
16480        /** Existing install */
16481        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16482                        boolean isExternal, boolean isForwardLocked) {
16483            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16484                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16485                    instructionSets, null, null, null, 0, null /*certificates*/,
16486                    PackageManager.INSTALL_REASON_UNKNOWN);
16487            // Hackily pretend we're still looking at a full code path
16488            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16489                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16490            }
16491
16492            // Extract cid from fullCodePath
16493            int eidx = fullCodePath.lastIndexOf("/");
16494            String subStr1 = fullCodePath.substring(0, eidx);
16495            int sidx = subStr1.lastIndexOf("/");
16496            cid = subStr1.substring(sidx+1, eidx);
16497            setMountPath(subStr1);
16498        }
16499
16500        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16501            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16502                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16503                    instructionSets, null, null, null, 0, null /*certificates*/,
16504                    PackageManager.INSTALL_REASON_UNKNOWN);
16505            this.cid = cid;
16506            setMountPath(PackageHelper.getSdDir(cid));
16507        }
16508
16509        void createCopyFile() {
16510            cid = mInstallerService.allocateExternalStageCidLegacy();
16511        }
16512
16513        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16514            if (origin.staged && origin.cid != null) {
16515                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16516                cid = origin.cid;
16517                setMountPath(PackageHelper.getSdDir(cid));
16518                return PackageManager.INSTALL_SUCCEEDED;
16519            }
16520
16521            if (temp) {
16522                createCopyFile();
16523            } else {
16524                /*
16525                 * Pre-emptively destroy the container since it's destroyed if
16526                 * copying fails due to it existing anyway.
16527                 */
16528                PackageHelper.destroySdDir(cid);
16529            }
16530
16531            final String newMountPath = imcs.copyPackageToContainer(
16532                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16533                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16534
16535            if (newMountPath != null) {
16536                setMountPath(newMountPath);
16537                return PackageManager.INSTALL_SUCCEEDED;
16538            } else {
16539                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16540            }
16541        }
16542
16543        @Override
16544        String getCodePath() {
16545            return packagePath;
16546        }
16547
16548        @Override
16549        String getResourcePath() {
16550            return resourcePath;
16551        }
16552
16553        int doPreInstall(int status) {
16554            if (status != PackageManager.INSTALL_SUCCEEDED) {
16555                // Destroy container
16556                PackageHelper.destroySdDir(cid);
16557            } else {
16558                boolean mounted = PackageHelper.isContainerMounted(cid);
16559                if (!mounted) {
16560                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16561                            Process.SYSTEM_UID);
16562                    if (newMountPath != null) {
16563                        setMountPath(newMountPath);
16564                    } else {
16565                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16566                    }
16567                }
16568            }
16569            return status;
16570        }
16571
16572        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16573            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16574            String newMountPath = null;
16575            if (PackageHelper.isContainerMounted(cid)) {
16576                // Unmount the container
16577                if (!PackageHelper.unMountSdDir(cid)) {
16578                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16579                    return false;
16580                }
16581            }
16582            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16583                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16584                        " which might be stale. Will try to clean up.");
16585                // Clean up the stale container and proceed to recreate.
16586                if (!PackageHelper.destroySdDir(newCacheId)) {
16587                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16588                    return false;
16589                }
16590                // Successfully cleaned up stale container. Try to rename again.
16591                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16592                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16593                            + " inspite of cleaning it up.");
16594                    return false;
16595                }
16596            }
16597            if (!PackageHelper.isContainerMounted(newCacheId)) {
16598                Slog.w(TAG, "Mounting container " + newCacheId);
16599                newMountPath = PackageHelper.mountSdDir(newCacheId,
16600                        getEncryptKey(), Process.SYSTEM_UID);
16601            } else {
16602                newMountPath = PackageHelper.getSdDir(newCacheId);
16603            }
16604            if (newMountPath == null) {
16605                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16606                return false;
16607            }
16608            Log.i(TAG, "Succesfully renamed " + cid +
16609                    " to " + newCacheId +
16610                    " at new path: " + newMountPath);
16611            cid = newCacheId;
16612
16613            final File beforeCodeFile = new File(packagePath);
16614            setMountPath(newMountPath);
16615            final File afterCodeFile = new File(packagePath);
16616
16617            // Reflect the rename in scanned details
16618            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16619            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16620                    afterCodeFile, pkg.baseCodePath));
16621            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16622                    afterCodeFile, pkg.splitCodePaths));
16623
16624            // Reflect the rename in app info
16625            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16626            pkg.setApplicationInfoCodePath(pkg.codePath);
16627            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16628            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16629            pkg.setApplicationInfoResourcePath(pkg.codePath);
16630            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16631            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16632
16633            return true;
16634        }
16635
16636        private void setMountPath(String mountPath) {
16637            final File mountFile = new File(mountPath);
16638
16639            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16640            if (monolithicFile.exists()) {
16641                packagePath = monolithicFile.getAbsolutePath();
16642                if (isFwdLocked()) {
16643                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16644                } else {
16645                    resourcePath = packagePath;
16646                }
16647            } else {
16648                packagePath = mountFile.getAbsolutePath();
16649                resourcePath = packagePath;
16650            }
16651        }
16652
16653        int doPostInstall(int status, int uid) {
16654            if (status != PackageManager.INSTALL_SUCCEEDED) {
16655                cleanUp();
16656            } else {
16657                final int groupOwner;
16658                final String protectedFile;
16659                if (isFwdLocked()) {
16660                    groupOwner = UserHandle.getSharedAppGid(uid);
16661                    protectedFile = RES_FILE_NAME;
16662                } else {
16663                    groupOwner = -1;
16664                    protectedFile = null;
16665                }
16666
16667                if (uid < Process.FIRST_APPLICATION_UID
16668                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16669                    Slog.e(TAG, "Failed to finalize " + cid);
16670                    PackageHelper.destroySdDir(cid);
16671                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16672                }
16673
16674                boolean mounted = PackageHelper.isContainerMounted(cid);
16675                if (!mounted) {
16676                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16677                }
16678            }
16679            return status;
16680        }
16681
16682        private void cleanUp() {
16683            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16684
16685            // Destroy secure container
16686            PackageHelper.destroySdDir(cid);
16687        }
16688
16689        private List<String> getAllCodePaths() {
16690            final File codeFile = new File(getCodePath());
16691            if (codeFile != null && codeFile.exists()) {
16692                try {
16693                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16694                    return pkg.getAllCodePaths();
16695                } catch (PackageParserException e) {
16696                    // Ignored; we tried our best
16697                }
16698            }
16699            return Collections.EMPTY_LIST;
16700        }
16701
16702        void cleanUpResourcesLI() {
16703            // Enumerate all code paths before deleting
16704            cleanUpResourcesLI(getAllCodePaths());
16705        }
16706
16707        private void cleanUpResourcesLI(List<String> allCodePaths) {
16708            cleanUp();
16709            removeDexFiles(allCodePaths, instructionSets);
16710        }
16711
16712        String getPackageName() {
16713            return getAsecPackageName(cid);
16714        }
16715
16716        boolean doPostDeleteLI(boolean delete) {
16717            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16718            final List<String> allCodePaths = getAllCodePaths();
16719            boolean mounted = PackageHelper.isContainerMounted(cid);
16720            if (mounted) {
16721                // Unmount first
16722                if (PackageHelper.unMountSdDir(cid)) {
16723                    mounted = false;
16724                }
16725            }
16726            if (!mounted && delete) {
16727                cleanUpResourcesLI(allCodePaths);
16728            }
16729            return !mounted;
16730        }
16731
16732        @Override
16733        int doPreCopy() {
16734            if (isFwdLocked()) {
16735                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16736                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16737                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16738                }
16739            }
16740
16741            return PackageManager.INSTALL_SUCCEEDED;
16742        }
16743
16744        @Override
16745        int doPostCopy(int uid) {
16746            if (isFwdLocked()) {
16747                if (uid < Process.FIRST_APPLICATION_UID
16748                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16749                                RES_FILE_NAME)) {
16750                    Slog.e(TAG, "Failed to finalize " + cid);
16751                    PackageHelper.destroySdDir(cid);
16752                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16753                }
16754            }
16755
16756            return PackageManager.INSTALL_SUCCEEDED;
16757        }
16758    }
16759
16760    /**
16761     * Logic to handle movement of existing installed applications.
16762     */
16763    class MoveInstallArgs extends InstallArgs {
16764        private File codeFile;
16765        private File resourceFile;
16766
16767        /** New install */
16768        MoveInstallArgs(InstallParams params) {
16769            super(params.origin, params.move, params.observer, params.installFlags,
16770                    params.installerPackageName, params.volumeUuid,
16771                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16772                    params.grantedRuntimePermissions,
16773                    params.traceMethod, params.traceCookie, params.certificates,
16774                    params.installReason);
16775        }
16776
16777        int copyApk(IMediaContainerService imcs, boolean temp) {
16778            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16779                    + move.fromUuid + " to " + move.toUuid);
16780            synchronized (mInstaller) {
16781                try {
16782                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16783                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16784                } catch (InstallerException e) {
16785                    Slog.w(TAG, "Failed to move app", e);
16786                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16787                }
16788            }
16789
16790            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16791            resourceFile = codeFile;
16792            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16793
16794            return PackageManager.INSTALL_SUCCEEDED;
16795        }
16796
16797        int doPreInstall(int status) {
16798            if (status != PackageManager.INSTALL_SUCCEEDED) {
16799                cleanUp(move.toUuid);
16800            }
16801            return status;
16802        }
16803
16804        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16805            if (status != PackageManager.INSTALL_SUCCEEDED) {
16806                cleanUp(move.toUuid);
16807                return false;
16808            }
16809
16810            // Reflect the move in app info
16811            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16812            pkg.setApplicationInfoCodePath(pkg.codePath);
16813            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16814            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16815            pkg.setApplicationInfoResourcePath(pkg.codePath);
16816            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16817            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16818
16819            return true;
16820        }
16821
16822        int doPostInstall(int status, int uid) {
16823            if (status == PackageManager.INSTALL_SUCCEEDED) {
16824                cleanUp(move.fromUuid);
16825            } else {
16826                cleanUp(move.toUuid);
16827            }
16828            return status;
16829        }
16830
16831        @Override
16832        String getCodePath() {
16833            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16834        }
16835
16836        @Override
16837        String getResourcePath() {
16838            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16839        }
16840
16841        private boolean cleanUp(String volumeUuid) {
16842            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16843                    move.dataAppName);
16844            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16845            final int[] userIds = sUserManager.getUserIds();
16846            synchronized (mInstallLock) {
16847                // Clean up both app data and code
16848                // All package moves are frozen until finished
16849                for (int userId : userIds) {
16850                    try {
16851                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16852                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16853                    } catch (InstallerException e) {
16854                        Slog.w(TAG, String.valueOf(e));
16855                    }
16856                }
16857                removeCodePathLI(codeFile);
16858            }
16859            return true;
16860        }
16861
16862        void cleanUpResourcesLI() {
16863            throw new UnsupportedOperationException();
16864        }
16865
16866        boolean doPostDeleteLI(boolean delete) {
16867            throw new UnsupportedOperationException();
16868        }
16869    }
16870
16871    static String getAsecPackageName(String packageCid) {
16872        int idx = packageCid.lastIndexOf("-");
16873        if (idx == -1) {
16874            return packageCid;
16875        }
16876        return packageCid.substring(0, idx);
16877    }
16878
16879    // Utility method used to create code paths based on package name and available index.
16880    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16881        String idxStr = "";
16882        int idx = 1;
16883        // Fall back to default value of idx=1 if prefix is not
16884        // part of oldCodePath
16885        if (oldCodePath != null) {
16886            String subStr = oldCodePath;
16887            // Drop the suffix right away
16888            if (suffix != null && subStr.endsWith(suffix)) {
16889                subStr = subStr.substring(0, subStr.length() - suffix.length());
16890            }
16891            // If oldCodePath already contains prefix find out the
16892            // ending index to either increment or decrement.
16893            int sidx = subStr.lastIndexOf(prefix);
16894            if (sidx != -1) {
16895                subStr = subStr.substring(sidx + prefix.length());
16896                if (subStr != null) {
16897                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16898                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16899                    }
16900                    try {
16901                        idx = Integer.parseInt(subStr);
16902                        if (idx <= 1) {
16903                            idx++;
16904                        } else {
16905                            idx--;
16906                        }
16907                    } catch(NumberFormatException e) {
16908                    }
16909                }
16910            }
16911        }
16912        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16913        return prefix + idxStr;
16914    }
16915
16916    private File getNextCodePath(File targetDir, String packageName) {
16917        File result;
16918        SecureRandom random = new SecureRandom();
16919        byte[] bytes = new byte[16];
16920        do {
16921            random.nextBytes(bytes);
16922            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16923            result = new File(targetDir, packageName + "-" + suffix);
16924        } while (result.exists());
16925        return result;
16926    }
16927
16928    // Utility method that returns the relative package path with respect
16929    // to the installation directory. Like say for /data/data/com.test-1.apk
16930    // string com.test-1 is returned.
16931    static String deriveCodePathName(String codePath) {
16932        if (codePath == null) {
16933            return null;
16934        }
16935        final File codeFile = new File(codePath);
16936        final String name = codeFile.getName();
16937        if (codeFile.isDirectory()) {
16938            return name;
16939        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16940            final int lastDot = name.lastIndexOf('.');
16941            return name.substring(0, lastDot);
16942        } else {
16943            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16944            return null;
16945        }
16946    }
16947
16948    static class PackageInstalledInfo {
16949        String name;
16950        int uid;
16951        // The set of users that originally had this package installed.
16952        int[] origUsers;
16953        // The set of users that now have this package installed.
16954        int[] newUsers;
16955        PackageParser.Package pkg;
16956        int returnCode;
16957        String returnMsg;
16958        PackageRemovedInfo removedInfo;
16959        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16960
16961        public void setError(int code, String msg) {
16962            setReturnCode(code);
16963            setReturnMessage(msg);
16964            Slog.w(TAG, msg);
16965        }
16966
16967        public void setError(String msg, PackageParserException e) {
16968            setReturnCode(e.error);
16969            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16970            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16971            for (int i = 0; i < childCount; i++) {
16972                addedChildPackages.valueAt(i).setError(msg, e);
16973            }
16974            Slog.w(TAG, msg, e);
16975        }
16976
16977        public void setError(String msg, PackageManagerException e) {
16978            returnCode = e.error;
16979            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16980            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16981            for (int i = 0; i < childCount; i++) {
16982                addedChildPackages.valueAt(i).setError(msg, e);
16983            }
16984            Slog.w(TAG, msg, e);
16985        }
16986
16987        public void setReturnCode(int returnCode) {
16988            this.returnCode = returnCode;
16989            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16990            for (int i = 0; i < childCount; i++) {
16991                addedChildPackages.valueAt(i).returnCode = returnCode;
16992            }
16993        }
16994
16995        private void setReturnMessage(String returnMsg) {
16996            this.returnMsg = returnMsg;
16997            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16998            for (int i = 0; i < childCount; i++) {
16999                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17000            }
17001        }
17002
17003        // In some error cases we want to convey more info back to the observer
17004        String origPackage;
17005        String origPermission;
17006    }
17007
17008    /*
17009     * Install a non-existing package.
17010     */
17011    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17012            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17013            PackageInstalledInfo res, int installReason) {
17014        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17015
17016        // Remember this for later, in case we need to rollback this install
17017        String pkgName = pkg.packageName;
17018
17019        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17020
17021        synchronized(mPackages) {
17022            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17023            if (renamedPackage != null) {
17024                // A package with the same name is already installed, though
17025                // it has been renamed to an older name.  The package we
17026                // are trying to install should be installed as an update to
17027                // the existing one, but that has not been requested, so bail.
17028                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17029                        + " without first uninstalling package running as "
17030                        + renamedPackage);
17031                return;
17032            }
17033            if (mPackages.containsKey(pkgName)) {
17034                // Don't allow installation over an existing package with the same name.
17035                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17036                        + " without first uninstalling.");
17037                return;
17038            }
17039        }
17040
17041        try {
17042            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17043                    System.currentTimeMillis(), user);
17044
17045            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17046
17047            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17048                prepareAppDataAfterInstallLIF(newPackage);
17049
17050            } else {
17051                // Remove package from internal structures, but keep around any
17052                // data that might have already existed
17053                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17054                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17055            }
17056        } catch (PackageManagerException e) {
17057            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17058        }
17059
17060        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17061    }
17062
17063    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17064        // Can't rotate keys during boot or if sharedUser.
17065        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17066                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17067            return false;
17068        }
17069        // app is using upgradeKeySets; make sure all are valid
17070        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17071        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17072        for (int i = 0; i < upgradeKeySets.length; i++) {
17073            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17074                Slog.wtf(TAG, "Package "
17075                         + (oldPs.name != null ? oldPs.name : "<null>")
17076                         + " contains upgrade-key-set reference to unknown key-set: "
17077                         + upgradeKeySets[i]
17078                         + " reverting to signatures check.");
17079                return false;
17080            }
17081        }
17082        return true;
17083    }
17084
17085    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17086        // Upgrade keysets are being used.  Determine if new package has a superset of the
17087        // required keys.
17088        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17089        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17090        for (int i = 0; i < upgradeKeySets.length; i++) {
17091            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17092            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17093                return true;
17094            }
17095        }
17096        return false;
17097    }
17098
17099    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17100        try (DigestInputStream digestStream =
17101                new DigestInputStream(new FileInputStream(file), digest)) {
17102            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17103        }
17104    }
17105
17106    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17107            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17108            int installReason) {
17109        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17110
17111        final PackageParser.Package oldPackage;
17112        final PackageSetting ps;
17113        final String pkgName = pkg.packageName;
17114        final int[] allUsers;
17115        final int[] installedUsers;
17116
17117        synchronized(mPackages) {
17118            oldPackage = mPackages.get(pkgName);
17119            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17120
17121            // don't allow upgrade to target a release SDK from a pre-release SDK
17122            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17123                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17124            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17125                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17126            if (oldTargetsPreRelease
17127                    && !newTargetsPreRelease
17128                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17129                Slog.w(TAG, "Can't install package targeting released sdk");
17130                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17131                return;
17132            }
17133
17134            ps = mSettings.mPackages.get(pkgName);
17135
17136            // verify signatures are valid
17137            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17138                if (!checkUpgradeKeySetLP(ps, pkg)) {
17139                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17140                            "New package not signed by keys specified by upgrade-keysets: "
17141                                    + pkgName);
17142                    return;
17143                }
17144            } else {
17145                // default to original signature matching
17146                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17147                        != PackageManager.SIGNATURE_MATCH) {
17148                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17149                            "New package has a different signature: " + pkgName);
17150                    return;
17151                }
17152            }
17153
17154            // don't allow a system upgrade unless the upgrade hash matches
17155            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17156                byte[] digestBytes = null;
17157                try {
17158                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17159                    updateDigest(digest, new File(pkg.baseCodePath));
17160                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17161                        for (String path : pkg.splitCodePaths) {
17162                            updateDigest(digest, new File(path));
17163                        }
17164                    }
17165                    digestBytes = digest.digest();
17166                } catch (NoSuchAlgorithmException | IOException e) {
17167                    res.setError(INSTALL_FAILED_INVALID_APK,
17168                            "Could not compute hash: " + pkgName);
17169                    return;
17170                }
17171                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17172                    res.setError(INSTALL_FAILED_INVALID_APK,
17173                            "New package fails restrict-update check: " + pkgName);
17174                    return;
17175                }
17176                // retain upgrade restriction
17177                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17178            }
17179
17180            // Check for shared user id changes
17181            String invalidPackageName =
17182                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17183            if (invalidPackageName != null) {
17184                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17185                        "Package " + invalidPackageName + " tried to change user "
17186                                + oldPackage.mSharedUserId);
17187                return;
17188            }
17189
17190            // In case of rollback, remember per-user/profile install state
17191            allUsers = sUserManager.getUserIds();
17192            installedUsers = ps.queryInstalledUsers(allUsers, true);
17193
17194            // don't allow an upgrade from full to ephemeral
17195            if (isInstantApp) {
17196                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17197                    for (int currentUser : allUsers) {
17198                        if (!ps.getInstantApp(currentUser)) {
17199                            // can't downgrade from full to instant
17200                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17201                                    + " for user: " + currentUser);
17202                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17203                            return;
17204                        }
17205                    }
17206                } else if (!ps.getInstantApp(user.getIdentifier())) {
17207                    // can't downgrade from full to instant
17208                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17209                            + " for user: " + user.getIdentifier());
17210                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17211                    return;
17212                }
17213            }
17214        }
17215
17216        // Update what is removed
17217        res.removedInfo = new PackageRemovedInfo(this);
17218        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17219        res.removedInfo.removedPackage = oldPackage.packageName;
17220        res.removedInfo.installerPackageName = ps.installerPackageName;
17221        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17222        res.removedInfo.isUpdate = true;
17223        res.removedInfo.origUsers = installedUsers;
17224        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17225        for (int i = 0; i < installedUsers.length; i++) {
17226            final int userId = installedUsers[i];
17227            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17228        }
17229
17230        final int childCount = (oldPackage.childPackages != null)
17231                ? oldPackage.childPackages.size() : 0;
17232        for (int i = 0; i < childCount; i++) {
17233            boolean childPackageUpdated = false;
17234            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17235            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17236            if (res.addedChildPackages != null) {
17237                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17238                if (childRes != null) {
17239                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17240                    childRes.removedInfo.removedPackage = childPkg.packageName;
17241                    if (childPs != null) {
17242                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17243                    }
17244                    childRes.removedInfo.isUpdate = true;
17245                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17246                    childPackageUpdated = true;
17247                }
17248            }
17249            if (!childPackageUpdated) {
17250                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17251                childRemovedRes.removedPackage = childPkg.packageName;
17252                if (childPs != null) {
17253                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17254                }
17255                childRemovedRes.isUpdate = false;
17256                childRemovedRes.dataRemoved = true;
17257                synchronized (mPackages) {
17258                    if (childPs != null) {
17259                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17260                    }
17261                }
17262                if (res.removedInfo.removedChildPackages == null) {
17263                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17264                }
17265                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17266            }
17267        }
17268
17269        boolean sysPkg = (isSystemApp(oldPackage));
17270        if (sysPkg) {
17271            // Set the system/privileged flags as needed
17272            final boolean privileged =
17273                    (oldPackage.applicationInfo.privateFlags
17274                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17275            final int systemPolicyFlags = policyFlags
17276                    | PackageParser.PARSE_IS_SYSTEM
17277                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17278
17279            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17280                    user, allUsers, installerPackageName, res, installReason);
17281        } else {
17282            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17283                    user, allUsers, installerPackageName, res, installReason);
17284        }
17285    }
17286
17287    @Override
17288    public List<String> getPreviousCodePaths(String packageName) {
17289        final int callingUid = Binder.getCallingUid();
17290        final List<String> result = new ArrayList<>();
17291        if (getInstantAppPackageName(callingUid) != null) {
17292            return result;
17293        }
17294        final PackageSetting ps = mSettings.mPackages.get(packageName);
17295        if (ps != null
17296                && ps.oldCodePaths != null
17297                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17298            result.addAll(ps.oldCodePaths);
17299        }
17300        return result;
17301    }
17302
17303    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17304            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17305            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17306            int installReason) {
17307        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17308                + deletedPackage);
17309
17310        String pkgName = deletedPackage.packageName;
17311        boolean deletedPkg = true;
17312        boolean addedPkg = false;
17313        boolean updatedSettings = false;
17314        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17315        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17316                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17317
17318        final long origUpdateTime = (pkg.mExtras != null)
17319                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17320
17321        // First delete the existing package while retaining the data directory
17322        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17323                res.removedInfo, true, pkg)) {
17324            // If the existing package wasn't successfully deleted
17325            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17326            deletedPkg = false;
17327        } else {
17328            // Successfully deleted the old package; proceed with replace.
17329
17330            // If deleted package lived in a container, give users a chance to
17331            // relinquish resources before killing.
17332            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17333                if (DEBUG_INSTALL) {
17334                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17335                }
17336                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17337                final ArrayList<String> pkgList = new ArrayList<String>(1);
17338                pkgList.add(deletedPackage.applicationInfo.packageName);
17339                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17340            }
17341
17342            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17343                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17344            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17345
17346            try {
17347                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17348                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17349                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17350                        installReason);
17351
17352                // Update the in-memory copy of the previous code paths.
17353                PackageSetting ps = mSettings.mPackages.get(pkgName);
17354                if (!killApp) {
17355                    if (ps.oldCodePaths == null) {
17356                        ps.oldCodePaths = new ArraySet<>();
17357                    }
17358                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17359                    if (deletedPackage.splitCodePaths != null) {
17360                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17361                    }
17362                } else {
17363                    ps.oldCodePaths = null;
17364                }
17365                if (ps.childPackageNames != null) {
17366                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17367                        final String childPkgName = ps.childPackageNames.get(i);
17368                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17369                        childPs.oldCodePaths = ps.oldCodePaths;
17370                    }
17371                }
17372                // set instant app status, but, only if it's explicitly specified
17373                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17374                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17375                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17376                prepareAppDataAfterInstallLIF(newPackage);
17377                addedPkg = true;
17378                mDexManager.notifyPackageUpdated(newPackage.packageName,
17379                        newPackage.baseCodePath, newPackage.splitCodePaths);
17380            } catch (PackageManagerException e) {
17381                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17382            }
17383        }
17384
17385        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17386            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17387
17388            // Revert all internal state mutations and added folders for the failed install
17389            if (addedPkg) {
17390                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17391                        res.removedInfo, true, null);
17392            }
17393
17394            // Restore the old package
17395            if (deletedPkg) {
17396                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17397                File restoreFile = new File(deletedPackage.codePath);
17398                // Parse old package
17399                boolean oldExternal = isExternal(deletedPackage);
17400                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17401                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17402                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17403                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17404                try {
17405                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17406                            null);
17407                } catch (PackageManagerException e) {
17408                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17409                            + e.getMessage());
17410                    return;
17411                }
17412
17413                synchronized (mPackages) {
17414                    // Ensure the installer package name up to date
17415                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17416
17417                    // Update permissions for restored package
17418                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17419
17420                    mSettings.writeLPr();
17421                }
17422
17423                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17424            }
17425        } else {
17426            synchronized (mPackages) {
17427                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17428                if (ps != null) {
17429                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17430                    if (res.removedInfo.removedChildPackages != null) {
17431                        final int childCount = res.removedInfo.removedChildPackages.size();
17432                        // Iterate in reverse as we may modify the collection
17433                        for (int i = childCount - 1; i >= 0; i--) {
17434                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17435                            if (res.addedChildPackages.containsKey(childPackageName)) {
17436                                res.removedInfo.removedChildPackages.removeAt(i);
17437                            } else {
17438                                PackageRemovedInfo childInfo = res.removedInfo
17439                                        .removedChildPackages.valueAt(i);
17440                                childInfo.removedForAllUsers = mPackages.get(
17441                                        childInfo.removedPackage) == null;
17442                            }
17443                        }
17444                    }
17445                }
17446            }
17447        }
17448    }
17449
17450    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17451            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17452            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17453            int installReason) {
17454        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17455                + ", old=" + deletedPackage);
17456
17457        final boolean disabledSystem;
17458
17459        // Remove existing system package
17460        removePackageLI(deletedPackage, true);
17461
17462        synchronized (mPackages) {
17463            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17464        }
17465        if (!disabledSystem) {
17466            // We didn't need to disable the .apk as a current system package,
17467            // which means we are replacing another update that is already
17468            // installed.  We need to make sure to delete the older one's .apk.
17469            res.removedInfo.args = createInstallArgsForExisting(0,
17470                    deletedPackage.applicationInfo.getCodePath(),
17471                    deletedPackage.applicationInfo.getResourcePath(),
17472                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17473        } else {
17474            res.removedInfo.args = null;
17475        }
17476
17477        // Successfully disabled the old package. Now proceed with re-installation
17478        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17479                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17480        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17481
17482        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17483        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17484                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17485
17486        PackageParser.Package newPackage = null;
17487        try {
17488            // Add the package to the internal data structures
17489            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17490
17491            // Set the update and install times
17492            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17493            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17494                    System.currentTimeMillis());
17495
17496            // Update the package dynamic state if succeeded
17497            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17498                // Now that the install succeeded make sure we remove data
17499                // directories for any child package the update removed.
17500                final int deletedChildCount = (deletedPackage.childPackages != null)
17501                        ? deletedPackage.childPackages.size() : 0;
17502                final int newChildCount = (newPackage.childPackages != null)
17503                        ? newPackage.childPackages.size() : 0;
17504                for (int i = 0; i < deletedChildCount; i++) {
17505                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17506                    boolean childPackageDeleted = true;
17507                    for (int j = 0; j < newChildCount; j++) {
17508                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17509                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17510                            childPackageDeleted = false;
17511                            break;
17512                        }
17513                    }
17514                    if (childPackageDeleted) {
17515                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17516                                deletedChildPkg.packageName);
17517                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17518                            PackageRemovedInfo removedChildRes = res.removedInfo
17519                                    .removedChildPackages.get(deletedChildPkg.packageName);
17520                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17521                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17522                        }
17523                    }
17524                }
17525
17526                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17527                        installReason);
17528                prepareAppDataAfterInstallLIF(newPackage);
17529
17530                mDexManager.notifyPackageUpdated(newPackage.packageName,
17531                            newPackage.baseCodePath, newPackage.splitCodePaths);
17532            }
17533        } catch (PackageManagerException e) {
17534            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17535            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17536        }
17537
17538        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17539            // Re installation failed. Restore old information
17540            // Remove new pkg information
17541            if (newPackage != null) {
17542                removeInstalledPackageLI(newPackage, true);
17543            }
17544            // Add back the old system package
17545            try {
17546                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17547            } catch (PackageManagerException e) {
17548                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17549            }
17550
17551            synchronized (mPackages) {
17552                if (disabledSystem) {
17553                    enableSystemPackageLPw(deletedPackage);
17554                }
17555
17556                // Ensure the installer package name up to date
17557                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17558
17559                // Update permissions for restored package
17560                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17561
17562                mSettings.writeLPr();
17563            }
17564
17565            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17566                    + " after failed upgrade");
17567        }
17568    }
17569
17570    /**
17571     * Checks whether the parent or any of the child packages have a change shared
17572     * user. For a package to be a valid update the shred users of the parent and
17573     * the children should match. We may later support changing child shared users.
17574     * @param oldPkg The updated package.
17575     * @param newPkg The update package.
17576     * @return The shared user that change between the versions.
17577     */
17578    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17579            PackageParser.Package newPkg) {
17580        // Check parent shared user
17581        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17582            return newPkg.packageName;
17583        }
17584        // Check child shared users
17585        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17586        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17587        for (int i = 0; i < newChildCount; i++) {
17588            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17589            // If this child was present, did it have the same shared user?
17590            for (int j = 0; j < oldChildCount; j++) {
17591                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17592                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17593                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17594                    return newChildPkg.packageName;
17595                }
17596            }
17597        }
17598        return null;
17599    }
17600
17601    private void removeNativeBinariesLI(PackageSetting ps) {
17602        // Remove the lib path for the parent package
17603        if (ps != null) {
17604            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17605            // Remove the lib path for the child packages
17606            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17607            for (int i = 0; i < childCount; i++) {
17608                PackageSetting childPs = null;
17609                synchronized (mPackages) {
17610                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17611                }
17612                if (childPs != null) {
17613                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17614                            .legacyNativeLibraryPathString);
17615                }
17616            }
17617        }
17618    }
17619
17620    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17621        // Enable the parent package
17622        mSettings.enableSystemPackageLPw(pkg.packageName);
17623        // Enable the child packages
17624        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17625        for (int i = 0; i < childCount; i++) {
17626            PackageParser.Package childPkg = pkg.childPackages.get(i);
17627            mSettings.enableSystemPackageLPw(childPkg.packageName);
17628        }
17629    }
17630
17631    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17632            PackageParser.Package newPkg) {
17633        // Disable the parent package (parent always replaced)
17634        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17635        // Disable the child packages
17636        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17637        for (int i = 0; i < childCount; i++) {
17638            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17639            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17640            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17641        }
17642        return disabled;
17643    }
17644
17645    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17646            String installerPackageName) {
17647        // Enable the parent package
17648        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17649        // Enable the child packages
17650        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17651        for (int i = 0; i < childCount; i++) {
17652            PackageParser.Package childPkg = pkg.childPackages.get(i);
17653            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17654        }
17655    }
17656
17657    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17658        // Collect all used permissions in the UID
17659        ArraySet<String> usedPermissions = new ArraySet<>();
17660        final int packageCount = su.packages.size();
17661        for (int i = 0; i < packageCount; i++) {
17662            PackageSetting ps = su.packages.valueAt(i);
17663            if (ps.pkg == null) {
17664                continue;
17665            }
17666            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17667            for (int j = 0; j < requestedPermCount; j++) {
17668                String permission = ps.pkg.requestedPermissions.get(j);
17669                BasePermission bp = mSettings.mPermissions.get(permission);
17670                if (bp != null) {
17671                    usedPermissions.add(permission);
17672                }
17673            }
17674        }
17675
17676        PermissionsState permissionsState = su.getPermissionsState();
17677        // Prune install permissions
17678        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17679        final int installPermCount = installPermStates.size();
17680        for (int i = installPermCount - 1; i >= 0;  i--) {
17681            PermissionState permissionState = installPermStates.get(i);
17682            if (!usedPermissions.contains(permissionState.getName())) {
17683                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17684                if (bp != null) {
17685                    permissionsState.revokeInstallPermission(bp);
17686                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17687                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17688                }
17689            }
17690        }
17691
17692        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17693
17694        // Prune runtime permissions
17695        for (int userId : allUserIds) {
17696            List<PermissionState> runtimePermStates = permissionsState
17697                    .getRuntimePermissionStates(userId);
17698            final int runtimePermCount = runtimePermStates.size();
17699            for (int i = runtimePermCount - 1; i >= 0; i--) {
17700                PermissionState permissionState = runtimePermStates.get(i);
17701                if (!usedPermissions.contains(permissionState.getName())) {
17702                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17703                    if (bp != null) {
17704                        permissionsState.revokeRuntimePermission(bp, userId);
17705                        permissionsState.updatePermissionFlags(bp, userId,
17706                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17707                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17708                                runtimePermissionChangedUserIds, userId);
17709                    }
17710                }
17711            }
17712        }
17713
17714        return runtimePermissionChangedUserIds;
17715    }
17716
17717    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17718            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17719        // Update the parent package setting
17720        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17721                res, user, installReason);
17722        // Update the child packages setting
17723        final int childCount = (newPackage.childPackages != null)
17724                ? newPackage.childPackages.size() : 0;
17725        for (int i = 0; i < childCount; i++) {
17726            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17727            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17728            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17729                    childRes.origUsers, childRes, user, installReason);
17730        }
17731    }
17732
17733    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17734            String installerPackageName, int[] allUsers, int[] installedForUsers,
17735            PackageInstalledInfo res, UserHandle user, int installReason) {
17736        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17737
17738        String pkgName = newPackage.packageName;
17739        synchronized (mPackages) {
17740            //write settings. the installStatus will be incomplete at this stage.
17741            //note that the new package setting would have already been
17742            //added to mPackages. It hasn't been persisted yet.
17743            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17744            // TODO: Remove this write? It's also written at the end of this method
17745            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17746            mSettings.writeLPr();
17747            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17748        }
17749
17750        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17751        synchronized (mPackages) {
17752            updatePermissionsLPw(newPackage.packageName, newPackage,
17753                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17754                            ? UPDATE_PERMISSIONS_ALL : 0));
17755            // For system-bundled packages, we assume that installing an upgraded version
17756            // of the package implies that the user actually wants to run that new code,
17757            // so we enable the package.
17758            PackageSetting ps = mSettings.mPackages.get(pkgName);
17759            final int userId = user.getIdentifier();
17760            if (ps != null) {
17761                if (isSystemApp(newPackage)) {
17762                    if (DEBUG_INSTALL) {
17763                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17764                    }
17765                    // Enable system package for requested users
17766                    if (res.origUsers != null) {
17767                        for (int origUserId : res.origUsers) {
17768                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17769                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17770                                        origUserId, installerPackageName);
17771                            }
17772                        }
17773                    }
17774                    // Also convey the prior install/uninstall state
17775                    if (allUsers != null && installedForUsers != null) {
17776                        for (int currentUserId : allUsers) {
17777                            final boolean installed = ArrayUtils.contains(
17778                                    installedForUsers, currentUserId);
17779                            if (DEBUG_INSTALL) {
17780                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17781                            }
17782                            ps.setInstalled(installed, currentUserId);
17783                        }
17784                        // these install state changes will be persisted in the
17785                        // upcoming call to mSettings.writeLPr().
17786                    }
17787                }
17788                // It's implied that when a user requests installation, they want the app to be
17789                // installed and enabled.
17790                if (userId != UserHandle.USER_ALL) {
17791                    ps.setInstalled(true, userId);
17792                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17793                }
17794
17795                // When replacing an existing package, preserve the original install reason for all
17796                // users that had the package installed before.
17797                final Set<Integer> previousUserIds = new ArraySet<>();
17798                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17799                    final int installReasonCount = res.removedInfo.installReasons.size();
17800                    for (int i = 0; i < installReasonCount; i++) {
17801                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17802                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17803                        ps.setInstallReason(previousInstallReason, previousUserId);
17804                        previousUserIds.add(previousUserId);
17805                    }
17806                }
17807
17808                // Set install reason for users that are having the package newly installed.
17809                if (userId == UserHandle.USER_ALL) {
17810                    for (int currentUserId : sUserManager.getUserIds()) {
17811                        if (!previousUserIds.contains(currentUserId)) {
17812                            ps.setInstallReason(installReason, currentUserId);
17813                        }
17814                    }
17815                } else if (!previousUserIds.contains(userId)) {
17816                    ps.setInstallReason(installReason, userId);
17817                }
17818                mSettings.writeKernelMappingLPr(ps);
17819            }
17820            res.name = pkgName;
17821            res.uid = newPackage.applicationInfo.uid;
17822            res.pkg = newPackage;
17823            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17824            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17825            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17826            //to update install status
17827            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17828            mSettings.writeLPr();
17829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17830        }
17831
17832        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17833    }
17834
17835    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17836        try {
17837            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17838            installPackageLI(args, res);
17839        } finally {
17840            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17841        }
17842    }
17843
17844    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17845        final int installFlags = args.installFlags;
17846        final String installerPackageName = args.installerPackageName;
17847        final String volumeUuid = args.volumeUuid;
17848        final File tmpPackageFile = new File(args.getCodePath());
17849        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17850        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17851                || (args.volumeUuid != null));
17852        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17853        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17854        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17855        boolean replace = false;
17856        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17857        if (args.move != null) {
17858            // moving a complete application; perform an initial scan on the new install location
17859            scanFlags |= SCAN_INITIAL;
17860        }
17861        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17862            scanFlags |= SCAN_DONT_KILL_APP;
17863        }
17864        if (instantApp) {
17865            scanFlags |= SCAN_AS_INSTANT_APP;
17866        }
17867        if (fullApp) {
17868            scanFlags |= SCAN_AS_FULL_APP;
17869        }
17870
17871        // Result object to be returned
17872        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17873
17874        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17875
17876        // Sanity check
17877        if (instantApp && (forwardLocked || onExternal)) {
17878            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17879                    + " external=" + onExternal);
17880            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17881            return;
17882        }
17883
17884        // Retrieve PackageSettings and parse package
17885        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17886                | PackageParser.PARSE_ENFORCE_CODE
17887                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17888                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17889                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17890                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17891        PackageParser pp = new PackageParser();
17892        pp.setSeparateProcesses(mSeparateProcesses);
17893        pp.setDisplayMetrics(mMetrics);
17894        pp.setCallback(mPackageParserCallback);
17895
17896        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17897        final PackageParser.Package pkg;
17898        try {
17899            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17900        } catch (PackageParserException e) {
17901            res.setError("Failed parse during installPackageLI", e);
17902            return;
17903        } finally {
17904            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17905        }
17906
17907        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17908        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17909            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17910            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17911                    "Instant app package must target O");
17912            return;
17913        }
17914        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17915            Slog.w(TAG, "Instant app package " + pkg.packageName
17916                    + " does not target targetSandboxVersion 2");
17917            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17918                    "Instant app package must use targetSanboxVersion 2");
17919            return;
17920        }
17921
17922        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17923            // Static shared libraries have synthetic package names
17924            renameStaticSharedLibraryPackage(pkg);
17925
17926            // No static shared libs on external storage
17927            if (onExternal) {
17928                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17929                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17930                        "Packages declaring static-shared libs cannot be updated");
17931                return;
17932            }
17933        }
17934
17935        // If we are installing a clustered package add results for the children
17936        if (pkg.childPackages != null) {
17937            synchronized (mPackages) {
17938                final int childCount = pkg.childPackages.size();
17939                for (int i = 0; i < childCount; i++) {
17940                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17941                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17942                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17943                    childRes.pkg = childPkg;
17944                    childRes.name = childPkg.packageName;
17945                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17946                    if (childPs != null) {
17947                        childRes.origUsers = childPs.queryInstalledUsers(
17948                                sUserManager.getUserIds(), true);
17949                    }
17950                    if ((mPackages.containsKey(childPkg.packageName))) {
17951                        childRes.removedInfo = new PackageRemovedInfo(this);
17952                        childRes.removedInfo.removedPackage = childPkg.packageName;
17953                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17954                    }
17955                    if (res.addedChildPackages == null) {
17956                        res.addedChildPackages = new ArrayMap<>();
17957                    }
17958                    res.addedChildPackages.put(childPkg.packageName, childRes);
17959                }
17960            }
17961        }
17962
17963        // If package doesn't declare API override, mark that we have an install
17964        // time CPU ABI override.
17965        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17966            pkg.cpuAbiOverride = args.abiOverride;
17967        }
17968
17969        String pkgName = res.name = pkg.packageName;
17970        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17971            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17972                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17973                return;
17974            }
17975        }
17976
17977        try {
17978            // either use what we've been given or parse directly from the APK
17979            if (args.certificates != null) {
17980                try {
17981                    PackageParser.populateCertificates(pkg, args.certificates);
17982                } catch (PackageParserException e) {
17983                    // there was something wrong with the certificates we were given;
17984                    // try to pull them from the APK
17985                    PackageParser.collectCertificates(pkg, parseFlags);
17986                }
17987            } else {
17988                PackageParser.collectCertificates(pkg, parseFlags);
17989            }
17990        } catch (PackageParserException e) {
17991            res.setError("Failed collect during installPackageLI", e);
17992            return;
17993        }
17994
17995        // Get rid of all references to package scan path via parser.
17996        pp = null;
17997        String oldCodePath = null;
17998        boolean systemApp = false;
17999        synchronized (mPackages) {
18000            // Check if installing already existing package
18001            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18002                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18003                if (pkg.mOriginalPackages != null
18004                        && pkg.mOriginalPackages.contains(oldName)
18005                        && mPackages.containsKey(oldName)) {
18006                    // This package is derived from an original package,
18007                    // and this device has been updating from that original
18008                    // name.  We must continue using the original name, so
18009                    // rename the new package here.
18010                    pkg.setPackageName(oldName);
18011                    pkgName = pkg.packageName;
18012                    replace = true;
18013                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18014                            + oldName + " pkgName=" + pkgName);
18015                } else if (mPackages.containsKey(pkgName)) {
18016                    // This package, under its official name, already exists
18017                    // on the device; we should replace it.
18018                    replace = true;
18019                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18020                }
18021
18022                // Child packages are installed through the parent package
18023                if (pkg.parentPackage != null) {
18024                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18025                            "Package " + pkg.packageName + " is child of package "
18026                                    + pkg.parentPackage.parentPackage + ". Child packages "
18027                                    + "can be updated only through the parent package.");
18028                    return;
18029                }
18030
18031                if (replace) {
18032                    // Prevent apps opting out from runtime permissions
18033                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18034                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18035                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18036                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18037                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18038                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18039                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18040                                        + " doesn't support runtime permissions but the old"
18041                                        + " target SDK " + oldTargetSdk + " does.");
18042                        return;
18043                    }
18044                    // Prevent apps from downgrading their targetSandbox.
18045                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18046                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18047                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18048                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18049                                "Package " + pkg.packageName + " new target sandbox "
18050                                + newTargetSandbox + " is incompatible with the previous value of"
18051                                + oldTargetSandbox + ".");
18052                        return;
18053                    }
18054
18055                    // Prevent installing of child packages
18056                    if (oldPackage.parentPackage != null) {
18057                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18058                                "Package " + pkg.packageName + " is child of package "
18059                                        + oldPackage.parentPackage + ". Child packages "
18060                                        + "can be updated only through the parent package.");
18061                        return;
18062                    }
18063                }
18064            }
18065
18066            PackageSetting ps = mSettings.mPackages.get(pkgName);
18067            if (ps != null) {
18068                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18069
18070                // Static shared libs have same package with different versions where
18071                // we internally use a synthetic package name to allow multiple versions
18072                // of the same package, therefore we need to compare signatures against
18073                // the package setting for the latest library version.
18074                PackageSetting signatureCheckPs = ps;
18075                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18076                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18077                    if (libraryEntry != null) {
18078                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18079                    }
18080                }
18081
18082                // Quick sanity check that we're signed correctly if updating;
18083                // we'll check this again later when scanning, but we want to
18084                // bail early here before tripping over redefined permissions.
18085                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18086                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18087                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18088                                + pkg.packageName + " upgrade keys do not match the "
18089                                + "previously installed version");
18090                        return;
18091                    }
18092                } else {
18093                    try {
18094                        verifySignaturesLP(signatureCheckPs, pkg);
18095                    } catch (PackageManagerException e) {
18096                        res.setError(e.error, e.getMessage());
18097                        return;
18098                    }
18099                }
18100
18101                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18102                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18103                    systemApp = (ps.pkg.applicationInfo.flags &
18104                            ApplicationInfo.FLAG_SYSTEM) != 0;
18105                }
18106                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18107            }
18108
18109            int N = pkg.permissions.size();
18110            for (int i = N-1; i >= 0; i--) {
18111                PackageParser.Permission perm = pkg.permissions.get(i);
18112                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18113
18114                // Don't allow anyone but the system to define ephemeral permissions.
18115                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18116                        && !systemApp) {
18117                    Slog.w(TAG, "Non-System package " + pkg.packageName
18118                            + " attempting to delcare ephemeral permission "
18119                            + perm.info.name + "; Removing ephemeral.");
18120                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18121                }
18122                // Check whether the newly-scanned package wants to define an already-defined perm
18123                if (bp != null) {
18124                    // If the defining package is signed with our cert, it's okay.  This
18125                    // also includes the "updating the same package" case, of course.
18126                    // "updating same package" could also involve key-rotation.
18127                    final boolean sigsOk;
18128                    if (bp.sourcePackage.equals(pkg.packageName)
18129                            && (bp.packageSetting instanceof PackageSetting)
18130                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18131                                    scanFlags))) {
18132                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18133                    } else {
18134                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18135                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18136                    }
18137                    if (!sigsOk) {
18138                        // If the owning package is the system itself, we log but allow
18139                        // install to proceed; we fail the install on all other permission
18140                        // redefinitions.
18141                        if (!bp.sourcePackage.equals("android")) {
18142                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18143                                    + pkg.packageName + " attempting to redeclare permission "
18144                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18145                            res.origPermission = perm.info.name;
18146                            res.origPackage = bp.sourcePackage;
18147                            return;
18148                        } else {
18149                            Slog.w(TAG, "Package " + pkg.packageName
18150                                    + " attempting to redeclare system permission "
18151                                    + perm.info.name + "; ignoring new declaration");
18152                            pkg.permissions.remove(i);
18153                        }
18154                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18155                        // Prevent apps to change protection level to dangerous from any other
18156                        // type as this would allow a privilege escalation where an app adds a
18157                        // normal/signature permission in other app's group and later redefines
18158                        // it as dangerous leading to the group auto-grant.
18159                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18160                                == PermissionInfo.PROTECTION_DANGEROUS) {
18161                            if (bp != null && !bp.isRuntime()) {
18162                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18163                                        + "non-runtime permission " + perm.info.name
18164                                        + " to runtime; keeping old protection level");
18165                                perm.info.protectionLevel = bp.protectionLevel;
18166                            }
18167                        }
18168                    }
18169                }
18170            }
18171        }
18172
18173        if (systemApp) {
18174            if (onExternal) {
18175                // Abort update; system app can't be replaced with app on sdcard
18176                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18177                        "Cannot install updates to system apps on sdcard");
18178                return;
18179            } else if (instantApp) {
18180                // Abort update; system app can't be replaced with an instant app
18181                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18182                        "Cannot update a system app with an instant app");
18183                return;
18184            }
18185        }
18186
18187        if (args.move != null) {
18188            // We did an in-place move, so dex is ready to roll
18189            scanFlags |= SCAN_NO_DEX;
18190            scanFlags |= SCAN_MOVE;
18191
18192            synchronized (mPackages) {
18193                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18194                if (ps == null) {
18195                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18196                            "Missing settings for moved package " + pkgName);
18197                }
18198
18199                // We moved the entire application as-is, so bring over the
18200                // previously derived ABI information.
18201                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18202                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18203            }
18204
18205        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18206            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18207            scanFlags |= SCAN_NO_DEX;
18208
18209            try {
18210                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18211                    args.abiOverride : pkg.cpuAbiOverride);
18212                final boolean extractNativeLibs = !pkg.isLibrary();
18213                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18214                        extractNativeLibs, mAppLib32InstallDir);
18215            } catch (PackageManagerException pme) {
18216                Slog.e(TAG, "Error deriving application ABI", pme);
18217                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18218                return;
18219            }
18220
18221            // Shared libraries for the package need to be updated.
18222            synchronized (mPackages) {
18223                try {
18224                    updateSharedLibrariesLPr(pkg, null);
18225                } catch (PackageManagerException e) {
18226                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18227                }
18228            }
18229
18230            // dexopt can take some time to complete, so, for instant apps, we skip this
18231            // step during installation. Instead, we'll take extra time the first time the
18232            // instant app starts. It's preferred to do it this way to provide continuous
18233            // progress to the user instead of mysteriously blocking somewhere in the
18234            // middle of running an instant app. The default behaviour can be overridden
18235            // via gservices.
18236            if (!instantApp || Global.getInt(
18237                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18238                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18239                // Do not run PackageDexOptimizer through the local performDexOpt
18240                // method because `pkg` may not be in `mPackages` yet.
18241                //
18242                // Also, don't fail application installs if the dexopt step fails.
18243                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18244                        null /* instructionSets */, false /* checkProfiles */,
18245                        getCompilerFilterForReason(REASON_INSTALL),
18246                        getOrCreateCompilerPackageStats(pkg),
18247                        mDexManager.isUsedByOtherApps(pkg.packageName),
18248                        true /* bootComplete */);
18249                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18250            }
18251
18252            // Notify BackgroundDexOptService that the package has been changed.
18253            // If this is an update of a package which used to fail to compile,
18254            // BDOS will remove it from its blacklist.
18255            // TODO: Layering violation
18256            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18257        }
18258
18259        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18260            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18261            return;
18262        }
18263
18264        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18265
18266        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18267                "installPackageLI")) {
18268            if (replace) {
18269                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18270                    // Static libs have a synthetic package name containing the version
18271                    // and cannot be updated as an update would get a new package name,
18272                    // unless this is the exact same version code which is useful for
18273                    // development.
18274                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18275                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18276                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18277                                + "static-shared libs cannot be updated");
18278                        return;
18279                    }
18280                }
18281                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18282                        installerPackageName, res, args.installReason);
18283            } else {
18284                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18285                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18286            }
18287        }
18288
18289        synchronized (mPackages) {
18290            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18291            if (ps != null) {
18292                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18293                ps.setUpdateAvailable(false /*updateAvailable*/);
18294            }
18295
18296            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18297            for (int i = 0; i < childCount; i++) {
18298                PackageParser.Package childPkg = pkg.childPackages.get(i);
18299                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18300                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18301                if (childPs != null) {
18302                    childRes.newUsers = childPs.queryInstalledUsers(
18303                            sUserManager.getUserIds(), true);
18304                }
18305            }
18306
18307            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18308                updateSequenceNumberLP(ps, res.newUsers);
18309                updateInstantAppInstallerLocked(pkgName);
18310            }
18311        }
18312    }
18313
18314    private void startIntentFilterVerifications(int userId, boolean replacing,
18315            PackageParser.Package pkg) {
18316        if (mIntentFilterVerifierComponent == null) {
18317            Slog.w(TAG, "No IntentFilter verification will not be done as "
18318                    + "there is no IntentFilterVerifier available!");
18319            return;
18320        }
18321
18322        final int verifierUid = getPackageUid(
18323                mIntentFilterVerifierComponent.getPackageName(),
18324                MATCH_DEBUG_TRIAGED_MISSING,
18325                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18326
18327        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18328        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18329        mHandler.sendMessage(msg);
18330
18331        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18332        for (int i = 0; i < childCount; i++) {
18333            PackageParser.Package childPkg = pkg.childPackages.get(i);
18334            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18335            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18336            mHandler.sendMessage(msg);
18337        }
18338    }
18339
18340    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18341            PackageParser.Package pkg) {
18342        int size = pkg.activities.size();
18343        if (size == 0) {
18344            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18345                    "No activity, so no need to verify any IntentFilter!");
18346            return;
18347        }
18348
18349        final boolean hasDomainURLs = hasDomainURLs(pkg);
18350        if (!hasDomainURLs) {
18351            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18352                    "No domain URLs, so no need to verify any IntentFilter!");
18353            return;
18354        }
18355
18356        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18357                + " if any IntentFilter from the " + size
18358                + " Activities needs verification ...");
18359
18360        int count = 0;
18361        final String packageName = pkg.packageName;
18362
18363        synchronized (mPackages) {
18364            // If this is a new install and we see that we've already run verification for this
18365            // package, we have nothing to do: it means the state was restored from backup.
18366            if (!replacing) {
18367                IntentFilterVerificationInfo ivi =
18368                        mSettings.getIntentFilterVerificationLPr(packageName);
18369                if (ivi != null) {
18370                    if (DEBUG_DOMAIN_VERIFICATION) {
18371                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18372                                + ivi.getStatusString());
18373                    }
18374                    return;
18375                }
18376            }
18377
18378            // If any filters need to be verified, then all need to be.
18379            boolean needToVerify = false;
18380            for (PackageParser.Activity a : pkg.activities) {
18381                for (ActivityIntentInfo filter : a.intents) {
18382                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18383                        if (DEBUG_DOMAIN_VERIFICATION) {
18384                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18385                        }
18386                        needToVerify = true;
18387                        break;
18388                    }
18389                }
18390            }
18391
18392            if (needToVerify) {
18393                final int verificationId = mIntentFilterVerificationToken++;
18394                for (PackageParser.Activity a : pkg.activities) {
18395                    for (ActivityIntentInfo filter : a.intents) {
18396                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18397                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18398                                    "Verification needed for IntentFilter:" + filter.toString());
18399                            mIntentFilterVerifier.addOneIntentFilterVerification(
18400                                    verifierUid, userId, verificationId, filter, packageName);
18401                            count++;
18402                        }
18403                    }
18404                }
18405            }
18406        }
18407
18408        if (count > 0) {
18409            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18410                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18411                    +  " for userId:" + userId);
18412            mIntentFilterVerifier.startVerifications(userId);
18413        } else {
18414            if (DEBUG_DOMAIN_VERIFICATION) {
18415                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18416            }
18417        }
18418    }
18419
18420    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18421        final ComponentName cn  = filter.activity.getComponentName();
18422        final String packageName = cn.getPackageName();
18423
18424        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18425                packageName);
18426        if (ivi == null) {
18427            return true;
18428        }
18429        int status = ivi.getStatus();
18430        switch (status) {
18431            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18432            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18433                return true;
18434
18435            default:
18436                // Nothing to do
18437                return false;
18438        }
18439    }
18440
18441    private static boolean isMultiArch(ApplicationInfo info) {
18442        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18443    }
18444
18445    private static boolean isExternal(PackageParser.Package pkg) {
18446        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18447    }
18448
18449    private static boolean isExternal(PackageSetting ps) {
18450        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18451    }
18452
18453    private static boolean isSystemApp(PackageParser.Package pkg) {
18454        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18455    }
18456
18457    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18458        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18459    }
18460
18461    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18462        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18463    }
18464
18465    private static boolean isSystemApp(PackageSetting ps) {
18466        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18467    }
18468
18469    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18470        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18471    }
18472
18473    private int packageFlagsToInstallFlags(PackageSetting ps) {
18474        int installFlags = 0;
18475        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18476            // This existing package was an external ASEC install when we have
18477            // the external flag without a UUID
18478            installFlags |= PackageManager.INSTALL_EXTERNAL;
18479        }
18480        if (ps.isForwardLocked()) {
18481            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18482        }
18483        return installFlags;
18484    }
18485
18486    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18487        if (isExternal(pkg)) {
18488            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18489                return StorageManager.UUID_PRIMARY_PHYSICAL;
18490            } else {
18491                return pkg.volumeUuid;
18492            }
18493        } else {
18494            return StorageManager.UUID_PRIVATE_INTERNAL;
18495        }
18496    }
18497
18498    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18499        if (isExternal(pkg)) {
18500            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18501                return mSettings.getExternalVersion();
18502            } else {
18503                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18504            }
18505        } else {
18506            return mSettings.getInternalVersion();
18507        }
18508    }
18509
18510    private void deleteTempPackageFiles() {
18511        final FilenameFilter filter = new FilenameFilter() {
18512            public boolean accept(File dir, String name) {
18513                return name.startsWith("vmdl") && name.endsWith(".tmp");
18514            }
18515        };
18516        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18517            file.delete();
18518        }
18519    }
18520
18521    @Override
18522    public void deletePackageAsUser(String packageName, int versionCode,
18523            IPackageDeleteObserver observer, int userId, int flags) {
18524        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18525                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18526    }
18527
18528    @Override
18529    public void deletePackageVersioned(VersionedPackage versionedPackage,
18530            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18531        final int callingUid = Binder.getCallingUid();
18532        mContext.enforceCallingOrSelfPermission(
18533                android.Manifest.permission.DELETE_PACKAGES, null);
18534        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18535        Preconditions.checkNotNull(versionedPackage);
18536        Preconditions.checkNotNull(observer);
18537        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18538                PackageManager.VERSION_CODE_HIGHEST,
18539                Integer.MAX_VALUE, "versionCode must be >= -1");
18540
18541        final String packageName = versionedPackage.getPackageName();
18542        final int versionCode = versionedPackage.getVersionCode();
18543        final String internalPackageName;
18544        synchronized (mPackages) {
18545            // Normalize package name to handle renamed packages and static libs
18546            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18547                    versionedPackage.getVersionCode());
18548        }
18549
18550        final int uid = Binder.getCallingUid();
18551        if (!isOrphaned(internalPackageName)
18552                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18553            try {
18554                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18555                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18556                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18557                observer.onUserActionRequired(intent);
18558            } catch (RemoteException re) {
18559            }
18560            return;
18561        }
18562        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18563        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18564        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18565            mContext.enforceCallingOrSelfPermission(
18566                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18567                    "deletePackage for user " + userId);
18568        }
18569
18570        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18571            try {
18572                observer.onPackageDeleted(packageName,
18573                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18574            } catch (RemoteException re) {
18575            }
18576            return;
18577        }
18578
18579        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18580            try {
18581                observer.onPackageDeleted(packageName,
18582                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18583            } catch (RemoteException re) {
18584            }
18585            return;
18586        }
18587
18588        if (DEBUG_REMOVE) {
18589            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18590                    + " deleteAllUsers: " + deleteAllUsers + " version="
18591                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18592                    ? "VERSION_CODE_HIGHEST" : versionCode));
18593        }
18594        // Queue up an async operation since the package deletion may take a little while.
18595        mHandler.post(new Runnable() {
18596            public void run() {
18597                mHandler.removeCallbacks(this);
18598                int returnCode;
18599                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18600                boolean doDeletePackage = true;
18601                if (ps != null) {
18602                    final boolean targetIsInstantApp =
18603                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18604                    doDeletePackage = !targetIsInstantApp
18605                            || canViewInstantApps;
18606                }
18607                if (doDeletePackage) {
18608                    if (!deleteAllUsers) {
18609                        returnCode = deletePackageX(internalPackageName, versionCode,
18610                                userId, deleteFlags);
18611                    } else {
18612                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18613                                internalPackageName, users);
18614                        // If nobody is blocking uninstall, proceed with delete for all users
18615                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18616                            returnCode = deletePackageX(internalPackageName, versionCode,
18617                                    userId, deleteFlags);
18618                        } else {
18619                            // Otherwise uninstall individually for users with blockUninstalls=false
18620                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18621                            for (int userId : users) {
18622                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18623                                    returnCode = deletePackageX(internalPackageName, versionCode,
18624                                            userId, userFlags);
18625                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18626                                        Slog.w(TAG, "Package delete failed for user " + userId
18627                                                + ", returnCode " + returnCode);
18628                                    }
18629                                }
18630                            }
18631                            // The app has only been marked uninstalled for certain users.
18632                            // We still need to report that delete was blocked
18633                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18634                        }
18635                    }
18636                } else {
18637                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18638                }
18639                try {
18640                    observer.onPackageDeleted(packageName, returnCode, null);
18641                } catch (RemoteException e) {
18642                    Log.i(TAG, "Observer no longer exists.");
18643                } //end catch
18644            } //end run
18645        });
18646    }
18647
18648    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18649        if (pkg.staticSharedLibName != null) {
18650            return pkg.manifestPackageName;
18651        }
18652        return pkg.packageName;
18653    }
18654
18655    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18656        // Handle renamed packages
18657        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18658        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18659
18660        // Is this a static library?
18661        SparseArray<SharedLibraryEntry> versionedLib =
18662                mStaticLibsByDeclaringPackage.get(packageName);
18663        if (versionedLib == null || versionedLib.size() <= 0) {
18664            return packageName;
18665        }
18666
18667        // Figure out which lib versions the caller can see
18668        SparseIntArray versionsCallerCanSee = null;
18669        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18670        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18671                && callingAppId != Process.ROOT_UID) {
18672            versionsCallerCanSee = new SparseIntArray();
18673            String libName = versionedLib.valueAt(0).info.getName();
18674            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18675            if (uidPackages != null) {
18676                for (String uidPackage : uidPackages) {
18677                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18678                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18679                    if (libIdx >= 0) {
18680                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18681                        versionsCallerCanSee.append(libVersion, libVersion);
18682                    }
18683                }
18684            }
18685        }
18686
18687        // Caller can see nothing - done
18688        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18689            return packageName;
18690        }
18691
18692        // Find the version the caller can see and the app version code
18693        SharedLibraryEntry highestVersion = null;
18694        final int versionCount = versionedLib.size();
18695        for (int i = 0; i < versionCount; i++) {
18696            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18697            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18698                    libEntry.info.getVersion()) < 0) {
18699                continue;
18700            }
18701            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18702            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18703                if (libVersionCode == versionCode) {
18704                    return libEntry.apk;
18705                }
18706            } else if (highestVersion == null) {
18707                highestVersion = libEntry;
18708            } else if (libVersionCode  > highestVersion.info
18709                    .getDeclaringPackage().getVersionCode()) {
18710                highestVersion = libEntry;
18711            }
18712        }
18713
18714        if (highestVersion != null) {
18715            return highestVersion.apk;
18716        }
18717
18718        return packageName;
18719    }
18720
18721    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18722        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18723              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18724            return true;
18725        }
18726        final int callingUserId = UserHandle.getUserId(callingUid);
18727        // If the caller installed the pkgName, then allow it to silently uninstall.
18728        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18729            return true;
18730        }
18731
18732        // Allow package verifier to silently uninstall.
18733        if (mRequiredVerifierPackage != null &&
18734                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18735            return true;
18736        }
18737
18738        // Allow package uninstaller to silently uninstall.
18739        if (mRequiredUninstallerPackage != null &&
18740                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18741            return true;
18742        }
18743
18744        // Allow storage manager to silently uninstall.
18745        if (mStorageManagerPackage != null &&
18746                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18747            return true;
18748        }
18749
18750        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18751        // uninstall for device owner provisioning.
18752        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18753                == PERMISSION_GRANTED) {
18754            return true;
18755        }
18756
18757        return false;
18758    }
18759
18760    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18761        int[] result = EMPTY_INT_ARRAY;
18762        for (int userId : userIds) {
18763            if (getBlockUninstallForUser(packageName, userId)) {
18764                result = ArrayUtils.appendInt(result, userId);
18765            }
18766        }
18767        return result;
18768    }
18769
18770    @Override
18771    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18772        final int callingUid = Binder.getCallingUid();
18773        if (getInstantAppPackageName(callingUid) != null
18774                && !isCallerSameApp(packageName, callingUid)) {
18775            return false;
18776        }
18777        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18778    }
18779
18780    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18781        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18782                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18783        try {
18784            if (dpm != null) {
18785                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18786                        /* callingUserOnly =*/ false);
18787                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18788                        : deviceOwnerComponentName.getPackageName();
18789                // Does the package contains the device owner?
18790                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18791                // this check is probably not needed, since DO should be registered as a device
18792                // admin on some user too. (Original bug for this: b/17657954)
18793                if (packageName.equals(deviceOwnerPackageName)) {
18794                    return true;
18795                }
18796                // Does it contain a device admin for any user?
18797                int[] users;
18798                if (userId == UserHandle.USER_ALL) {
18799                    users = sUserManager.getUserIds();
18800                } else {
18801                    users = new int[]{userId};
18802                }
18803                for (int i = 0; i < users.length; ++i) {
18804                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18805                        return true;
18806                    }
18807                }
18808            }
18809        } catch (RemoteException e) {
18810        }
18811        return false;
18812    }
18813
18814    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18815        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18816    }
18817
18818    /**
18819     *  This method is an internal method that could be get invoked either
18820     *  to delete an installed package or to clean up a failed installation.
18821     *  After deleting an installed package, a broadcast is sent to notify any
18822     *  listeners that the package has been removed. For cleaning up a failed
18823     *  installation, the broadcast is not necessary since the package's
18824     *  installation wouldn't have sent the initial broadcast either
18825     *  The key steps in deleting a package are
18826     *  deleting the package information in internal structures like mPackages,
18827     *  deleting the packages base directories through installd
18828     *  updating mSettings to reflect current status
18829     *  persisting settings for later use
18830     *  sending a broadcast if necessary
18831     */
18832    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18833        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18834        final boolean res;
18835
18836        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18837                ? UserHandle.USER_ALL : userId;
18838
18839        if (isPackageDeviceAdmin(packageName, removeUser)) {
18840            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18841            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18842        }
18843
18844        PackageSetting uninstalledPs = null;
18845        PackageParser.Package pkg = null;
18846
18847        // for the uninstall-updates case and restricted profiles, remember the per-
18848        // user handle installed state
18849        int[] allUsers;
18850        synchronized (mPackages) {
18851            uninstalledPs = mSettings.mPackages.get(packageName);
18852            if (uninstalledPs == null) {
18853                Slog.w(TAG, "Not removing non-existent package " + packageName);
18854                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18855            }
18856
18857            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18858                    && uninstalledPs.versionCode != versionCode) {
18859                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18860                        + uninstalledPs.versionCode + " != " + versionCode);
18861                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18862            }
18863
18864            // Static shared libs can be declared by any package, so let us not
18865            // allow removing a package if it provides a lib others depend on.
18866            pkg = mPackages.get(packageName);
18867
18868            allUsers = sUserManager.getUserIds();
18869
18870            if (pkg != null && pkg.staticSharedLibName != null) {
18871                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18872                        pkg.staticSharedLibVersion);
18873                if (libEntry != null) {
18874                    for (int currUserId : allUsers) {
18875                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18876                            continue;
18877                        }
18878                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18879                                libEntry.info, 0, currUserId);
18880                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18881                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18882                                    + " hosting lib " + libEntry.info.getName() + " version "
18883                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18884                                    + " for user " + currUserId);
18885                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18886                        }
18887                    }
18888                }
18889            }
18890
18891            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18892        }
18893
18894        final int freezeUser;
18895        if (isUpdatedSystemApp(uninstalledPs)
18896                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18897            // We're downgrading a system app, which will apply to all users, so
18898            // freeze them all during the downgrade
18899            freezeUser = UserHandle.USER_ALL;
18900        } else {
18901            freezeUser = removeUser;
18902        }
18903
18904        synchronized (mInstallLock) {
18905            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18906            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18907                    deleteFlags, "deletePackageX")) {
18908                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18909                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18910            }
18911            synchronized (mPackages) {
18912                if (res) {
18913                    if (pkg != null) {
18914                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18915                    }
18916                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18917                    updateInstantAppInstallerLocked(packageName);
18918                }
18919            }
18920        }
18921
18922        if (res) {
18923            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18924            info.sendPackageRemovedBroadcasts(killApp);
18925            info.sendSystemPackageUpdatedBroadcasts();
18926            info.sendSystemPackageAppearedBroadcasts();
18927        }
18928        // Force a gc here.
18929        Runtime.getRuntime().gc();
18930        // Delete the resources here after sending the broadcast to let
18931        // other processes clean up before deleting resources.
18932        if (info.args != null) {
18933            synchronized (mInstallLock) {
18934                info.args.doPostDeleteLI(true);
18935            }
18936        }
18937
18938        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18939    }
18940
18941    static class PackageRemovedInfo {
18942        final PackageSender packageSender;
18943        String removedPackage;
18944        String installerPackageName;
18945        int uid = -1;
18946        int removedAppId = -1;
18947        int[] origUsers;
18948        int[] removedUsers = null;
18949        int[] broadcastUsers = null;
18950        SparseArray<Integer> installReasons;
18951        boolean isRemovedPackageSystemUpdate = false;
18952        boolean isUpdate;
18953        boolean dataRemoved;
18954        boolean removedForAllUsers;
18955        boolean isStaticSharedLib;
18956        // Clean up resources deleted packages.
18957        InstallArgs args = null;
18958        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18959        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18960
18961        PackageRemovedInfo(PackageSender packageSender) {
18962            this.packageSender = packageSender;
18963        }
18964
18965        void sendPackageRemovedBroadcasts(boolean killApp) {
18966            sendPackageRemovedBroadcastInternal(killApp);
18967            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18968            for (int i = 0; i < childCount; i++) {
18969                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18970                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18971            }
18972        }
18973
18974        void sendSystemPackageUpdatedBroadcasts() {
18975            if (isRemovedPackageSystemUpdate) {
18976                sendSystemPackageUpdatedBroadcastsInternal();
18977                final int childCount = (removedChildPackages != null)
18978                        ? removedChildPackages.size() : 0;
18979                for (int i = 0; i < childCount; i++) {
18980                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18981                    if (childInfo.isRemovedPackageSystemUpdate) {
18982                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18983                    }
18984                }
18985            }
18986        }
18987
18988        void sendSystemPackageAppearedBroadcasts() {
18989            final int packageCount = (appearedChildPackages != null)
18990                    ? appearedChildPackages.size() : 0;
18991            for (int i = 0; i < packageCount; i++) {
18992                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18993                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18994                    true, UserHandle.getAppId(installedInfo.uid),
18995                    installedInfo.newUsers);
18996            }
18997        }
18998
18999        private void sendSystemPackageUpdatedBroadcastsInternal() {
19000            Bundle extras = new Bundle(2);
19001            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19002            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19003            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19004                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19005            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19006                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19007            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19008                null, null, 0, removedPackage, null, null);
19009            if (installerPackageName != null) {
19010                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19011                        removedPackage, extras, 0 /*flags*/,
19012                        installerPackageName, null, null);
19013                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19014                        removedPackage, extras, 0 /*flags*/,
19015                        installerPackageName, null, null);
19016            }
19017        }
19018
19019        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19020            // Don't send static shared library removal broadcasts as these
19021            // libs are visible only the the apps that depend on them an one
19022            // cannot remove the library if it has a dependency.
19023            if (isStaticSharedLib) {
19024                return;
19025            }
19026            Bundle extras = new Bundle(2);
19027            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19028            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19029            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19030            if (isUpdate || isRemovedPackageSystemUpdate) {
19031                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19032            }
19033            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19034            if (removedPackage != null) {
19035                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19036                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19037                if (installerPackageName != null) {
19038                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19039                            removedPackage, extras, 0 /*flags*/,
19040                            installerPackageName, null, broadcastUsers);
19041                }
19042                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19043                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19044                        removedPackage, extras,
19045                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19046                        null, null, broadcastUsers);
19047                }
19048            }
19049            if (removedAppId >= 0) {
19050                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19051                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19052                    null, null, broadcastUsers);
19053            }
19054        }
19055
19056        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19057            removedUsers = userIds;
19058            if (removedUsers == null) {
19059                broadcastUsers = null;
19060                return;
19061            }
19062
19063            broadcastUsers = EMPTY_INT_ARRAY;
19064            for (int i = userIds.length - 1; i >= 0; --i) {
19065                final int userId = userIds[i];
19066                if (deletedPackageSetting.getInstantApp(userId)) {
19067                    continue;
19068                }
19069                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19070            }
19071        }
19072    }
19073
19074    /*
19075     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19076     * flag is not set, the data directory is removed as well.
19077     * make sure this flag is set for partially installed apps. If not its meaningless to
19078     * delete a partially installed application.
19079     */
19080    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19081            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19082        String packageName = ps.name;
19083        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19084        // Retrieve object to delete permissions for shared user later on
19085        final PackageParser.Package deletedPkg;
19086        final PackageSetting deletedPs;
19087        // reader
19088        synchronized (mPackages) {
19089            deletedPkg = mPackages.get(packageName);
19090            deletedPs = mSettings.mPackages.get(packageName);
19091            if (outInfo != null) {
19092                outInfo.removedPackage = packageName;
19093                outInfo.installerPackageName = ps.installerPackageName;
19094                outInfo.isStaticSharedLib = deletedPkg != null
19095                        && deletedPkg.staticSharedLibName != null;
19096                outInfo.populateUsers(deletedPs == null ? null
19097                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19098            }
19099        }
19100
19101        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19102
19103        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19104            final PackageParser.Package resolvedPkg;
19105            if (deletedPkg != null) {
19106                resolvedPkg = deletedPkg;
19107            } else {
19108                // We don't have a parsed package when it lives on an ejected
19109                // adopted storage device, so fake something together
19110                resolvedPkg = new PackageParser.Package(ps.name);
19111                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19112            }
19113            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19114                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19115            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19116            if (outInfo != null) {
19117                outInfo.dataRemoved = true;
19118            }
19119            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19120        }
19121
19122        int removedAppId = -1;
19123
19124        // writer
19125        synchronized (mPackages) {
19126            boolean installedStateChanged = false;
19127            if (deletedPs != null) {
19128                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19129                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19130                    clearDefaultBrowserIfNeeded(packageName);
19131                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19132                    removedAppId = mSettings.removePackageLPw(packageName);
19133                    if (outInfo != null) {
19134                        outInfo.removedAppId = removedAppId;
19135                    }
19136                    updatePermissionsLPw(deletedPs.name, null, 0);
19137                    if (deletedPs.sharedUser != null) {
19138                        // Remove permissions associated with package. Since runtime
19139                        // permissions are per user we have to kill the removed package
19140                        // or packages running under the shared user of the removed
19141                        // package if revoking the permissions requested only by the removed
19142                        // package is successful and this causes a change in gids.
19143                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19144                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19145                                    userId);
19146                            if (userIdToKill == UserHandle.USER_ALL
19147                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19148                                // If gids changed for this user, kill all affected packages.
19149                                mHandler.post(new Runnable() {
19150                                    @Override
19151                                    public void run() {
19152                                        // This has to happen with no lock held.
19153                                        killApplication(deletedPs.name, deletedPs.appId,
19154                                                KILL_APP_REASON_GIDS_CHANGED);
19155                                    }
19156                                });
19157                                break;
19158                            }
19159                        }
19160                    }
19161                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19162                }
19163                // make sure to preserve per-user disabled state if this removal was just
19164                // a downgrade of a system app to the factory package
19165                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19166                    if (DEBUG_REMOVE) {
19167                        Slog.d(TAG, "Propagating install state across downgrade");
19168                    }
19169                    for (int userId : allUserHandles) {
19170                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19171                        if (DEBUG_REMOVE) {
19172                            Slog.d(TAG, "    user " + userId + " => " + installed);
19173                        }
19174                        if (installed != ps.getInstalled(userId)) {
19175                            installedStateChanged = true;
19176                        }
19177                        ps.setInstalled(installed, userId);
19178                    }
19179                }
19180            }
19181            // can downgrade to reader
19182            if (writeSettings) {
19183                // Save settings now
19184                mSettings.writeLPr();
19185            }
19186            if (installedStateChanged) {
19187                mSettings.writeKernelMappingLPr(ps);
19188            }
19189        }
19190        if (removedAppId != -1) {
19191            // A user ID was deleted here. Go through all users and remove it
19192            // from KeyStore.
19193            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19194        }
19195    }
19196
19197    static boolean locationIsPrivileged(File path) {
19198        try {
19199            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19200                    .getCanonicalPath();
19201            return path.getCanonicalPath().startsWith(privilegedAppDir);
19202        } catch (IOException e) {
19203            Slog.e(TAG, "Unable to access code path " + path);
19204        }
19205        return false;
19206    }
19207
19208    /*
19209     * Tries to delete system package.
19210     */
19211    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19212            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19213            boolean writeSettings) {
19214        if (deletedPs.parentPackageName != null) {
19215            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19216            return false;
19217        }
19218
19219        final boolean applyUserRestrictions
19220                = (allUserHandles != null) && (outInfo.origUsers != null);
19221        final PackageSetting disabledPs;
19222        // Confirm if the system package has been updated
19223        // An updated system app can be deleted. This will also have to restore
19224        // the system pkg from system partition
19225        // reader
19226        synchronized (mPackages) {
19227            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19228        }
19229
19230        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19231                + " disabledPs=" + disabledPs);
19232
19233        if (disabledPs == null) {
19234            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19235            return false;
19236        } else if (DEBUG_REMOVE) {
19237            Slog.d(TAG, "Deleting system pkg from data partition");
19238        }
19239
19240        if (DEBUG_REMOVE) {
19241            if (applyUserRestrictions) {
19242                Slog.d(TAG, "Remembering install states:");
19243                for (int userId : allUserHandles) {
19244                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19245                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19246                }
19247            }
19248        }
19249
19250        // Delete the updated package
19251        outInfo.isRemovedPackageSystemUpdate = true;
19252        if (outInfo.removedChildPackages != null) {
19253            final int childCount = (deletedPs.childPackageNames != null)
19254                    ? deletedPs.childPackageNames.size() : 0;
19255            for (int i = 0; i < childCount; i++) {
19256                String childPackageName = deletedPs.childPackageNames.get(i);
19257                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19258                        .contains(childPackageName)) {
19259                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19260                            childPackageName);
19261                    if (childInfo != null) {
19262                        childInfo.isRemovedPackageSystemUpdate = true;
19263                    }
19264                }
19265            }
19266        }
19267
19268        if (disabledPs.versionCode < deletedPs.versionCode) {
19269            // Delete data for downgrades
19270            flags &= ~PackageManager.DELETE_KEEP_DATA;
19271        } else {
19272            // Preserve data by setting flag
19273            flags |= PackageManager.DELETE_KEEP_DATA;
19274        }
19275
19276        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19277                outInfo, writeSettings, disabledPs.pkg);
19278        if (!ret) {
19279            return false;
19280        }
19281
19282        // writer
19283        synchronized (mPackages) {
19284            // Reinstate the old system package
19285            enableSystemPackageLPw(disabledPs.pkg);
19286            // Remove any native libraries from the upgraded package.
19287            removeNativeBinariesLI(deletedPs);
19288        }
19289
19290        // Install the system package
19291        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19292        int parseFlags = mDefParseFlags
19293                | PackageParser.PARSE_MUST_BE_APK
19294                | PackageParser.PARSE_IS_SYSTEM
19295                | PackageParser.PARSE_IS_SYSTEM_DIR;
19296        if (locationIsPrivileged(disabledPs.codePath)) {
19297            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19298        }
19299
19300        final PackageParser.Package newPkg;
19301        try {
19302            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19303                0 /* currentTime */, null);
19304        } catch (PackageManagerException e) {
19305            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19306                    + e.getMessage());
19307            return false;
19308        }
19309
19310        try {
19311            // update shared libraries for the newly re-installed system package
19312            updateSharedLibrariesLPr(newPkg, null);
19313        } catch (PackageManagerException e) {
19314            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19315        }
19316
19317        prepareAppDataAfterInstallLIF(newPkg);
19318
19319        // writer
19320        synchronized (mPackages) {
19321            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19322
19323            // Propagate the permissions state as we do not want to drop on the floor
19324            // runtime permissions. The update permissions method below will take
19325            // care of removing obsolete permissions and grant install permissions.
19326            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19327            updatePermissionsLPw(newPkg.packageName, newPkg,
19328                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19329
19330            if (applyUserRestrictions) {
19331                boolean installedStateChanged = false;
19332                if (DEBUG_REMOVE) {
19333                    Slog.d(TAG, "Propagating install state across reinstall");
19334                }
19335                for (int userId : allUserHandles) {
19336                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19337                    if (DEBUG_REMOVE) {
19338                        Slog.d(TAG, "    user " + userId + " => " + installed);
19339                    }
19340                    if (installed != ps.getInstalled(userId)) {
19341                        installedStateChanged = true;
19342                    }
19343                    ps.setInstalled(installed, userId);
19344
19345                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19346                }
19347                // Regardless of writeSettings we need to ensure that this restriction
19348                // state propagation is persisted
19349                mSettings.writeAllUsersPackageRestrictionsLPr();
19350                if (installedStateChanged) {
19351                    mSettings.writeKernelMappingLPr(ps);
19352                }
19353            }
19354            // can downgrade to reader here
19355            if (writeSettings) {
19356                mSettings.writeLPr();
19357            }
19358        }
19359        return true;
19360    }
19361
19362    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19363            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19364            PackageRemovedInfo outInfo, boolean writeSettings,
19365            PackageParser.Package replacingPackage) {
19366        synchronized (mPackages) {
19367            if (outInfo != null) {
19368                outInfo.uid = ps.appId;
19369            }
19370
19371            if (outInfo != null && outInfo.removedChildPackages != null) {
19372                final int childCount = (ps.childPackageNames != null)
19373                        ? ps.childPackageNames.size() : 0;
19374                for (int i = 0; i < childCount; i++) {
19375                    String childPackageName = ps.childPackageNames.get(i);
19376                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19377                    if (childPs == null) {
19378                        return false;
19379                    }
19380                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19381                            childPackageName);
19382                    if (childInfo != null) {
19383                        childInfo.uid = childPs.appId;
19384                    }
19385                }
19386            }
19387        }
19388
19389        // Delete package data from internal structures and also remove data if flag is set
19390        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19391
19392        // Delete the child packages data
19393        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19394        for (int i = 0; i < childCount; i++) {
19395            PackageSetting childPs;
19396            synchronized (mPackages) {
19397                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19398            }
19399            if (childPs != null) {
19400                PackageRemovedInfo childOutInfo = (outInfo != null
19401                        && outInfo.removedChildPackages != null)
19402                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19403                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19404                        && (replacingPackage != null
19405                        && !replacingPackage.hasChildPackage(childPs.name))
19406                        ? flags & ~DELETE_KEEP_DATA : flags;
19407                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19408                        deleteFlags, writeSettings);
19409            }
19410        }
19411
19412        // Delete application code and resources only for parent packages
19413        if (ps.parentPackageName == null) {
19414            if (deleteCodeAndResources && (outInfo != null)) {
19415                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19416                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19417                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19418            }
19419        }
19420
19421        return true;
19422    }
19423
19424    @Override
19425    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19426            int userId) {
19427        mContext.enforceCallingOrSelfPermission(
19428                android.Manifest.permission.DELETE_PACKAGES, null);
19429        synchronized (mPackages) {
19430            // Cannot block uninstall of static shared libs as they are
19431            // considered a part of the using app (emulating static linking).
19432            // Also static libs are installed always on internal storage.
19433            PackageParser.Package pkg = mPackages.get(packageName);
19434            if (pkg != null && pkg.staticSharedLibName != null) {
19435                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19436                        + " providing static shared library: " + pkg.staticSharedLibName);
19437                return false;
19438            }
19439            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19440            mSettings.writePackageRestrictionsLPr(userId);
19441        }
19442        return true;
19443    }
19444
19445    @Override
19446    public boolean getBlockUninstallForUser(String packageName, int userId) {
19447        synchronized (mPackages) {
19448            final PackageSetting ps = mSettings.mPackages.get(packageName);
19449            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19450                return false;
19451            }
19452            return mSettings.getBlockUninstallLPr(userId, packageName);
19453        }
19454    }
19455
19456    @Override
19457    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19458        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19459        synchronized (mPackages) {
19460            PackageSetting ps = mSettings.mPackages.get(packageName);
19461            if (ps == null) {
19462                Log.w(TAG, "Package doesn't exist: " + packageName);
19463                return false;
19464            }
19465            if (systemUserApp) {
19466                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19467            } else {
19468                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19469            }
19470            mSettings.writeLPr();
19471        }
19472        return true;
19473    }
19474
19475    /*
19476     * This method handles package deletion in general
19477     */
19478    private boolean deletePackageLIF(String packageName, UserHandle user,
19479            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19480            PackageRemovedInfo outInfo, boolean writeSettings,
19481            PackageParser.Package replacingPackage) {
19482        if (packageName == null) {
19483            Slog.w(TAG, "Attempt to delete null packageName.");
19484            return false;
19485        }
19486
19487        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19488
19489        PackageSetting ps;
19490        synchronized (mPackages) {
19491            ps = mSettings.mPackages.get(packageName);
19492            if (ps == null) {
19493                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19494                return false;
19495            }
19496
19497            if (ps.parentPackageName != null && (!isSystemApp(ps)
19498                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19499                if (DEBUG_REMOVE) {
19500                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19501                            + ((user == null) ? UserHandle.USER_ALL : user));
19502                }
19503                final int removedUserId = (user != null) ? user.getIdentifier()
19504                        : UserHandle.USER_ALL;
19505                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19506                    return false;
19507                }
19508                markPackageUninstalledForUserLPw(ps, user);
19509                scheduleWritePackageRestrictionsLocked(user);
19510                return true;
19511            }
19512        }
19513
19514        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19515                && user.getIdentifier() != UserHandle.USER_ALL)) {
19516            // The caller is asking that the package only be deleted for a single
19517            // user.  To do this, we just mark its uninstalled state and delete
19518            // its data. If this is a system app, we only allow this to happen if
19519            // they have set the special DELETE_SYSTEM_APP which requests different
19520            // semantics than normal for uninstalling system apps.
19521            markPackageUninstalledForUserLPw(ps, user);
19522
19523            if (!isSystemApp(ps)) {
19524                // Do not uninstall the APK if an app should be cached
19525                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19526                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19527                    // Other user still have this package installed, so all
19528                    // we need to do is clear this user's data and save that
19529                    // it is uninstalled.
19530                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19531                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19532                        return false;
19533                    }
19534                    scheduleWritePackageRestrictionsLocked(user);
19535                    return true;
19536                } else {
19537                    // We need to set it back to 'installed' so the uninstall
19538                    // broadcasts will be sent correctly.
19539                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19540                    ps.setInstalled(true, user.getIdentifier());
19541                    mSettings.writeKernelMappingLPr(ps);
19542                }
19543            } else {
19544                // This is a system app, so we assume that the
19545                // other users still have this package installed, so all
19546                // we need to do is clear this user's data and save that
19547                // it is uninstalled.
19548                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19549                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19550                    return false;
19551                }
19552                scheduleWritePackageRestrictionsLocked(user);
19553                return true;
19554            }
19555        }
19556
19557        // If we are deleting a composite package for all users, keep track
19558        // of result for each child.
19559        if (ps.childPackageNames != null && outInfo != null) {
19560            synchronized (mPackages) {
19561                final int childCount = ps.childPackageNames.size();
19562                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19563                for (int i = 0; i < childCount; i++) {
19564                    String childPackageName = ps.childPackageNames.get(i);
19565                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19566                    childInfo.removedPackage = childPackageName;
19567                    childInfo.installerPackageName = ps.installerPackageName;
19568                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19569                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19570                    if (childPs != null) {
19571                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19572                    }
19573                }
19574            }
19575        }
19576
19577        boolean ret = false;
19578        if (isSystemApp(ps)) {
19579            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19580            // When an updated system application is deleted we delete the existing resources
19581            // as well and fall back to existing code in system partition
19582            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19583        } else {
19584            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19585            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19586                    outInfo, writeSettings, replacingPackage);
19587        }
19588
19589        // Take a note whether we deleted the package for all users
19590        if (outInfo != null) {
19591            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19592            if (outInfo.removedChildPackages != null) {
19593                synchronized (mPackages) {
19594                    final int childCount = outInfo.removedChildPackages.size();
19595                    for (int i = 0; i < childCount; i++) {
19596                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19597                        if (childInfo != null) {
19598                            childInfo.removedForAllUsers = mPackages.get(
19599                                    childInfo.removedPackage) == null;
19600                        }
19601                    }
19602                }
19603            }
19604            // If we uninstalled an update to a system app there may be some
19605            // child packages that appeared as they are declared in the system
19606            // app but were not declared in the update.
19607            if (isSystemApp(ps)) {
19608                synchronized (mPackages) {
19609                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19610                    final int childCount = (updatedPs.childPackageNames != null)
19611                            ? updatedPs.childPackageNames.size() : 0;
19612                    for (int i = 0; i < childCount; i++) {
19613                        String childPackageName = updatedPs.childPackageNames.get(i);
19614                        if (outInfo.removedChildPackages == null
19615                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19616                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19617                            if (childPs == null) {
19618                                continue;
19619                            }
19620                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19621                            installRes.name = childPackageName;
19622                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19623                            installRes.pkg = mPackages.get(childPackageName);
19624                            installRes.uid = childPs.pkg.applicationInfo.uid;
19625                            if (outInfo.appearedChildPackages == null) {
19626                                outInfo.appearedChildPackages = new ArrayMap<>();
19627                            }
19628                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19629                        }
19630                    }
19631                }
19632            }
19633        }
19634
19635        return ret;
19636    }
19637
19638    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19639        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19640                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19641        for (int nextUserId : userIds) {
19642            if (DEBUG_REMOVE) {
19643                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19644            }
19645            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19646                    false /*installed*/,
19647                    true /*stopped*/,
19648                    true /*notLaunched*/,
19649                    false /*hidden*/,
19650                    false /*suspended*/,
19651                    false /*instantApp*/,
19652                    null /*lastDisableAppCaller*/,
19653                    null /*enabledComponents*/,
19654                    null /*disabledComponents*/,
19655                    ps.readUserState(nextUserId).domainVerificationStatus,
19656                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19657        }
19658        mSettings.writeKernelMappingLPr(ps);
19659    }
19660
19661    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19662            PackageRemovedInfo outInfo) {
19663        final PackageParser.Package pkg;
19664        synchronized (mPackages) {
19665            pkg = mPackages.get(ps.name);
19666        }
19667
19668        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19669                : new int[] {userId};
19670        for (int nextUserId : userIds) {
19671            if (DEBUG_REMOVE) {
19672                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19673                        + nextUserId);
19674            }
19675
19676            destroyAppDataLIF(pkg, userId,
19677                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19678            destroyAppProfilesLIF(pkg, userId);
19679            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19680            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19681            schedulePackageCleaning(ps.name, nextUserId, false);
19682            synchronized (mPackages) {
19683                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19684                    scheduleWritePackageRestrictionsLocked(nextUserId);
19685                }
19686                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19687            }
19688        }
19689
19690        if (outInfo != null) {
19691            outInfo.removedPackage = ps.name;
19692            outInfo.installerPackageName = ps.installerPackageName;
19693            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19694            outInfo.removedAppId = ps.appId;
19695            outInfo.removedUsers = userIds;
19696            outInfo.broadcastUsers = userIds;
19697        }
19698
19699        return true;
19700    }
19701
19702    private final class ClearStorageConnection implements ServiceConnection {
19703        IMediaContainerService mContainerService;
19704
19705        @Override
19706        public void onServiceConnected(ComponentName name, IBinder service) {
19707            synchronized (this) {
19708                mContainerService = IMediaContainerService.Stub
19709                        .asInterface(Binder.allowBlocking(service));
19710                notifyAll();
19711            }
19712        }
19713
19714        @Override
19715        public void onServiceDisconnected(ComponentName name) {
19716        }
19717    }
19718
19719    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19720        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19721
19722        final boolean mounted;
19723        if (Environment.isExternalStorageEmulated()) {
19724            mounted = true;
19725        } else {
19726            final String status = Environment.getExternalStorageState();
19727
19728            mounted = status.equals(Environment.MEDIA_MOUNTED)
19729                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19730        }
19731
19732        if (!mounted) {
19733            return;
19734        }
19735
19736        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19737        int[] users;
19738        if (userId == UserHandle.USER_ALL) {
19739            users = sUserManager.getUserIds();
19740        } else {
19741            users = new int[] { userId };
19742        }
19743        final ClearStorageConnection conn = new ClearStorageConnection();
19744        if (mContext.bindServiceAsUser(
19745                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19746            try {
19747                for (int curUser : users) {
19748                    long timeout = SystemClock.uptimeMillis() + 5000;
19749                    synchronized (conn) {
19750                        long now;
19751                        while (conn.mContainerService == null &&
19752                                (now = SystemClock.uptimeMillis()) < timeout) {
19753                            try {
19754                                conn.wait(timeout - now);
19755                            } catch (InterruptedException e) {
19756                            }
19757                        }
19758                    }
19759                    if (conn.mContainerService == null) {
19760                        return;
19761                    }
19762
19763                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19764                    clearDirectory(conn.mContainerService,
19765                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19766                    if (allData) {
19767                        clearDirectory(conn.mContainerService,
19768                                userEnv.buildExternalStorageAppDataDirs(packageName));
19769                        clearDirectory(conn.mContainerService,
19770                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19771                    }
19772                }
19773            } finally {
19774                mContext.unbindService(conn);
19775            }
19776        }
19777    }
19778
19779    @Override
19780    public void clearApplicationProfileData(String packageName) {
19781        enforceSystemOrRoot("Only the system can clear all profile data");
19782
19783        final PackageParser.Package pkg;
19784        synchronized (mPackages) {
19785            pkg = mPackages.get(packageName);
19786        }
19787
19788        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19789            synchronized (mInstallLock) {
19790                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19791            }
19792        }
19793    }
19794
19795    @Override
19796    public void clearApplicationUserData(final String packageName,
19797            final IPackageDataObserver observer, final int userId) {
19798        mContext.enforceCallingOrSelfPermission(
19799                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19800
19801        final int callingUid = Binder.getCallingUid();
19802        enforceCrossUserPermission(callingUid, userId,
19803                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19804
19805        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19806        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19807            return;
19808        }
19809        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19810            throw new SecurityException("Cannot clear data for a protected package: "
19811                    + packageName);
19812        }
19813        // Queue up an async operation since the package deletion may take a little while.
19814        mHandler.post(new Runnable() {
19815            public void run() {
19816                mHandler.removeCallbacks(this);
19817                final boolean succeeded;
19818                try (PackageFreezer freezer = freezePackage(packageName,
19819                        "clearApplicationUserData")) {
19820                    synchronized (mInstallLock) {
19821                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19822                    }
19823                    clearExternalStorageDataSync(packageName, userId, true);
19824                    synchronized (mPackages) {
19825                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19826                                packageName, userId);
19827                    }
19828                }
19829                if (succeeded) {
19830                    // invoke DeviceStorageMonitor's update method to clear any notifications
19831                    DeviceStorageMonitorInternal dsm = LocalServices
19832                            .getService(DeviceStorageMonitorInternal.class);
19833                    if (dsm != null) {
19834                        dsm.checkMemory();
19835                    }
19836                }
19837                if(observer != null) {
19838                    try {
19839                        observer.onRemoveCompleted(packageName, succeeded);
19840                    } catch (RemoteException e) {
19841                        Log.i(TAG, "Observer no longer exists.");
19842                    }
19843                } //end if observer
19844            } //end run
19845        });
19846    }
19847
19848    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19849        if (packageName == null) {
19850            Slog.w(TAG, "Attempt to delete null packageName.");
19851            return false;
19852        }
19853
19854        // Try finding details about the requested package
19855        PackageParser.Package pkg;
19856        synchronized (mPackages) {
19857            pkg = mPackages.get(packageName);
19858            if (pkg == null) {
19859                final PackageSetting ps = mSettings.mPackages.get(packageName);
19860                if (ps != null) {
19861                    pkg = ps.pkg;
19862                }
19863            }
19864
19865            if (pkg == null) {
19866                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19867                return false;
19868            }
19869
19870            PackageSetting ps = (PackageSetting) pkg.mExtras;
19871            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19872        }
19873
19874        clearAppDataLIF(pkg, userId,
19875                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19876
19877        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19878        removeKeystoreDataIfNeeded(userId, appId);
19879
19880        UserManagerInternal umInternal = getUserManagerInternal();
19881        final int flags;
19882        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19883            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19884        } else if (umInternal.isUserRunning(userId)) {
19885            flags = StorageManager.FLAG_STORAGE_DE;
19886        } else {
19887            flags = 0;
19888        }
19889        prepareAppDataContentsLIF(pkg, userId, flags);
19890
19891        return true;
19892    }
19893
19894    /**
19895     * Reverts user permission state changes (permissions and flags) in
19896     * all packages for a given user.
19897     *
19898     * @param userId The device user for which to do a reset.
19899     */
19900    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19901        final int packageCount = mPackages.size();
19902        for (int i = 0; i < packageCount; i++) {
19903            PackageParser.Package pkg = mPackages.valueAt(i);
19904            PackageSetting ps = (PackageSetting) pkg.mExtras;
19905            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19906        }
19907    }
19908
19909    private void resetNetworkPolicies(int userId) {
19910        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19911    }
19912
19913    /**
19914     * Reverts user permission state changes (permissions and flags).
19915     *
19916     * @param ps The package for which to reset.
19917     * @param userId The device user for which to do a reset.
19918     */
19919    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19920            final PackageSetting ps, final int userId) {
19921        if (ps.pkg == null) {
19922            return;
19923        }
19924
19925        // These are flags that can change base on user actions.
19926        final int userSettableMask = FLAG_PERMISSION_USER_SET
19927                | FLAG_PERMISSION_USER_FIXED
19928                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19929                | FLAG_PERMISSION_REVIEW_REQUIRED;
19930
19931        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19932                | FLAG_PERMISSION_POLICY_FIXED;
19933
19934        boolean writeInstallPermissions = false;
19935        boolean writeRuntimePermissions = false;
19936
19937        final int permissionCount = ps.pkg.requestedPermissions.size();
19938        for (int i = 0; i < permissionCount; i++) {
19939            String permission = ps.pkg.requestedPermissions.get(i);
19940
19941            BasePermission bp = mSettings.mPermissions.get(permission);
19942            if (bp == null) {
19943                continue;
19944            }
19945
19946            // If shared user we just reset the state to which only this app contributed.
19947            if (ps.sharedUser != null) {
19948                boolean used = false;
19949                final int packageCount = ps.sharedUser.packages.size();
19950                for (int j = 0; j < packageCount; j++) {
19951                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19952                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19953                            && pkg.pkg.requestedPermissions.contains(permission)) {
19954                        used = true;
19955                        break;
19956                    }
19957                }
19958                if (used) {
19959                    continue;
19960                }
19961            }
19962
19963            PermissionsState permissionsState = ps.getPermissionsState();
19964
19965            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19966
19967            // Always clear the user settable flags.
19968            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19969                    bp.name) != null;
19970            // If permission review is enabled and this is a legacy app, mark the
19971            // permission as requiring a review as this is the initial state.
19972            int flags = 0;
19973            if (mPermissionReviewRequired
19974                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19975                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19976            }
19977            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19978                if (hasInstallState) {
19979                    writeInstallPermissions = true;
19980                } else {
19981                    writeRuntimePermissions = true;
19982                }
19983            }
19984
19985            // Below is only runtime permission handling.
19986            if (!bp.isRuntime()) {
19987                continue;
19988            }
19989
19990            // Never clobber system or policy.
19991            if ((oldFlags & policyOrSystemFlags) != 0) {
19992                continue;
19993            }
19994
19995            // If this permission was granted by default, make sure it is.
19996            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19997                if (permissionsState.grantRuntimePermission(bp, userId)
19998                        != PERMISSION_OPERATION_FAILURE) {
19999                    writeRuntimePermissions = true;
20000                }
20001            // If permission review is enabled the permissions for a legacy apps
20002            // are represented as constantly granted runtime ones, so don't revoke.
20003            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20004                // Otherwise, reset the permission.
20005                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20006                switch (revokeResult) {
20007                    case PERMISSION_OPERATION_SUCCESS:
20008                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20009                        writeRuntimePermissions = true;
20010                        final int appId = ps.appId;
20011                        mHandler.post(new Runnable() {
20012                            @Override
20013                            public void run() {
20014                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20015                            }
20016                        });
20017                    } break;
20018                }
20019            }
20020        }
20021
20022        // Synchronously write as we are taking permissions away.
20023        if (writeRuntimePermissions) {
20024            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20025        }
20026
20027        // Synchronously write as we are taking permissions away.
20028        if (writeInstallPermissions) {
20029            mSettings.writeLPr();
20030        }
20031    }
20032
20033    /**
20034     * Remove entries from the keystore daemon. Will only remove it if the
20035     * {@code appId} is valid.
20036     */
20037    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20038        if (appId < 0) {
20039            return;
20040        }
20041
20042        final KeyStore keyStore = KeyStore.getInstance();
20043        if (keyStore != null) {
20044            if (userId == UserHandle.USER_ALL) {
20045                for (final int individual : sUserManager.getUserIds()) {
20046                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20047                }
20048            } else {
20049                keyStore.clearUid(UserHandle.getUid(userId, appId));
20050            }
20051        } else {
20052            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20053        }
20054    }
20055
20056    @Override
20057    public void deleteApplicationCacheFiles(final String packageName,
20058            final IPackageDataObserver observer) {
20059        final int userId = UserHandle.getCallingUserId();
20060        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20061    }
20062
20063    @Override
20064    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20065            final IPackageDataObserver observer) {
20066        final int callingUid = Binder.getCallingUid();
20067        mContext.enforceCallingOrSelfPermission(
20068                android.Manifest.permission.DELETE_CACHE_FILES, null);
20069        enforceCrossUserPermission(callingUid, userId,
20070                /* requireFullPermission= */ true, /* checkShell= */ false,
20071                "delete application cache files");
20072        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20073                android.Manifest.permission.ACCESS_INSTANT_APPS);
20074
20075        final PackageParser.Package pkg;
20076        synchronized (mPackages) {
20077            pkg = mPackages.get(packageName);
20078        }
20079
20080        // Queue up an async operation since the package deletion may take a little while.
20081        mHandler.post(new Runnable() {
20082            public void run() {
20083                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20084                boolean doClearData = true;
20085                if (ps != null) {
20086                    final boolean targetIsInstantApp =
20087                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20088                    doClearData = !targetIsInstantApp
20089                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20090                }
20091                if (doClearData) {
20092                    synchronized (mInstallLock) {
20093                        final int flags = StorageManager.FLAG_STORAGE_DE
20094                                | StorageManager.FLAG_STORAGE_CE;
20095                        // We're only clearing cache files, so we don't care if the
20096                        // app is unfrozen and still able to run
20097                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20098                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20099                    }
20100                    clearExternalStorageDataSync(packageName, userId, false);
20101                }
20102                if (observer != null) {
20103                    try {
20104                        observer.onRemoveCompleted(packageName, true);
20105                    } catch (RemoteException e) {
20106                        Log.i(TAG, "Observer no longer exists.");
20107                    }
20108                }
20109            }
20110        });
20111    }
20112
20113    @Override
20114    public void getPackageSizeInfo(final String packageName, int userHandle,
20115            final IPackageStatsObserver observer) {
20116        throw new UnsupportedOperationException(
20117                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20118    }
20119
20120    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20121        final PackageSetting ps;
20122        synchronized (mPackages) {
20123            ps = mSettings.mPackages.get(packageName);
20124            if (ps == null) {
20125                Slog.w(TAG, "Failed to find settings for " + packageName);
20126                return false;
20127            }
20128        }
20129
20130        final String[] packageNames = { packageName };
20131        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20132        final String[] codePaths = { ps.codePathString };
20133
20134        try {
20135            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20136                    ps.appId, ceDataInodes, codePaths, stats);
20137
20138            // For now, ignore code size of packages on system partition
20139            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20140                stats.codeSize = 0;
20141            }
20142
20143            // External clients expect these to be tracked separately
20144            stats.dataSize -= stats.cacheSize;
20145
20146        } catch (InstallerException e) {
20147            Slog.w(TAG, String.valueOf(e));
20148            return false;
20149        }
20150
20151        return true;
20152    }
20153
20154    private int getUidTargetSdkVersionLockedLPr(int uid) {
20155        Object obj = mSettings.getUserIdLPr(uid);
20156        if (obj instanceof SharedUserSetting) {
20157            final SharedUserSetting sus = (SharedUserSetting) obj;
20158            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20159            final Iterator<PackageSetting> it = sus.packages.iterator();
20160            while (it.hasNext()) {
20161                final PackageSetting ps = it.next();
20162                if (ps.pkg != null) {
20163                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20164                    if (v < vers) vers = v;
20165                }
20166            }
20167            return vers;
20168        } else if (obj instanceof PackageSetting) {
20169            final PackageSetting ps = (PackageSetting) obj;
20170            if (ps.pkg != null) {
20171                return ps.pkg.applicationInfo.targetSdkVersion;
20172            }
20173        }
20174        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20175    }
20176
20177    @Override
20178    public void addPreferredActivity(IntentFilter filter, int match,
20179            ComponentName[] set, ComponentName activity, int userId) {
20180        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20181                "Adding preferred");
20182    }
20183
20184    private void addPreferredActivityInternal(IntentFilter filter, int match,
20185            ComponentName[] set, ComponentName activity, boolean always, int userId,
20186            String opname) {
20187        // writer
20188        int callingUid = Binder.getCallingUid();
20189        enforceCrossUserPermission(callingUid, userId,
20190                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20191        if (filter.countActions() == 0) {
20192            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20193            return;
20194        }
20195        synchronized (mPackages) {
20196            if (mContext.checkCallingOrSelfPermission(
20197                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20198                    != PackageManager.PERMISSION_GRANTED) {
20199                if (getUidTargetSdkVersionLockedLPr(callingUid)
20200                        < Build.VERSION_CODES.FROYO) {
20201                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20202                            + callingUid);
20203                    return;
20204                }
20205                mContext.enforceCallingOrSelfPermission(
20206                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20207            }
20208
20209            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20210            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20211                    + userId + ":");
20212            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20213            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20214            scheduleWritePackageRestrictionsLocked(userId);
20215            postPreferredActivityChangedBroadcast(userId);
20216        }
20217    }
20218
20219    private void postPreferredActivityChangedBroadcast(int userId) {
20220        mHandler.post(() -> {
20221            final IActivityManager am = ActivityManager.getService();
20222            if (am == null) {
20223                return;
20224            }
20225
20226            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20227            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20228            try {
20229                am.broadcastIntent(null, intent, null, null,
20230                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20231                        null, false, false, userId);
20232            } catch (RemoteException e) {
20233            }
20234        });
20235    }
20236
20237    @Override
20238    public void replacePreferredActivity(IntentFilter filter, int match,
20239            ComponentName[] set, ComponentName activity, int userId) {
20240        if (filter.countActions() != 1) {
20241            throw new IllegalArgumentException(
20242                    "replacePreferredActivity expects filter to have only 1 action.");
20243        }
20244        if (filter.countDataAuthorities() != 0
20245                || filter.countDataPaths() != 0
20246                || filter.countDataSchemes() > 1
20247                || filter.countDataTypes() != 0) {
20248            throw new IllegalArgumentException(
20249                    "replacePreferredActivity expects filter to have no data authorities, " +
20250                    "paths, or types; and at most one scheme.");
20251        }
20252
20253        final int callingUid = Binder.getCallingUid();
20254        enforceCrossUserPermission(callingUid, userId,
20255                true /* requireFullPermission */, false /* checkShell */,
20256                "replace preferred activity");
20257        synchronized (mPackages) {
20258            if (mContext.checkCallingOrSelfPermission(
20259                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20260                    != PackageManager.PERMISSION_GRANTED) {
20261                if (getUidTargetSdkVersionLockedLPr(callingUid)
20262                        < Build.VERSION_CODES.FROYO) {
20263                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20264                            + Binder.getCallingUid());
20265                    return;
20266                }
20267                mContext.enforceCallingOrSelfPermission(
20268                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20269            }
20270
20271            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20272            if (pir != null) {
20273                // Get all of the existing entries that exactly match this filter.
20274                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20275                if (existing != null && existing.size() == 1) {
20276                    PreferredActivity cur = existing.get(0);
20277                    if (DEBUG_PREFERRED) {
20278                        Slog.i(TAG, "Checking replace of preferred:");
20279                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20280                        if (!cur.mPref.mAlways) {
20281                            Slog.i(TAG, "  -- CUR; not mAlways!");
20282                        } else {
20283                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20284                            Slog.i(TAG, "  -- CUR: mSet="
20285                                    + Arrays.toString(cur.mPref.mSetComponents));
20286                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20287                            Slog.i(TAG, "  -- NEW: mMatch="
20288                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20289                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20290                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20291                        }
20292                    }
20293                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20294                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20295                            && cur.mPref.sameSet(set)) {
20296                        // Setting the preferred activity to what it happens to be already
20297                        if (DEBUG_PREFERRED) {
20298                            Slog.i(TAG, "Replacing with same preferred activity "
20299                                    + cur.mPref.mShortComponent + " for user "
20300                                    + userId + ":");
20301                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20302                        }
20303                        return;
20304                    }
20305                }
20306
20307                if (existing != null) {
20308                    if (DEBUG_PREFERRED) {
20309                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20310                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20311                    }
20312                    for (int i = 0; i < existing.size(); i++) {
20313                        PreferredActivity pa = existing.get(i);
20314                        if (DEBUG_PREFERRED) {
20315                            Slog.i(TAG, "Removing existing preferred activity "
20316                                    + pa.mPref.mComponent + ":");
20317                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20318                        }
20319                        pir.removeFilter(pa);
20320                    }
20321                }
20322            }
20323            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20324                    "Replacing preferred");
20325        }
20326    }
20327
20328    @Override
20329    public void clearPackagePreferredActivities(String packageName) {
20330        final int callingUid = Binder.getCallingUid();
20331        if (getInstantAppPackageName(callingUid) != null) {
20332            return;
20333        }
20334        // writer
20335        synchronized (mPackages) {
20336            PackageParser.Package pkg = mPackages.get(packageName);
20337            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20338                if (mContext.checkCallingOrSelfPermission(
20339                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20340                        != PackageManager.PERMISSION_GRANTED) {
20341                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20342                            < Build.VERSION_CODES.FROYO) {
20343                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20344                                + callingUid);
20345                        return;
20346                    }
20347                    mContext.enforceCallingOrSelfPermission(
20348                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20349                }
20350            }
20351            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20352            if (ps != null
20353                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20354                return;
20355            }
20356            int user = UserHandle.getCallingUserId();
20357            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20358                scheduleWritePackageRestrictionsLocked(user);
20359            }
20360        }
20361    }
20362
20363    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20364    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20365        ArrayList<PreferredActivity> removed = null;
20366        boolean changed = false;
20367        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20368            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20369            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20370            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20371                continue;
20372            }
20373            Iterator<PreferredActivity> it = pir.filterIterator();
20374            while (it.hasNext()) {
20375                PreferredActivity pa = it.next();
20376                // Mark entry for removal only if it matches the package name
20377                // and the entry is of type "always".
20378                if (packageName == null ||
20379                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20380                                && pa.mPref.mAlways)) {
20381                    if (removed == null) {
20382                        removed = new ArrayList<PreferredActivity>();
20383                    }
20384                    removed.add(pa);
20385                }
20386            }
20387            if (removed != null) {
20388                for (int j=0; j<removed.size(); j++) {
20389                    PreferredActivity pa = removed.get(j);
20390                    pir.removeFilter(pa);
20391                }
20392                changed = true;
20393            }
20394        }
20395        if (changed) {
20396            postPreferredActivityChangedBroadcast(userId);
20397        }
20398        return changed;
20399    }
20400
20401    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20402    private void clearIntentFilterVerificationsLPw(int userId) {
20403        final int packageCount = mPackages.size();
20404        for (int i = 0; i < packageCount; i++) {
20405            PackageParser.Package pkg = mPackages.valueAt(i);
20406            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20407        }
20408    }
20409
20410    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20411    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20412        if (userId == UserHandle.USER_ALL) {
20413            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20414                    sUserManager.getUserIds())) {
20415                for (int oneUserId : sUserManager.getUserIds()) {
20416                    scheduleWritePackageRestrictionsLocked(oneUserId);
20417                }
20418            }
20419        } else {
20420            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20421                scheduleWritePackageRestrictionsLocked(userId);
20422            }
20423        }
20424    }
20425
20426    /** Clears state for all users, and touches intent filter verification policy */
20427    void clearDefaultBrowserIfNeeded(String packageName) {
20428        for (int oneUserId : sUserManager.getUserIds()) {
20429            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20430        }
20431    }
20432
20433    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20434        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20435        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20436            if (packageName.equals(defaultBrowserPackageName)) {
20437                setDefaultBrowserPackageName(null, userId);
20438            }
20439        }
20440    }
20441
20442    @Override
20443    public void resetApplicationPreferences(int userId) {
20444        mContext.enforceCallingOrSelfPermission(
20445                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20446        final long identity = Binder.clearCallingIdentity();
20447        // writer
20448        try {
20449            synchronized (mPackages) {
20450                clearPackagePreferredActivitiesLPw(null, userId);
20451                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20452                // TODO: We have to reset the default SMS and Phone. This requires
20453                // significant refactoring to keep all default apps in the package
20454                // manager (cleaner but more work) or have the services provide
20455                // callbacks to the package manager to request a default app reset.
20456                applyFactoryDefaultBrowserLPw(userId);
20457                clearIntentFilterVerificationsLPw(userId);
20458                primeDomainVerificationsLPw(userId);
20459                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20460                scheduleWritePackageRestrictionsLocked(userId);
20461            }
20462            resetNetworkPolicies(userId);
20463        } finally {
20464            Binder.restoreCallingIdentity(identity);
20465        }
20466    }
20467
20468    @Override
20469    public int getPreferredActivities(List<IntentFilter> outFilters,
20470            List<ComponentName> outActivities, String packageName) {
20471        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20472            return 0;
20473        }
20474        int num = 0;
20475        final int userId = UserHandle.getCallingUserId();
20476        // reader
20477        synchronized (mPackages) {
20478            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20479            if (pir != null) {
20480                final Iterator<PreferredActivity> it = pir.filterIterator();
20481                while (it.hasNext()) {
20482                    final PreferredActivity pa = it.next();
20483                    if (packageName == null
20484                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20485                                    && pa.mPref.mAlways)) {
20486                        if (outFilters != null) {
20487                            outFilters.add(new IntentFilter(pa));
20488                        }
20489                        if (outActivities != null) {
20490                            outActivities.add(pa.mPref.mComponent);
20491                        }
20492                    }
20493                }
20494            }
20495        }
20496
20497        return num;
20498    }
20499
20500    @Override
20501    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20502            int userId) {
20503        int callingUid = Binder.getCallingUid();
20504        if (callingUid != Process.SYSTEM_UID) {
20505            throw new SecurityException(
20506                    "addPersistentPreferredActivity can only be run by the system");
20507        }
20508        if (filter.countActions() == 0) {
20509            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20510            return;
20511        }
20512        synchronized (mPackages) {
20513            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20514                    ":");
20515            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20516            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20517                    new PersistentPreferredActivity(filter, activity));
20518            scheduleWritePackageRestrictionsLocked(userId);
20519            postPreferredActivityChangedBroadcast(userId);
20520        }
20521    }
20522
20523    @Override
20524    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20525        int callingUid = Binder.getCallingUid();
20526        if (callingUid != Process.SYSTEM_UID) {
20527            throw new SecurityException(
20528                    "clearPackagePersistentPreferredActivities can only be run by the system");
20529        }
20530        ArrayList<PersistentPreferredActivity> removed = null;
20531        boolean changed = false;
20532        synchronized (mPackages) {
20533            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20534                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20535                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20536                        .valueAt(i);
20537                if (userId != thisUserId) {
20538                    continue;
20539                }
20540                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20541                while (it.hasNext()) {
20542                    PersistentPreferredActivity ppa = it.next();
20543                    // Mark entry for removal only if it matches the package name.
20544                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20545                        if (removed == null) {
20546                            removed = new ArrayList<PersistentPreferredActivity>();
20547                        }
20548                        removed.add(ppa);
20549                    }
20550                }
20551                if (removed != null) {
20552                    for (int j=0; j<removed.size(); j++) {
20553                        PersistentPreferredActivity ppa = removed.get(j);
20554                        ppir.removeFilter(ppa);
20555                    }
20556                    changed = true;
20557                }
20558            }
20559
20560            if (changed) {
20561                scheduleWritePackageRestrictionsLocked(userId);
20562                postPreferredActivityChangedBroadcast(userId);
20563            }
20564        }
20565    }
20566
20567    /**
20568     * Common machinery for picking apart a restored XML blob and passing
20569     * it to a caller-supplied functor to be applied to the running system.
20570     */
20571    private void restoreFromXml(XmlPullParser parser, int userId,
20572            String expectedStartTag, BlobXmlRestorer functor)
20573            throws IOException, XmlPullParserException {
20574        int type;
20575        while ((type = parser.next()) != XmlPullParser.START_TAG
20576                && type != XmlPullParser.END_DOCUMENT) {
20577        }
20578        if (type != XmlPullParser.START_TAG) {
20579            // oops didn't find a start tag?!
20580            if (DEBUG_BACKUP) {
20581                Slog.e(TAG, "Didn't find start tag during restore");
20582            }
20583            return;
20584        }
20585Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20586        // this is supposed to be TAG_PREFERRED_BACKUP
20587        if (!expectedStartTag.equals(parser.getName())) {
20588            if (DEBUG_BACKUP) {
20589                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20590            }
20591            return;
20592        }
20593
20594        // skip interfering stuff, then we're aligned with the backing implementation
20595        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20596Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20597        functor.apply(parser, userId);
20598    }
20599
20600    private interface BlobXmlRestorer {
20601        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20602    }
20603
20604    /**
20605     * Non-Binder method, support for the backup/restore mechanism: write the
20606     * full set of preferred activities in its canonical XML format.  Returns the
20607     * XML output as a byte array, or null if there is none.
20608     */
20609    @Override
20610    public byte[] getPreferredActivityBackup(int userId) {
20611        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20612            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20613        }
20614
20615        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20616        try {
20617            final XmlSerializer serializer = new FastXmlSerializer();
20618            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20619            serializer.startDocument(null, true);
20620            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20621
20622            synchronized (mPackages) {
20623                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20624            }
20625
20626            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20627            serializer.endDocument();
20628            serializer.flush();
20629        } catch (Exception e) {
20630            if (DEBUG_BACKUP) {
20631                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20632            }
20633            return null;
20634        }
20635
20636        return dataStream.toByteArray();
20637    }
20638
20639    @Override
20640    public void restorePreferredActivities(byte[] backup, int userId) {
20641        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20642            throw new SecurityException("Only the system may call restorePreferredActivities()");
20643        }
20644
20645        try {
20646            final XmlPullParser parser = Xml.newPullParser();
20647            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20648            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20649                    new BlobXmlRestorer() {
20650                        @Override
20651                        public void apply(XmlPullParser parser, int userId)
20652                                throws XmlPullParserException, IOException {
20653                            synchronized (mPackages) {
20654                                mSettings.readPreferredActivitiesLPw(parser, userId);
20655                            }
20656                        }
20657                    } );
20658        } catch (Exception e) {
20659            if (DEBUG_BACKUP) {
20660                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20661            }
20662        }
20663    }
20664
20665    /**
20666     * Non-Binder method, support for the backup/restore mechanism: write the
20667     * default browser (etc) settings in its canonical XML format.  Returns the default
20668     * browser XML representation as a byte array, or null if there is none.
20669     */
20670    @Override
20671    public byte[] getDefaultAppsBackup(int userId) {
20672        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20673            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20674        }
20675
20676        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20677        try {
20678            final XmlSerializer serializer = new FastXmlSerializer();
20679            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20680            serializer.startDocument(null, true);
20681            serializer.startTag(null, TAG_DEFAULT_APPS);
20682
20683            synchronized (mPackages) {
20684                mSettings.writeDefaultAppsLPr(serializer, userId);
20685            }
20686
20687            serializer.endTag(null, TAG_DEFAULT_APPS);
20688            serializer.endDocument();
20689            serializer.flush();
20690        } catch (Exception e) {
20691            if (DEBUG_BACKUP) {
20692                Slog.e(TAG, "Unable to write default apps for backup", e);
20693            }
20694            return null;
20695        }
20696
20697        return dataStream.toByteArray();
20698    }
20699
20700    @Override
20701    public void restoreDefaultApps(byte[] backup, int userId) {
20702        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20703            throw new SecurityException("Only the system may call restoreDefaultApps()");
20704        }
20705
20706        try {
20707            final XmlPullParser parser = Xml.newPullParser();
20708            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20709            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20710                    new BlobXmlRestorer() {
20711                        @Override
20712                        public void apply(XmlPullParser parser, int userId)
20713                                throws XmlPullParserException, IOException {
20714                            synchronized (mPackages) {
20715                                mSettings.readDefaultAppsLPw(parser, userId);
20716                            }
20717                        }
20718                    } );
20719        } catch (Exception e) {
20720            if (DEBUG_BACKUP) {
20721                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20722            }
20723        }
20724    }
20725
20726    @Override
20727    public byte[] getIntentFilterVerificationBackup(int userId) {
20728        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20729            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20730        }
20731
20732        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20733        try {
20734            final XmlSerializer serializer = new FastXmlSerializer();
20735            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20736            serializer.startDocument(null, true);
20737            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20738
20739            synchronized (mPackages) {
20740                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20741            }
20742
20743            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20744            serializer.endDocument();
20745            serializer.flush();
20746        } catch (Exception e) {
20747            if (DEBUG_BACKUP) {
20748                Slog.e(TAG, "Unable to write default apps for backup", e);
20749            }
20750            return null;
20751        }
20752
20753        return dataStream.toByteArray();
20754    }
20755
20756    @Override
20757    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20758        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20759            throw new SecurityException("Only the system may call restorePreferredActivities()");
20760        }
20761
20762        try {
20763            final XmlPullParser parser = Xml.newPullParser();
20764            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20765            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20766                    new BlobXmlRestorer() {
20767                        @Override
20768                        public void apply(XmlPullParser parser, int userId)
20769                                throws XmlPullParserException, IOException {
20770                            synchronized (mPackages) {
20771                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20772                                mSettings.writeLPr();
20773                            }
20774                        }
20775                    } );
20776        } catch (Exception e) {
20777            if (DEBUG_BACKUP) {
20778                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20779            }
20780        }
20781    }
20782
20783    @Override
20784    public byte[] getPermissionGrantBackup(int userId) {
20785        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20786            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20787        }
20788
20789        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20790        try {
20791            final XmlSerializer serializer = new FastXmlSerializer();
20792            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20793            serializer.startDocument(null, true);
20794            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20795
20796            synchronized (mPackages) {
20797                serializeRuntimePermissionGrantsLPr(serializer, userId);
20798            }
20799
20800            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20801            serializer.endDocument();
20802            serializer.flush();
20803        } catch (Exception e) {
20804            if (DEBUG_BACKUP) {
20805                Slog.e(TAG, "Unable to write default apps for backup", e);
20806            }
20807            return null;
20808        }
20809
20810        return dataStream.toByteArray();
20811    }
20812
20813    @Override
20814    public void restorePermissionGrants(byte[] backup, int userId) {
20815        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20816            throw new SecurityException("Only the system may call restorePermissionGrants()");
20817        }
20818
20819        try {
20820            final XmlPullParser parser = Xml.newPullParser();
20821            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20822            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20823                    new BlobXmlRestorer() {
20824                        @Override
20825                        public void apply(XmlPullParser parser, int userId)
20826                                throws XmlPullParserException, IOException {
20827                            synchronized (mPackages) {
20828                                processRestoredPermissionGrantsLPr(parser, userId);
20829                            }
20830                        }
20831                    } );
20832        } catch (Exception e) {
20833            if (DEBUG_BACKUP) {
20834                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20835            }
20836        }
20837    }
20838
20839    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20840            throws IOException {
20841        serializer.startTag(null, TAG_ALL_GRANTS);
20842
20843        final int N = mSettings.mPackages.size();
20844        for (int i = 0; i < N; i++) {
20845            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20846            boolean pkgGrantsKnown = false;
20847
20848            PermissionsState packagePerms = ps.getPermissionsState();
20849
20850            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20851                final int grantFlags = state.getFlags();
20852                // only look at grants that are not system/policy fixed
20853                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20854                    final boolean isGranted = state.isGranted();
20855                    // And only back up the user-twiddled state bits
20856                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20857                        final String packageName = mSettings.mPackages.keyAt(i);
20858                        if (!pkgGrantsKnown) {
20859                            serializer.startTag(null, TAG_GRANT);
20860                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20861                            pkgGrantsKnown = true;
20862                        }
20863
20864                        final boolean userSet =
20865                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20866                        final boolean userFixed =
20867                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20868                        final boolean revoke =
20869                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20870
20871                        serializer.startTag(null, TAG_PERMISSION);
20872                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20873                        if (isGranted) {
20874                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20875                        }
20876                        if (userSet) {
20877                            serializer.attribute(null, ATTR_USER_SET, "true");
20878                        }
20879                        if (userFixed) {
20880                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20881                        }
20882                        if (revoke) {
20883                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20884                        }
20885                        serializer.endTag(null, TAG_PERMISSION);
20886                    }
20887                }
20888            }
20889
20890            if (pkgGrantsKnown) {
20891                serializer.endTag(null, TAG_GRANT);
20892            }
20893        }
20894
20895        serializer.endTag(null, TAG_ALL_GRANTS);
20896    }
20897
20898    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20899            throws XmlPullParserException, IOException {
20900        String pkgName = null;
20901        int outerDepth = parser.getDepth();
20902        int type;
20903        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20904                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20905            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20906                continue;
20907            }
20908
20909            final String tagName = parser.getName();
20910            if (tagName.equals(TAG_GRANT)) {
20911                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20912                if (DEBUG_BACKUP) {
20913                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20914                }
20915            } else if (tagName.equals(TAG_PERMISSION)) {
20916
20917                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20918                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20919
20920                int newFlagSet = 0;
20921                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20922                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20923                }
20924                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20925                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20926                }
20927                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20928                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20929                }
20930                if (DEBUG_BACKUP) {
20931                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20932                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20933                }
20934                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20935                if (ps != null) {
20936                    // Already installed so we apply the grant immediately
20937                    if (DEBUG_BACKUP) {
20938                        Slog.v(TAG, "        + already installed; applying");
20939                    }
20940                    PermissionsState perms = ps.getPermissionsState();
20941                    BasePermission bp = mSettings.mPermissions.get(permName);
20942                    if (bp != null) {
20943                        if (isGranted) {
20944                            perms.grantRuntimePermission(bp, userId);
20945                        }
20946                        if (newFlagSet != 0) {
20947                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20948                        }
20949                    }
20950                } else {
20951                    // Need to wait for post-restore install to apply the grant
20952                    if (DEBUG_BACKUP) {
20953                        Slog.v(TAG, "        - not yet installed; saving for later");
20954                    }
20955                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20956                            isGranted, newFlagSet, userId);
20957                }
20958            } else {
20959                PackageManagerService.reportSettingsProblem(Log.WARN,
20960                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20961                XmlUtils.skipCurrentTag(parser);
20962            }
20963        }
20964
20965        scheduleWriteSettingsLocked();
20966        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20967    }
20968
20969    @Override
20970    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20971            int sourceUserId, int targetUserId, int flags) {
20972        mContext.enforceCallingOrSelfPermission(
20973                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20974        int callingUid = Binder.getCallingUid();
20975        enforceOwnerRights(ownerPackage, callingUid);
20976        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20977        if (intentFilter.countActions() == 0) {
20978            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20979            return;
20980        }
20981        synchronized (mPackages) {
20982            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20983                    ownerPackage, targetUserId, flags);
20984            CrossProfileIntentResolver resolver =
20985                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20986            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20987            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20988            if (existing != null) {
20989                int size = existing.size();
20990                for (int i = 0; i < size; i++) {
20991                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20992                        return;
20993                    }
20994                }
20995            }
20996            resolver.addFilter(newFilter);
20997            scheduleWritePackageRestrictionsLocked(sourceUserId);
20998        }
20999    }
21000
21001    @Override
21002    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21003        mContext.enforceCallingOrSelfPermission(
21004                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21005        final int callingUid = Binder.getCallingUid();
21006        enforceOwnerRights(ownerPackage, callingUid);
21007        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21008        synchronized (mPackages) {
21009            CrossProfileIntentResolver resolver =
21010                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21011            ArraySet<CrossProfileIntentFilter> set =
21012                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21013            for (CrossProfileIntentFilter filter : set) {
21014                if (filter.getOwnerPackage().equals(ownerPackage)) {
21015                    resolver.removeFilter(filter);
21016                }
21017            }
21018            scheduleWritePackageRestrictionsLocked(sourceUserId);
21019        }
21020    }
21021
21022    // Enforcing that callingUid is owning pkg on userId
21023    private void enforceOwnerRights(String pkg, int callingUid) {
21024        // The system owns everything.
21025        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21026            return;
21027        }
21028        final int callingUserId = UserHandle.getUserId(callingUid);
21029        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21030        if (pi == null) {
21031            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21032                    + callingUserId);
21033        }
21034        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21035            throw new SecurityException("Calling uid " + callingUid
21036                    + " does not own package " + pkg);
21037        }
21038    }
21039
21040    @Override
21041    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21042        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21043            return null;
21044        }
21045        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21046    }
21047
21048    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21049        UserManagerService ums = UserManagerService.getInstance();
21050        if (ums != null) {
21051            final UserInfo parent = ums.getProfileParent(userId);
21052            final int launcherUid = (parent != null) ? parent.id : userId;
21053            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21054            if (launcherComponent != null) {
21055                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21056                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21057                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21058                        .setPackage(launcherComponent.getPackageName());
21059                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21060            }
21061        }
21062    }
21063
21064    /**
21065     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21066     * then reports the most likely home activity or null if there are more than one.
21067     */
21068    private ComponentName getDefaultHomeActivity(int userId) {
21069        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21070        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21071        if (cn != null) {
21072            return cn;
21073        }
21074
21075        // Find the launcher with the highest priority and return that component if there are no
21076        // other home activity with the same priority.
21077        int lastPriority = Integer.MIN_VALUE;
21078        ComponentName lastComponent = null;
21079        final int size = allHomeCandidates.size();
21080        for (int i = 0; i < size; i++) {
21081            final ResolveInfo ri = allHomeCandidates.get(i);
21082            if (ri.priority > lastPriority) {
21083                lastComponent = ri.activityInfo.getComponentName();
21084                lastPriority = ri.priority;
21085            } else if (ri.priority == lastPriority) {
21086                // Two components found with same priority.
21087                lastComponent = null;
21088            }
21089        }
21090        return lastComponent;
21091    }
21092
21093    private Intent getHomeIntent() {
21094        Intent intent = new Intent(Intent.ACTION_MAIN);
21095        intent.addCategory(Intent.CATEGORY_HOME);
21096        intent.addCategory(Intent.CATEGORY_DEFAULT);
21097        return intent;
21098    }
21099
21100    private IntentFilter getHomeFilter() {
21101        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21102        filter.addCategory(Intent.CATEGORY_HOME);
21103        filter.addCategory(Intent.CATEGORY_DEFAULT);
21104        return filter;
21105    }
21106
21107    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21108            int userId) {
21109        Intent intent  = getHomeIntent();
21110        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21111                PackageManager.GET_META_DATA, userId);
21112        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21113                true, false, false, userId);
21114
21115        allHomeCandidates.clear();
21116        if (list != null) {
21117            for (ResolveInfo ri : list) {
21118                allHomeCandidates.add(ri);
21119            }
21120        }
21121        return (preferred == null || preferred.activityInfo == null)
21122                ? null
21123                : new ComponentName(preferred.activityInfo.packageName,
21124                        preferred.activityInfo.name);
21125    }
21126
21127    @Override
21128    public void setHomeActivity(ComponentName comp, int userId) {
21129        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21130            return;
21131        }
21132        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21133        getHomeActivitiesAsUser(homeActivities, userId);
21134
21135        boolean found = false;
21136
21137        final int size = homeActivities.size();
21138        final ComponentName[] set = new ComponentName[size];
21139        for (int i = 0; i < size; i++) {
21140            final ResolveInfo candidate = homeActivities.get(i);
21141            final ActivityInfo info = candidate.activityInfo;
21142            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21143            set[i] = activityName;
21144            if (!found && activityName.equals(comp)) {
21145                found = true;
21146            }
21147        }
21148        if (!found) {
21149            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21150                    + userId);
21151        }
21152        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21153                set, comp, userId);
21154    }
21155
21156    private @Nullable String getSetupWizardPackageName() {
21157        final Intent intent = new Intent(Intent.ACTION_MAIN);
21158        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21159
21160        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21161                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21162                        | MATCH_DISABLED_COMPONENTS,
21163                UserHandle.myUserId());
21164        if (matches.size() == 1) {
21165            return matches.get(0).getComponentInfo().packageName;
21166        } else {
21167            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21168                    + ": matches=" + matches);
21169            return null;
21170        }
21171    }
21172
21173    private @Nullable String getStorageManagerPackageName() {
21174        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21175
21176        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21177                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21178                        | MATCH_DISABLED_COMPONENTS,
21179                UserHandle.myUserId());
21180        if (matches.size() == 1) {
21181            return matches.get(0).getComponentInfo().packageName;
21182        } else {
21183            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21184                    + matches.size() + ": matches=" + matches);
21185            return null;
21186        }
21187    }
21188
21189    @Override
21190    public void setApplicationEnabledSetting(String appPackageName,
21191            int newState, int flags, int userId, String callingPackage) {
21192        if (!sUserManager.exists(userId)) return;
21193        if (callingPackage == null) {
21194            callingPackage = Integer.toString(Binder.getCallingUid());
21195        }
21196        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21197    }
21198
21199    @Override
21200    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21201        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21202        synchronized (mPackages) {
21203            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21204            if (pkgSetting != null) {
21205                pkgSetting.setUpdateAvailable(updateAvailable);
21206            }
21207        }
21208    }
21209
21210    @Override
21211    public void setComponentEnabledSetting(ComponentName componentName,
21212            int newState, int flags, int userId) {
21213        if (!sUserManager.exists(userId)) return;
21214        setEnabledSetting(componentName.getPackageName(),
21215                componentName.getClassName(), newState, flags, userId, null);
21216    }
21217
21218    private void setEnabledSetting(final String packageName, String className, int newState,
21219            final int flags, int userId, String callingPackage) {
21220        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21221              || newState == COMPONENT_ENABLED_STATE_ENABLED
21222              || newState == COMPONENT_ENABLED_STATE_DISABLED
21223              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21224              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21225            throw new IllegalArgumentException("Invalid new component state: "
21226                    + newState);
21227        }
21228        PackageSetting pkgSetting;
21229        final int callingUid = Binder.getCallingUid();
21230        final int permission;
21231        if (callingUid == Process.SYSTEM_UID) {
21232            permission = PackageManager.PERMISSION_GRANTED;
21233        } else {
21234            permission = mContext.checkCallingOrSelfPermission(
21235                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21236        }
21237        enforceCrossUserPermission(callingUid, userId,
21238                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21239        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21240        boolean sendNow = false;
21241        boolean isApp = (className == null);
21242        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21243        String componentName = isApp ? packageName : className;
21244        int packageUid = -1;
21245        ArrayList<String> components;
21246
21247        // reader
21248        synchronized (mPackages) {
21249            pkgSetting = mSettings.mPackages.get(packageName);
21250            if (pkgSetting == null) {
21251                if (!isCallerInstantApp) {
21252                    if (className == null) {
21253                        throw new IllegalArgumentException("Unknown package: " + packageName);
21254                    }
21255                    throw new IllegalArgumentException(
21256                            "Unknown component: " + packageName + "/" + className);
21257                } else {
21258                    // throw SecurityException to prevent leaking package information
21259                    throw new SecurityException(
21260                            "Attempt to change component state; "
21261                            + "pid=" + Binder.getCallingPid()
21262                            + ", uid=" + callingUid
21263                            + (className == null
21264                                    ? ", package=" + packageName
21265                                    : ", component=" + packageName + "/" + className));
21266                }
21267            }
21268        }
21269
21270        // Limit who can change which apps
21271        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21272            // Don't allow apps that don't have permission to modify other apps
21273            if (!allowedByPermission
21274                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21275                throw new SecurityException(
21276                        "Attempt to change component state; "
21277                        + "pid=" + Binder.getCallingPid()
21278                        + ", uid=" + callingUid
21279                        + (className == null
21280                                ? ", package=" + packageName
21281                                : ", component=" + packageName + "/" + className));
21282            }
21283            // Don't allow changing protected packages.
21284            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21285                throw new SecurityException("Cannot disable a protected package: " + packageName);
21286            }
21287        }
21288
21289        synchronized (mPackages) {
21290            if (callingUid == Process.SHELL_UID
21291                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21292                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21293                // unless it is a test package.
21294                int oldState = pkgSetting.getEnabled(userId);
21295                if (className == null
21296                    &&
21297                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21298                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21299                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21300                    &&
21301                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21302                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21303                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21304                    // ok
21305                } else {
21306                    throw new SecurityException(
21307                            "Shell cannot change component state for " + packageName + "/"
21308                            + className + " to " + newState);
21309                }
21310            }
21311            if (className == null) {
21312                // We're dealing with an application/package level state change
21313                if (pkgSetting.getEnabled(userId) == newState) {
21314                    // Nothing to do
21315                    return;
21316                }
21317                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21318                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21319                    // Don't care about who enables an app.
21320                    callingPackage = null;
21321                }
21322                pkgSetting.setEnabled(newState, userId, callingPackage);
21323                // pkgSetting.pkg.mSetEnabled = newState;
21324            } else {
21325                // We're dealing with a component level state change
21326                // First, verify that this is a valid class name.
21327                PackageParser.Package pkg = pkgSetting.pkg;
21328                if (pkg == null || !pkg.hasComponentClassName(className)) {
21329                    if (pkg != null &&
21330                            pkg.applicationInfo.targetSdkVersion >=
21331                                    Build.VERSION_CODES.JELLY_BEAN) {
21332                        throw new IllegalArgumentException("Component class " + className
21333                                + " does not exist in " + packageName);
21334                    } else {
21335                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21336                                + className + " does not exist in " + packageName);
21337                    }
21338                }
21339                switch (newState) {
21340                case COMPONENT_ENABLED_STATE_ENABLED:
21341                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21342                        return;
21343                    }
21344                    break;
21345                case COMPONENT_ENABLED_STATE_DISABLED:
21346                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21347                        return;
21348                    }
21349                    break;
21350                case COMPONENT_ENABLED_STATE_DEFAULT:
21351                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21352                        return;
21353                    }
21354                    break;
21355                default:
21356                    Slog.e(TAG, "Invalid new component state: " + newState);
21357                    return;
21358                }
21359            }
21360            scheduleWritePackageRestrictionsLocked(userId);
21361            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21362            final long callingId = Binder.clearCallingIdentity();
21363            try {
21364                updateInstantAppInstallerLocked(packageName);
21365            } finally {
21366                Binder.restoreCallingIdentity(callingId);
21367            }
21368            components = mPendingBroadcasts.get(userId, packageName);
21369            final boolean newPackage = components == null;
21370            if (newPackage) {
21371                components = new ArrayList<String>();
21372            }
21373            if (!components.contains(componentName)) {
21374                components.add(componentName);
21375            }
21376            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21377                sendNow = true;
21378                // Purge entry from pending broadcast list if another one exists already
21379                // since we are sending one right away.
21380                mPendingBroadcasts.remove(userId, packageName);
21381            } else {
21382                if (newPackage) {
21383                    mPendingBroadcasts.put(userId, packageName, components);
21384                }
21385                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21386                    // Schedule a message
21387                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21388                }
21389            }
21390        }
21391
21392        long callingId = Binder.clearCallingIdentity();
21393        try {
21394            if (sendNow) {
21395                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21396                sendPackageChangedBroadcast(packageName,
21397                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21398            }
21399        } finally {
21400            Binder.restoreCallingIdentity(callingId);
21401        }
21402    }
21403
21404    @Override
21405    public void flushPackageRestrictionsAsUser(int userId) {
21406        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21407            return;
21408        }
21409        if (!sUserManager.exists(userId)) {
21410            return;
21411        }
21412        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21413                false /* checkShell */, "flushPackageRestrictions");
21414        synchronized (mPackages) {
21415            mSettings.writePackageRestrictionsLPr(userId);
21416            mDirtyUsers.remove(userId);
21417            if (mDirtyUsers.isEmpty()) {
21418                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21419            }
21420        }
21421    }
21422
21423    private void sendPackageChangedBroadcast(String packageName,
21424            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21425        if (DEBUG_INSTALL)
21426            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21427                    + componentNames);
21428        Bundle extras = new Bundle(4);
21429        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21430        String nameList[] = new String[componentNames.size()];
21431        componentNames.toArray(nameList);
21432        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21433        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21434        extras.putInt(Intent.EXTRA_UID, packageUid);
21435        // If this is not reporting a change of the overall package, then only send it
21436        // to registered receivers.  We don't want to launch a swath of apps for every
21437        // little component state change.
21438        final int flags = !componentNames.contains(packageName)
21439                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21440        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21441                new int[] {UserHandle.getUserId(packageUid)});
21442    }
21443
21444    @Override
21445    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21446        if (!sUserManager.exists(userId)) return;
21447        final int callingUid = Binder.getCallingUid();
21448        if (getInstantAppPackageName(callingUid) != null) {
21449            return;
21450        }
21451        final int permission = mContext.checkCallingOrSelfPermission(
21452                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21453        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21454        enforceCrossUserPermission(callingUid, userId,
21455                true /* requireFullPermission */, true /* checkShell */, "stop package");
21456        // writer
21457        synchronized (mPackages) {
21458            final PackageSetting ps = mSettings.mPackages.get(packageName);
21459            if (!filterAppAccessLPr(ps, callingUid, userId)
21460                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21461                            allowedByPermission, callingUid, userId)) {
21462                scheduleWritePackageRestrictionsLocked(userId);
21463            }
21464        }
21465    }
21466
21467    @Override
21468    public String getInstallerPackageName(String packageName) {
21469        final int callingUid = Binder.getCallingUid();
21470        if (getInstantAppPackageName(callingUid) != null) {
21471            return null;
21472        }
21473        // reader
21474        synchronized (mPackages) {
21475            final PackageSetting ps = mSettings.mPackages.get(packageName);
21476            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21477                return null;
21478            }
21479            return mSettings.getInstallerPackageNameLPr(packageName);
21480        }
21481    }
21482
21483    public boolean isOrphaned(String packageName) {
21484        // reader
21485        synchronized (mPackages) {
21486            return mSettings.isOrphaned(packageName);
21487        }
21488    }
21489
21490    @Override
21491    public int getApplicationEnabledSetting(String packageName, int userId) {
21492        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21493        int callingUid = Binder.getCallingUid();
21494        enforceCrossUserPermission(callingUid, userId,
21495                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21496        // reader
21497        synchronized (mPackages) {
21498            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21499                return COMPONENT_ENABLED_STATE_DISABLED;
21500            }
21501            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21502        }
21503    }
21504
21505    @Override
21506    public int getComponentEnabledSetting(ComponentName component, int userId) {
21507        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21508        int callingUid = Binder.getCallingUid();
21509        enforceCrossUserPermission(callingUid, userId,
21510                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21511        synchronized (mPackages) {
21512            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21513                    component, TYPE_UNKNOWN, userId)) {
21514                return COMPONENT_ENABLED_STATE_DISABLED;
21515            }
21516            return mSettings.getComponentEnabledSettingLPr(component, userId);
21517        }
21518    }
21519
21520    @Override
21521    public void enterSafeMode() {
21522        enforceSystemOrRoot("Only the system can request entering safe mode");
21523
21524        if (!mSystemReady) {
21525            mSafeMode = true;
21526        }
21527    }
21528
21529    @Override
21530    public void systemReady() {
21531        enforceSystemOrRoot("Only the system can claim the system is ready");
21532
21533        mSystemReady = true;
21534        final ContentResolver resolver = mContext.getContentResolver();
21535        ContentObserver co = new ContentObserver(mHandler) {
21536            @Override
21537            public void onChange(boolean selfChange) {
21538                mEphemeralAppsDisabled =
21539                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21540                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21541            }
21542        };
21543        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21544                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21545                false, co, UserHandle.USER_SYSTEM);
21546        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21547                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21548        co.onChange(true);
21549
21550        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21551        // disabled after already being started.
21552        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21553                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21554
21555        // Read the compatibilty setting when the system is ready.
21556        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21557                mContext.getContentResolver(),
21558                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21559        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21560        if (DEBUG_SETTINGS) {
21561            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21562        }
21563
21564        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21565
21566        synchronized (mPackages) {
21567            // Verify that all of the preferred activity components actually
21568            // exist.  It is possible for applications to be updated and at
21569            // that point remove a previously declared activity component that
21570            // had been set as a preferred activity.  We try to clean this up
21571            // the next time we encounter that preferred activity, but it is
21572            // possible for the user flow to never be able to return to that
21573            // situation so here we do a sanity check to make sure we haven't
21574            // left any junk around.
21575            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21576            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21577                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21578                removed.clear();
21579                for (PreferredActivity pa : pir.filterSet()) {
21580                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21581                        removed.add(pa);
21582                    }
21583                }
21584                if (removed.size() > 0) {
21585                    for (int r=0; r<removed.size(); r++) {
21586                        PreferredActivity pa = removed.get(r);
21587                        Slog.w(TAG, "Removing dangling preferred activity: "
21588                                + pa.mPref.mComponent);
21589                        pir.removeFilter(pa);
21590                    }
21591                    mSettings.writePackageRestrictionsLPr(
21592                            mSettings.mPreferredActivities.keyAt(i));
21593                }
21594            }
21595
21596            for (int userId : UserManagerService.getInstance().getUserIds()) {
21597                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21598                    grantPermissionsUserIds = ArrayUtils.appendInt(
21599                            grantPermissionsUserIds, userId);
21600                }
21601            }
21602        }
21603        sUserManager.systemReady();
21604
21605        // If we upgraded grant all default permissions before kicking off.
21606        for (int userId : grantPermissionsUserIds) {
21607            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21608        }
21609
21610        // If we did not grant default permissions, we preload from this the
21611        // default permission exceptions lazily to ensure we don't hit the
21612        // disk on a new user creation.
21613        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21614            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21615        }
21616
21617        // Kick off any messages waiting for system ready
21618        if (mPostSystemReadyMessages != null) {
21619            for (Message msg : mPostSystemReadyMessages) {
21620                msg.sendToTarget();
21621            }
21622            mPostSystemReadyMessages = null;
21623        }
21624
21625        // Watch for external volumes that come and go over time
21626        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21627        storage.registerListener(mStorageListener);
21628
21629        mInstallerService.systemReady();
21630        mPackageDexOptimizer.systemReady();
21631
21632        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21633                StorageManagerInternal.class);
21634        StorageManagerInternal.addExternalStoragePolicy(
21635                new StorageManagerInternal.ExternalStorageMountPolicy() {
21636            @Override
21637            public int getMountMode(int uid, String packageName) {
21638                if (Process.isIsolated(uid)) {
21639                    return Zygote.MOUNT_EXTERNAL_NONE;
21640                }
21641                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21642                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21643                }
21644                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21645                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21646                }
21647                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21648                    return Zygote.MOUNT_EXTERNAL_READ;
21649                }
21650                return Zygote.MOUNT_EXTERNAL_WRITE;
21651            }
21652
21653            @Override
21654            public boolean hasExternalStorage(int uid, String packageName) {
21655                return true;
21656            }
21657        });
21658
21659        // Now that we're mostly running, clean up stale users and apps
21660        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21661        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21662
21663        if (mPrivappPermissionsViolations != null) {
21664            Slog.wtf(TAG,"Signature|privileged permissions not in "
21665                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21666            mPrivappPermissionsViolations = null;
21667        }
21668    }
21669
21670    public void waitForAppDataPrepared() {
21671        if (mPrepareAppDataFuture == null) {
21672            return;
21673        }
21674        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21675        mPrepareAppDataFuture = null;
21676    }
21677
21678    @Override
21679    public boolean isSafeMode() {
21680        // allow instant applications
21681        return mSafeMode;
21682    }
21683
21684    @Override
21685    public boolean hasSystemUidErrors() {
21686        // allow instant applications
21687        return mHasSystemUidErrors;
21688    }
21689
21690    static String arrayToString(int[] array) {
21691        StringBuffer buf = new StringBuffer(128);
21692        buf.append('[');
21693        if (array != null) {
21694            for (int i=0; i<array.length; i++) {
21695                if (i > 0) buf.append(", ");
21696                buf.append(array[i]);
21697            }
21698        }
21699        buf.append(']');
21700        return buf.toString();
21701    }
21702
21703    static class DumpState {
21704        public static final int DUMP_LIBS = 1 << 0;
21705        public static final int DUMP_FEATURES = 1 << 1;
21706        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21707        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21708        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21709        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21710        public static final int DUMP_PERMISSIONS = 1 << 6;
21711        public static final int DUMP_PACKAGES = 1 << 7;
21712        public static final int DUMP_SHARED_USERS = 1 << 8;
21713        public static final int DUMP_MESSAGES = 1 << 9;
21714        public static final int DUMP_PROVIDERS = 1 << 10;
21715        public static final int DUMP_VERIFIERS = 1 << 11;
21716        public static final int DUMP_PREFERRED = 1 << 12;
21717        public static final int DUMP_PREFERRED_XML = 1 << 13;
21718        public static final int DUMP_KEYSETS = 1 << 14;
21719        public static final int DUMP_VERSION = 1 << 15;
21720        public static final int DUMP_INSTALLS = 1 << 16;
21721        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21722        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21723        public static final int DUMP_FROZEN = 1 << 19;
21724        public static final int DUMP_DEXOPT = 1 << 20;
21725        public static final int DUMP_COMPILER_STATS = 1 << 21;
21726        public static final int DUMP_CHANGES = 1 << 22;
21727        public static final int DUMP_VOLUMES = 1 << 23;
21728
21729        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21730
21731        private int mTypes;
21732
21733        private int mOptions;
21734
21735        private boolean mTitlePrinted;
21736
21737        private SharedUserSetting mSharedUser;
21738
21739        public boolean isDumping(int type) {
21740            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21741                return true;
21742            }
21743
21744            return (mTypes & type) != 0;
21745        }
21746
21747        public void setDump(int type) {
21748            mTypes |= type;
21749        }
21750
21751        public boolean isOptionEnabled(int option) {
21752            return (mOptions & option) != 0;
21753        }
21754
21755        public void setOptionEnabled(int option) {
21756            mOptions |= option;
21757        }
21758
21759        public boolean onTitlePrinted() {
21760            final boolean printed = mTitlePrinted;
21761            mTitlePrinted = true;
21762            return printed;
21763        }
21764
21765        public boolean getTitlePrinted() {
21766            return mTitlePrinted;
21767        }
21768
21769        public void setTitlePrinted(boolean enabled) {
21770            mTitlePrinted = enabled;
21771        }
21772
21773        public SharedUserSetting getSharedUser() {
21774            return mSharedUser;
21775        }
21776
21777        public void setSharedUser(SharedUserSetting user) {
21778            mSharedUser = user;
21779        }
21780    }
21781
21782    @Override
21783    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21784            FileDescriptor err, String[] args, ShellCallback callback,
21785            ResultReceiver resultReceiver) {
21786        (new PackageManagerShellCommand(this)).exec(
21787                this, in, out, err, args, callback, resultReceiver);
21788    }
21789
21790    @Override
21791    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21792        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21793
21794        DumpState dumpState = new DumpState();
21795        boolean fullPreferred = false;
21796        boolean checkin = false;
21797
21798        String packageName = null;
21799        ArraySet<String> permissionNames = null;
21800
21801        int opti = 0;
21802        while (opti < args.length) {
21803            String opt = args[opti];
21804            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21805                break;
21806            }
21807            opti++;
21808
21809            if ("-a".equals(opt)) {
21810                // Right now we only know how to print all.
21811            } else if ("-h".equals(opt)) {
21812                pw.println("Package manager dump options:");
21813                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21814                pw.println("    --checkin: dump for a checkin");
21815                pw.println("    -f: print details of intent filters");
21816                pw.println("    -h: print this help");
21817                pw.println("  cmd may be one of:");
21818                pw.println("    l[ibraries]: list known shared libraries");
21819                pw.println("    f[eatures]: list device features");
21820                pw.println("    k[eysets]: print known keysets");
21821                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21822                pw.println("    perm[issions]: dump permissions");
21823                pw.println("    permission [name ...]: dump declaration and use of given permission");
21824                pw.println("    pref[erred]: print preferred package settings");
21825                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21826                pw.println("    prov[iders]: dump content providers");
21827                pw.println("    p[ackages]: dump installed packages");
21828                pw.println("    s[hared-users]: dump shared user IDs");
21829                pw.println("    m[essages]: print collected runtime messages");
21830                pw.println("    v[erifiers]: print package verifier info");
21831                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21832                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21833                pw.println("    version: print database version info");
21834                pw.println("    write: write current settings now");
21835                pw.println("    installs: details about install sessions");
21836                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21837                pw.println("    dexopt: dump dexopt state");
21838                pw.println("    compiler-stats: dump compiler statistics");
21839                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21840                pw.println("    <package.name>: info about given package");
21841                return;
21842            } else if ("--checkin".equals(opt)) {
21843                checkin = true;
21844            } else if ("-f".equals(opt)) {
21845                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21846            } else if ("--proto".equals(opt)) {
21847                dumpProto(fd);
21848                return;
21849            } else {
21850                pw.println("Unknown argument: " + opt + "; use -h for help");
21851            }
21852        }
21853
21854        // Is the caller requesting to dump a particular piece of data?
21855        if (opti < args.length) {
21856            String cmd = args[opti];
21857            opti++;
21858            // Is this a package name?
21859            if ("android".equals(cmd) || cmd.contains(".")) {
21860                packageName = cmd;
21861                // When dumping a single package, we always dump all of its
21862                // filter information since the amount of data will be reasonable.
21863                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21864            } else if ("check-permission".equals(cmd)) {
21865                if (opti >= args.length) {
21866                    pw.println("Error: check-permission missing permission argument");
21867                    return;
21868                }
21869                String perm = args[opti];
21870                opti++;
21871                if (opti >= args.length) {
21872                    pw.println("Error: check-permission missing package argument");
21873                    return;
21874                }
21875
21876                String pkg = args[opti];
21877                opti++;
21878                int user = UserHandle.getUserId(Binder.getCallingUid());
21879                if (opti < args.length) {
21880                    try {
21881                        user = Integer.parseInt(args[opti]);
21882                    } catch (NumberFormatException e) {
21883                        pw.println("Error: check-permission user argument is not a number: "
21884                                + args[opti]);
21885                        return;
21886                    }
21887                }
21888
21889                // Normalize package name to handle renamed packages and static libs
21890                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21891
21892                pw.println(checkPermission(perm, pkg, user));
21893                return;
21894            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21895                dumpState.setDump(DumpState.DUMP_LIBS);
21896            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21897                dumpState.setDump(DumpState.DUMP_FEATURES);
21898            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21899                if (opti >= args.length) {
21900                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21901                            | DumpState.DUMP_SERVICE_RESOLVERS
21902                            | DumpState.DUMP_RECEIVER_RESOLVERS
21903                            | DumpState.DUMP_CONTENT_RESOLVERS);
21904                } else {
21905                    while (opti < args.length) {
21906                        String name = args[opti];
21907                        if ("a".equals(name) || "activity".equals(name)) {
21908                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21909                        } else if ("s".equals(name) || "service".equals(name)) {
21910                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21911                        } else if ("r".equals(name) || "receiver".equals(name)) {
21912                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21913                        } else if ("c".equals(name) || "content".equals(name)) {
21914                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21915                        } else {
21916                            pw.println("Error: unknown resolver table type: " + name);
21917                            return;
21918                        }
21919                        opti++;
21920                    }
21921                }
21922            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21923                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21924            } else if ("permission".equals(cmd)) {
21925                if (opti >= args.length) {
21926                    pw.println("Error: permission requires permission name");
21927                    return;
21928                }
21929                permissionNames = new ArraySet<>();
21930                while (opti < args.length) {
21931                    permissionNames.add(args[opti]);
21932                    opti++;
21933                }
21934                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21935                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21936            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21937                dumpState.setDump(DumpState.DUMP_PREFERRED);
21938            } else if ("preferred-xml".equals(cmd)) {
21939                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21940                if (opti < args.length && "--full".equals(args[opti])) {
21941                    fullPreferred = true;
21942                    opti++;
21943                }
21944            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21945                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21946            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21947                dumpState.setDump(DumpState.DUMP_PACKAGES);
21948            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21949                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21950            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21951                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21952            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21953                dumpState.setDump(DumpState.DUMP_MESSAGES);
21954            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21955                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21956            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21957                    || "intent-filter-verifiers".equals(cmd)) {
21958                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21959            } else if ("version".equals(cmd)) {
21960                dumpState.setDump(DumpState.DUMP_VERSION);
21961            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21962                dumpState.setDump(DumpState.DUMP_KEYSETS);
21963            } else if ("installs".equals(cmd)) {
21964                dumpState.setDump(DumpState.DUMP_INSTALLS);
21965            } else if ("frozen".equals(cmd)) {
21966                dumpState.setDump(DumpState.DUMP_FROZEN);
21967            } else if ("volumes".equals(cmd)) {
21968                dumpState.setDump(DumpState.DUMP_VOLUMES);
21969            } else if ("dexopt".equals(cmd)) {
21970                dumpState.setDump(DumpState.DUMP_DEXOPT);
21971            } else if ("compiler-stats".equals(cmd)) {
21972                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21973            } else if ("changes".equals(cmd)) {
21974                dumpState.setDump(DumpState.DUMP_CHANGES);
21975            } else if ("write".equals(cmd)) {
21976                synchronized (mPackages) {
21977                    mSettings.writeLPr();
21978                    pw.println("Settings written.");
21979                    return;
21980                }
21981            }
21982        }
21983
21984        if (checkin) {
21985            pw.println("vers,1");
21986        }
21987
21988        // reader
21989        synchronized (mPackages) {
21990            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21991                if (!checkin) {
21992                    if (dumpState.onTitlePrinted())
21993                        pw.println();
21994                    pw.println("Database versions:");
21995                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21996                }
21997            }
21998
21999            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22000                if (!checkin) {
22001                    if (dumpState.onTitlePrinted())
22002                        pw.println();
22003                    pw.println("Verifiers:");
22004                    pw.print("  Required: ");
22005                    pw.print(mRequiredVerifierPackage);
22006                    pw.print(" (uid=");
22007                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22008                            UserHandle.USER_SYSTEM));
22009                    pw.println(")");
22010                } else if (mRequiredVerifierPackage != null) {
22011                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22012                    pw.print(",");
22013                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22014                            UserHandle.USER_SYSTEM));
22015                }
22016            }
22017
22018            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22019                    packageName == null) {
22020                if (mIntentFilterVerifierComponent != null) {
22021                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22022                    if (!checkin) {
22023                        if (dumpState.onTitlePrinted())
22024                            pw.println();
22025                        pw.println("Intent Filter Verifier:");
22026                        pw.print("  Using: ");
22027                        pw.print(verifierPackageName);
22028                        pw.print(" (uid=");
22029                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22030                                UserHandle.USER_SYSTEM));
22031                        pw.println(")");
22032                    } else if (verifierPackageName != null) {
22033                        pw.print("ifv,"); pw.print(verifierPackageName);
22034                        pw.print(",");
22035                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22036                                UserHandle.USER_SYSTEM));
22037                    }
22038                } else {
22039                    pw.println();
22040                    pw.println("No Intent Filter Verifier available!");
22041                }
22042            }
22043
22044            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22045                boolean printedHeader = false;
22046                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22047                while (it.hasNext()) {
22048                    String libName = it.next();
22049                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22050                    if (versionedLib == null) {
22051                        continue;
22052                    }
22053                    final int versionCount = versionedLib.size();
22054                    for (int i = 0; i < versionCount; i++) {
22055                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22056                        if (!checkin) {
22057                            if (!printedHeader) {
22058                                if (dumpState.onTitlePrinted())
22059                                    pw.println();
22060                                pw.println("Libraries:");
22061                                printedHeader = true;
22062                            }
22063                            pw.print("  ");
22064                        } else {
22065                            pw.print("lib,");
22066                        }
22067                        pw.print(libEntry.info.getName());
22068                        if (libEntry.info.isStatic()) {
22069                            pw.print(" version=" + libEntry.info.getVersion());
22070                        }
22071                        if (!checkin) {
22072                            pw.print(" -> ");
22073                        }
22074                        if (libEntry.path != null) {
22075                            pw.print(" (jar) ");
22076                            pw.print(libEntry.path);
22077                        } else {
22078                            pw.print(" (apk) ");
22079                            pw.print(libEntry.apk);
22080                        }
22081                        pw.println();
22082                    }
22083                }
22084            }
22085
22086            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22087                if (dumpState.onTitlePrinted())
22088                    pw.println();
22089                if (!checkin) {
22090                    pw.println("Features:");
22091                }
22092
22093                synchronized (mAvailableFeatures) {
22094                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22095                        if (checkin) {
22096                            pw.print("feat,");
22097                            pw.print(feat.name);
22098                            pw.print(",");
22099                            pw.println(feat.version);
22100                        } else {
22101                            pw.print("  ");
22102                            pw.print(feat.name);
22103                            if (feat.version > 0) {
22104                                pw.print(" version=");
22105                                pw.print(feat.version);
22106                            }
22107                            pw.println();
22108                        }
22109                    }
22110                }
22111            }
22112
22113            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22114                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22115                        : "Activity Resolver Table:", "  ", packageName,
22116                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22117                    dumpState.setTitlePrinted(true);
22118                }
22119            }
22120            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22121                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22122                        : "Receiver Resolver Table:", "  ", packageName,
22123                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22124                    dumpState.setTitlePrinted(true);
22125                }
22126            }
22127            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22128                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22129                        : "Service Resolver Table:", "  ", packageName,
22130                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22131                    dumpState.setTitlePrinted(true);
22132                }
22133            }
22134            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22135                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22136                        : "Provider Resolver Table:", "  ", packageName,
22137                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22138                    dumpState.setTitlePrinted(true);
22139                }
22140            }
22141
22142            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22143                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22144                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22145                    int user = mSettings.mPreferredActivities.keyAt(i);
22146                    if (pir.dump(pw,
22147                            dumpState.getTitlePrinted()
22148                                ? "\nPreferred Activities User " + user + ":"
22149                                : "Preferred Activities User " + user + ":", "  ",
22150                            packageName, true, false)) {
22151                        dumpState.setTitlePrinted(true);
22152                    }
22153                }
22154            }
22155
22156            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22157                pw.flush();
22158                FileOutputStream fout = new FileOutputStream(fd);
22159                BufferedOutputStream str = new BufferedOutputStream(fout);
22160                XmlSerializer serializer = new FastXmlSerializer();
22161                try {
22162                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22163                    serializer.startDocument(null, true);
22164                    serializer.setFeature(
22165                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22166                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22167                    serializer.endDocument();
22168                    serializer.flush();
22169                } catch (IllegalArgumentException e) {
22170                    pw.println("Failed writing: " + e);
22171                } catch (IllegalStateException e) {
22172                    pw.println("Failed writing: " + e);
22173                } catch (IOException e) {
22174                    pw.println("Failed writing: " + e);
22175                }
22176            }
22177
22178            if (!checkin
22179                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22180                    && packageName == null) {
22181                pw.println();
22182                int count = mSettings.mPackages.size();
22183                if (count == 0) {
22184                    pw.println("No applications!");
22185                    pw.println();
22186                } else {
22187                    final String prefix = "  ";
22188                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22189                    if (allPackageSettings.size() == 0) {
22190                        pw.println("No domain preferred apps!");
22191                        pw.println();
22192                    } else {
22193                        pw.println("App verification status:");
22194                        pw.println();
22195                        count = 0;
22196                        for (PackageSetting ps : allPackageSettings) {
22197                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22198                            if (ivi == null || ivi.getPackageName() == null) continue;
22199                            pw.println(prefix + "Package: " + ivi.getPackageName());
22200                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22201                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22202                            pw.println();
22203                            count++;
22204                        }
22205                        if (count == 0) {
22206                            pw.println(prefix + "No app verification established.");
22207                            pw.println();
22208                        }
22209                        for (int userId : sUserManager.getUserIds()) {
22210                            pw.println("App linkages for user " + userId + ":");
22211                            pw.println();
22212                            count = 0;
22213                            for (PackageSetting ps : allPackageSettings) {
22214                                final long status = ps.getDomainVerificationStatusForUser(userId);
22215                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22216                                        && !DEBUG_DOMAIN_VERIFICATION) {
22217                                    continue;
22218                                }
22219                                pw.println(prefix + "Package: " + ps.name);
22220                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22221                                String statusStr = IntentFilterVerificationInfo.
22222                                        getStatusStringFromValue(status);
22223                                pw.println(prefix + "Status:  " + statusStr);
22224                                pw.println();
22225                                count++;
22226                            }
22227                            if (count == 0) {
22228                                pw.println(prefix + "No configured app linkages.");
22229                                pw.println();
22230                            }
22231                        }
22232                    }
22233                }
22234            }
22235
22236            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22237                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22238                if (packageName == null && permissionNames == null) {
22239                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22240                        if (iperm == 0) {
22241                            if (dumpState.onTitlePrinted())
22242                                pw.println();
22243                            pw.println("AppOp Permissions:");
22244                        }
22245                        pw.print("  AppOp Permission ");
22246                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22247                        pw.println(":");
22248                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22249                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22250                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22251                        }
22252                    }
22253                }
22254            }
22255
22256            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22257                boolean printedSomething = false;
22258                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22259                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22260                        continue;
22261                    }
22262                    if (!printedSomething) {
22263                        if (dumpState.onTitlePrinted())
22264                            pw.println();
22265                        pw.println("Registered ContentProviders:");
22266                        printedSomething = true;
22267                    }
22268                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22269                    pw.print("    "); pw.println(p.toString());
22270                }
22271                printedSomething = false;
22272                for (Map.Entry<String, PackageParser.Provider> entry :
22273                        mProvidersByAuthority.entrySet()) {
22274                    PackageParser.Provider p = entry.getValue();
22275                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22276                        continue;
22277                    }
22278                    if (!printedSomething) {
22279                        if (dumpState.onTitlePrinted())
22280                            pw.println();
22281                        pw.println("ContentProvider Authorities:");
22282                        printedSomething = true;
22283                    }
22284                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22285                    pw.print("    "); pw.println(p.toString());
22286                    if (p.info != null && p.info.applicationInfo != null) {
22287                        final String appInfo = p.info.applicationInfo.toString();
22288                        pw.print("      applicationInfo="); pw.println(appInfo);
22289                    }
22290                }
22291            }
22292
22293            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22294                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22295            }
22296
22297            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22298                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22299            }
22300
22301            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22302                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22303            }
22304
22305            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22306                if (dumpState.onTitlePrinted()) pw.println();
22307                pw.println("Package Changes:");
22308                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22309                final int K = mChangedPackages.size();
22310                for (int i = 0; i < K; i++) {
22311                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22312                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22313                    final int N = changes.size();
22314                    if (N == 0) {
22315                        pw.print("    "); pw.println("No packages changed");
22316                    } else {
22317                        for (int j = 0; j < N; j++) {
22318                            final String pkgName = changes.valueAt(j);
22319                            final int sequenceNumber = changes.keyAt(j);
22320                            pw.print("    ");
22321                            pw.print("seq=");
22322                            pw.print(sequenceNumber);
22323                            pw.print(", package=");
22324                            pw.println(pkgName);
22325                        }
22326                    }
22327                }
22328            }
22329
22330            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22331                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22332            }
22333
22334            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22335                // XXX should handle packageName != null by dumping only install data that
22336                // the given package is involved with.
22337                if (dumpState.onTitlePrinted()) pw.println();
22338
22339                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22340                ipw.println();
22341                ipw.println("Frozen packages:");
22342                ipw.increaseIndent();
22343                if (mFrozenPackages.size() == 0) {
22344                    ipw.println("(none)");
22345                } else {
22346                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22347                        ipw.println(mFrozenPackages.valueAt(i));
22348                    }
22349                }
22350                ipw.decreaseIndent();
22351            }
22352
22353            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22354                if (dumpState.onTitlePrinted()) pw.println();
22355
22356                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22357                ipw.println();
22358                ipw.println("Loaded volumes:");
22359                ipw.increaseIndent();
22360                if (mLoadedVolumes.size() == 0) {
22361                    ipw.println("(none)");
22362                } else {
22363                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22364                        ipw.println(mLoadedVolumes.valueAt(i));
22365                    }
22366                }
22367                ipw.decreaseIndent();
22368            }
22369
22370            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22371                if (dumpState.onTitlePrinted()) pw.println();
22372                dumpDexoptStateLPr(pw, packageName);
22373            }
22374
22375            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22376                if (dumpState.onTitlePrinted()) pw.println();
22377                dumpCompilerStatsLPr(pw, packageName);
22378            }
22379
22380            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22381                if (dumpState.onTitlePrinted()) pw.println();
22382                mSettings.dumpReadMessagesLPr(pw, dumpState);
22383
22384                pw.println();
22385                pw.println("Package warning messages:");
22386                BufferedReader in = null;
22387                String line = null;
22388                try {
22389                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22390                    while ((line = in.readLine()) != null) {
22391                        if (line.contains("ignored: updated version")) continue;
22392                        pw.println(line);
22393                    }
22394                } catch (IOException ignored) {
22395                } finally {
22396                    IoUtils.closeQuietly(in);
22397                }
22398            }
22399
22400            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22401                BufferedReader in = null;
22402                String line = null;
22403                try {
22404                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22405                    while ((line = in.readLine()) != null) {
22406                        if (line.contains("ignored: updated version")) continue;
22407                        pw.print("msg,");
22408                        pw.println(line);
22409                    }
22410                } catch (IOException ignored) {
22411                } finally {
22412                    IoUtils.closeQuietly(in);
22413                }
22414            }
22415        }
22416
22417        // PackageInstaller should be called outside of mPackages lock
22418        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22419            // XXX should handle packageName != null by dumping only install data that
22420            // the given package is involved with.
22421            if (dumpState.onTitlePrinted()) pw.println();
22422            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22423        }
22424    }
22425
22426    private void dumpProto(FileDescriptor fd) {
22427        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22428
22429        synchronized (mPackages) {
22430            final long requiredVerifierPackageToken =
22431                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22432            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22433            proto.write(
22434                    PackageServiceDumpProto.PackageShortProto.UID,
22435                    getPackageUid(
22436                            mRequiredVerifierPackage,
22437                            MATCH_DEBUG_TRIAGED_MISSING,
22438                            UserHandle.USER_SYSTEM));
22439            proto.end(requiredVerifierPackageToken);
22440
22441            if (mIntentFilterVerifierComponent != null) {
22442                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22443                final long verifierPackageToken =
22444                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22445                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22446                proto.write(
22447                        PackageServiceDumpProto.PackageShortProto.UID,
22448                        getPackageUid(
22449                                verifierPackageName,
22450                                MATCH_DEBUG_TRIAGED_MISSING,
22451                                UserHandle.USER_SYSTEM));
22452                proto.end(verifierPackageToken);
22453            }
22454
22455            dumpSharedLibrariesProto(proto);
22456            dumpFeaturesProto(proto);
22457            mSettings.dumpPackagesProto(proto);
22458            mSettings.dumpSharedUsersProto(proto);
22459            dumpMessagesProto(proto);
22460        }
22461        proto.flush();
22462    }
22463
22464    private void dumpMessagesProto(ProtoOutputStream proto) {
22465        BufferedReader in = null;
22466        String line = null;
22467        try {
22468            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22469            while ((line = in.readLine()) != null) {
22470                if (line.contains("ignored: updated version")) continue;
22471                proto.write(PackageServiceDumpProto.MESSAGES, line);
22472            }
22473        } catch (IOException ignored) {
22474        } finally {
22475            IoUtils.closeQuietly(in);
22476        }
22477    }
22478
22479    private void dumpFeaturesProto(ProtoOutputStream proto) {
22480        synchronized (mAvailableFeatures) {
22481            final int count = mAvailableFeatures.size();
22482            for (int i = 0; i < count; i++) {
22483                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22484                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22485                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22486                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22487                proto.end(featureToken);
22488            }
22489        }
22490    }
22491
22492    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22493        final int count = mSharedLibraries.size();
22494        for (int i = 0; i < count; i++) {
22495            final String libName = mSharedLibraries.keyAt(i);
22496            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22497            if (versionedLib == null) {
22498                continue;
22499            }
22500            final int versionCount = versionedLib.size();
22501            for (int j = 0; j < versionCount; j++) {
22502                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22503                final long sharedLibraryToken =
22504                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22505                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22506                final boolean isJar = (libEntry.path != null);
22507                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22508                if (isJar) {
22509                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22510                } else {
22511                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22512                }
22513                proto.end(sharedLibraryToken);
22514            }
22515        }
22516    }
22517
22518    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22519        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22520        ipw.println();
22521        ipw.println("Dexopt state:");
22522        ipw.increaseIndent();
22523        Collection<PackageParser.Package> packages = null;
22524        if (packageName != null) {
22525            PackageParser.Package targetPackage = mPackages.get(packageName);
22526            if (targetPackage != null) {
22527                packages = Collections.singletonList(targetPackage);
22528            } else {
22529                ipw.println("Unable to find package: " + packageName);
22530                return;
22531            }
22532        } else {
22533            packages = mPackages.values();
22534        }
22535
22536        for (PackageParser.Package pkg : packages) {
22537            ipw.println("[" + pkg.packageName + "]");
22538            ipw.increaseIndent();
22539            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22540            ipw.decreaseIndent();
22541        }
22542    }
22543
22544    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22545        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22546        ipw.println();
22547        ipw.println("Compiler stats:");
22548        ipw.increaseIndent();
22549        Collection<PackageParser.Package> packages = null;
22550        if (packageName != null) {
22551            PackageParser.Package targetPackage = mPackages.get(packageName);
22552            if (targetPackage != null) {
22553                packages = Collections.singletonList(targetPackage);
22554            } else {
22555                ipw.println("Unable to find package: " + packageName);
22556                return;
22557            }
22558        } else {
22559            packages = mPackages.values();
22560        }
22561
22562        for (PackageParser.Package pkg : packages) {
22563            ipw.println("[" + pkg.packageName + "]");
22564            ipw.increaseIndent();
22565
22566            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22567            if (stats == null) {
22568                ipw.println("(No recorded stats)");
22569            } else {
22570                stats.dump(ipw);
22571            }
22572            ipw.decreaseIndent();
22573        }
22574    }
22575
22576    private String dumpDomainString(String packageName) {
22577        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22578                .getList();
22579        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22580
22581        ArraySet<String> result = new ArraySet<>();
22582        if (iviList.size() > 0) {
22583            for (IntentFilterVerificationInfo ivi : iviList) {
22584                for (String host : ivi.getDomains()) {
22585                    result.add(host);
22586                }
22587            }
22588        }
22589        if (filters != null && filters.size() > 0) {
22590            for (IntentFilter filter : filters) {
22591                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22592                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22593                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22594                    result.addAll(filter.getHostsList());
22595                }
22596            }
22597        }
22598
22599        StringBuilder sb = new StringBuilder(result.size() * 16);
22600        for (String domain : result) {
22601            if (sb.length() > 0) sb.append(" ");
22602            sb.append(domain);
22603        }
22604        return sb.toString();
22605    }
22606
22607    // ------- apps on sdcard specific code -------
22608    static final boolean DEBUG_SD_INSTALL = false;
22609
22610    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22611
22612    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22613
22614    private boolean mMediaMounted = false;
22615
22616    static String getEncryptKey() {
22617        try {
22618            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22619                    SD_ENCRYPTION_KEYSTORE_NAME);
22620            if (sdEncKey == null) {
22621                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22622                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22623                if (sdEncKey == null) {
22624                    Slog.e(TAG, "Failed to create encryption keys");
22625                    return null;
22626                }
22627            }
22628            return sdEncKey;
22629        } catch (NoSuchAlgorithmException nsae) {
22630            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22631            return null;
22632        } catch (IOException ioe) {
22633            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22634            return null;
22635        }
22636    }
22637
22638    /*
22639     * Update media status on PackageManager.
22640     */
22641    @Override
22642    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22643        enforceSystemOrRoot("Media status can only be updated by the system");
22644        // reader; this apparently protects mMediaMounted, but should probably
22645        // be a different lock in that case.
22646        synchronized (mPackages) {
22647            Log.i(TAG, "Updating external media status from "
22648                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22649                    + (mediaStatus ? "mounted" : "unmounted"));
22650            if (DEBUG_SD_INSTALL)
22651                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22652                        + ", mMediaMounted=" + mMediaMounted);
22653            if (mediaStatus == mMediaMounted) {
22654                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22655                        : 0, -1);
22656                mHandler.sendMessage(msg);
22657                return;
22658            }
22659            mMediaMounted = mediaStatus;
22660        }
22661        // Queue up an async operation since the package installation may take a
22662        // little while.
22663        mHandler.post(new Runnable() {
22664            public void run() {
22665                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22666            }
22667        });
22668    }
22669
22670    /**
22671     * Called by StorageManagerService when the initial ASECs to scan are available.
22672     * Should block until all the ASEC containers are finished being scanned.
22673     */
22674    public void scanAvailableAsecs() {
22675        updateExternalMediaStatusInner(true, false, false);
22676    }
22677
22678    /*
22679     * Collect information of applications on external media, map them against
22680     * existing containers and update information based on current mount status.
22681     * Please note that we always have to report status if reportStatus has been
22682     * set to true especially when unloading packages.
22683     */
22684    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22685            boolean externalStorage) {
22686        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22687        int[] uidArr = EmptyArray.INT;
22688
22689        final String[] list = PackageHelper.getSecureContainerList();
22690        if (ArrayUtils.isEmpty(list)) {
22691            Log.i(TAG, "No secure containers found");
22692        } else {
22693            // Process list of secure containers and categorize them
22694            // as active or stale based on their package internal state.
22695
22696            // reader
22697            synchronized (mPackages) {
22698                for (String cid : list) {
22699                    // Leave stages untouched for now; installer service owns them
22700                    if (PackageInstallerService.isStageName(cid)) continue;
22701
22702                    if (DEBUG_SD_INSTALL)
22703                        Log.i(TAG, "Processing container " + cid);
22704                    String pkgName = getAsecPackageName(cid);
22705                    if (pkgName == null) {
22706                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22707                        continue;
22708                    }
22709                    if (DEBUG_SD_INSTALL)
22710                        Log.i(TAG, "Looking for pkg : " + pkgName);
22711
22712                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22713                    if (ps == null) {
22714                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22715                        continue;
22716                    }
22717
22718                    /*
22719                     * Skip packages that are not external if we're unmounting
22720                     * external storage.
22721                     */
22722                    if (externalStorage && !isMounted && !isExternal(ps)) {
22723                        continue;
22724                    }
22725
22726                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22727                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22728                    // The package status is changed only if the code path
22729                    // matches between settings and the container id.
22730                    if (ps.codePathString != null
22731                            && ps.codePathString.startsWith(args.getCodePath())) {
22732                        if (DEBUG_SD_INSTALL) {
22733                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22734                                    + " at code path: " + ps.codePathString);
22735                        }
22736
22737                        // We do have a valid package installed on sdcard
22738                        processCids.put(args, ps.codePathString);
22739                        final int uid = ps.appId;
22740                        if (uid != -1) {
22741                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22742                        }
22743                    } else {
22744                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22745                                + ps.codePathString);
22746                    }
22747                }
22748            }
22749
22750            Arrays.sort(uidArr);
22751        }
22752
22753        // Process packages with valid entries.
22754        if (isMounted) {
22755            if (DEBUG_SD_INSTALL)
22756                Log.i(TAG, "Loading packages");
22757            loadMediaPackages(processCids, uidArr, externalStorage);
22758            startCleaningPackages();
22759            mInstallerService.onSecureContainersAvailable();
22760        } else {
22761            if (DEBUG_SD_INSTALL)
22762                Log.i(TAG, "Unloading packages");
22763            unloadMediaPackages(processCids, uidArr, reportStatus);
22764        }
22765    }
22766
22767    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22768            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22769        final int size = infos.size();
22770        final String[] packageNames = new String[size];
22771        final int[] packageUids = new int[size];
22772        for (int i = 0; i < size; i++) {
22773            final ApplicationInfo info = infos.get(i);
22774            packageNames[i] = info.packageName;
22775            packageUids[i] = info.uid;
22776        }
22777        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22778                finishedReceiver);
22779    }
22780
22781    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22782            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22783        sendResourcesChangedBroadcast(mediaStatus, replacing,
22784                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22785    }
22786
22787    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22788            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22789        int size = pkgList.length;
22790        if (size > 0) {
22791            // Send broadcasts here
22792            Bundle extras = new Bundle();
22793            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22794            if (uidArr != null) {
22795                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22796            }
22797            if (replacing) {
22798                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22799            }
22800            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22801                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22802            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22803        }
22804    }
22805
22806   /*
22807     * Look at potentially valid container ids from processCids If package
22808     * information doesn't match the one on record or package scanning fails,
22809     * the cid is added to list of removeCids. We currently don't delete stale
22810     * containers.
22811     */
22812    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22813            boolean externalStorage) {
22814        ArrayList<String> pkgList = new ArrayList<String>();
22815        Set<AsecInstallArgs> keys = processCids.keySet();
22816
22817        for (AsecInstallArgs args : keys) {
22818            String codePath = processCids.get(args);
22819            if (DEBUG_SD_INSTALL)
22820                Log.i(TAG, "Loading container : " + args.cid);
22821            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22822            try {
22823                // Make sure there are no container errors first.
22824                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22825                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22826                            + " when installing from sdcard");
22827                    continue;
22828                }
22829                // Check code path here.
22830                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22831                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22832                            + " does not match one in settings " + codePath);
22833                    continue;
22834                }
22835                // Parse package
22836                int parseFlags = mDefParseFlags;
22837                if (args.isExternalAsec()) {
22838                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22839                }
22840                if (args.isFwdLocked()) {
22841                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22842                }
22843
22844                synchronized (mInstallLock) {
22845                    PackageParser.Package pkg = null;
22846                    try {
22847                        // Sadly we don't know the package name yet to freeze it
22848                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22849                                SCAN_IGNORE_FROZEN, 0, null);
22850                    } catch (PackageManagerException e) {
22851                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22852                    }
22853                    // Scan the package
22854                    if (pkg != null) {
22855                        /*
22856                         * TODO why is the lock being held? doPostInstall is
22857                         * called in other places without the lock. This needs
22858                         * to be straightened out.
22859                         */
22860                        // writer
22861                        synchronized (mPackages) {
22862                            retCode = PackageManager.INSTALL_SUCCEEDED;
22863                            pkgList.add(pkg.packageName);
22864                            // Post process args
22865                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22866                                    pkg.applicationInfo.uid);
22867                        }
22868                    } else {
22869                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22870                    }
22871                }
22872
22873            } finally {
22874                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22875                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22876                }
22877            }
22878        }
22879        // writer
22880        synchronized (mPackages) {
22881            // If the platform SDK has changed since the last time we booted,
22882            // we need to re-grant app permission to catch any new ones that
22883            // appear. This is really a hack, and means that apps can in some
22884            // cases get permissions that the user didn't initially explicitly
22885            // allow... it would be nice to have some better way to handle
22886            // this situation.
22887            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22888                    : mSettings.getInternalVersion();
22889            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22890                    : StorageManager.UUID_PRIVATE_INTERNAL;
22891
22892            int updateFlags = UPDATE_PERMISSIONS_ALL;
22893            if (ver.sdkVersion != mSdkVersion) {
22894                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22895                        + mSdkVersion + "; regranting permissions for external");
22896                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22897            }
22898            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22899
22900            // Yay, everything is now upgraded
22901            ver.forceCurrent();
22902
22903            // can downgrade to reader
22904            // Persist settings
22905            mSettings.writeLPr();
22906        }
22907        // Send a broadcast to let everyone know we are done processing
22908        if (pkgList.size() > 0) {
22909            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22910        }
22911    }
22912
22913   /*
22914     * Utility method to unload a list of specified containers
22915     */
22916    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22917        // Just unmount all valid containers.
22918        for (AsecInstallArgs arg : cidArgs) {
22919            synchronized (mInstallLock) {
22920                arg.doPostDeleteLI(false);
22921           }
22922       }
22923   }
22924
22925    /*
22926     * Unload packages mounted on external media. This involves deleting package
22927     * data from internal structures, sending broadcasts about disabled packages,
22928     * gc'ing to free up references, unmounting all secure containers
22929     * corresponding to packages on external media, and posting a
22930     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22931     * that we always have to post this message if status has been requested no
22932     * matter what.
22933     */
22934    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22935            final boolean reportStatus) {
22936        if (DEBUG_SD_INSTALL)
22937            Log.i(TAG, "unloading media packages");
22938        ArrayList<String> pkgList = new ArrayList<String>();
22939        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22940        final Set<AsecInstallArgs> keys = processCids.keySet();
22941        for (AsecInstallArgs args : keys) {
22942            String pkgName = args.getPackageName();
22943            if (DEBUG_SD_INSTALL)
22944                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22945            // Delete package internally
22946            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22947            synchronized (mInstallLock) {
22948                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22949                final boolean res;
22950                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22951                        "unloadMediaPackages")) {
22952                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22953                            null);
22954                }
22955                if (res) {
22956                    pkgList.add(pkgName);
22957                } else {
22958                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22959                    failedList.add(args);
22960                }
22961            }
22962        }
22963
22964        // reader
22965        synchronized (mPackages) {
22966            // We didn't update the settings after removing each package;
22967            // write them now for all packages.
22968            mSettings.writeLPr();
22969        }
22970
22971        // We have to absolutely send UPDATED_MEDIA_STATUS only
22972        // after confirming that all the receivers processed the ordered
22973        // broadcast when packages get disabled, force a gc to clean things up.
22974        // and unload all the containers.
22975        if (pkgList.size() > 0) {
22976            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22977                    new IIntentReceiver.Stub() {
22978                public void performReceive(Intent intent, int resultCode, String data,
22979                        Bundle extras, boolean ordered, boolean sticky,
22980                        int sendingUser) throws RemoteException {
22981                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22982                            reportStatus ? 1 : 0, 1, keys);
22983                    mHandler.sendMessage(msg);
22984                }
22985            });
22986        } else {
22987            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22988                    keys);
22989            mHandler.sendMessage(msg);
22990        }
22991    }
22992
22993    private void loadPrivatePackages(final VolumeInfo vol) {
22994        mHandler.post(new Runnable() {
22995            @Override
22996            public void run() {
22997                loadPrivatePackagesInner(vol);
22998            }
22999        });
23000    }
23001
23002    private void loadPrivatePackagesInner(VolumeInfo vol) {
23003        final String volumeUuid = vol.fsUuid;
23004        if (TextUtils.isEmpty(volumeUuid)) {
23005            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23006            return;
23007        }
23008
23009        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23010        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23011        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23012
23013        final VersionInfo ver;
23014        final List<PackageSetting> packages;
23015        synchronized (mPackages) {
23016            ver = mSettings.findOrCreateVersion(volumeUuid);
23017            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23018        }
23019
23020        for (PackageSetting ps : packages) {
23021            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23022            synchronized (mInstallLock) {
23023                final PackageParser.Package pkg;
23024                try {
23025                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23026                    loaded.add(pkg.applicationInfo);
23027
23028                } catch (PackageManagerException e) {
23029                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23030                }
23031
23032                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23033                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23034                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23035                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23036                }
23037            }
23038        }
23039
23040        // Reconcile app data for all started/unlocked users
23041        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23042        final UserManager um = mContext.getSystemService(UserManager.class);
23043        UserManagerInternal umInternal = getUserManagerInternal();
23044        for (UserInfo user : um.getUsers()) {
23045            final int flags;
23046            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23047                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23048            } else if (umInternal.isUserRunning(user.id)) {
23049                flags = StorageManager.FLAG_STORAGE_DE;
23050            } else {
23051                continue;
23052            }
23053
23054            try {
23055                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23056                synchronized (mInstallLock) {
23057                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23058                }
23059            } catch (IllegalStateException e) {
23060                // Device was probably ejected, and we'll process that event momentarily
23061                Slog.w(TAG, "Failed to prepare storage: " + e);
23062            }
23063        }
23064
23065        synchronized (mPackages) {
23066            int updateFlags = UPDATE_PERMISSIONS_ALL;
23067            if (ver.sdkVersion != mSdkVersion) {
23068                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23069                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23070                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23071            }
23072            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23073
23074            // Yay, everything is now upgraded
23075            ver.forceCurrent();
23076
23077            mSettings.writeLPr();
23078        }
23079
23080        for (PackageFreezer freezer : freezers) {
23081            freezer.close();
23082        }
23083
23084        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23085        sendResourcesChangedBroadcast(true, false, loaded, null);
23086        mLoadedVolumes.add(vol.getId());
23087    }
23088
23089    private void unloadPrivatePackages(final VolumeInfo vol) {
23090        mHandler.post(new Runnable() {
23091            @Override
23092            public void run() {
23093                unloadPrivatePackagesInner(vol);
23094            }
23095        });
23096    }
23097
23098    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23099        final String volumeUuid = vol.fsUuid;
23100        if (TextUtils.isEmpty(volumeUuid)) {
23101            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23102            return;
23103        }
23104
23105        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23106        synchronized (mInstallLock) {
23107        synchronized (mPackages) {
23108            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23109            for (PackageSetting ps : packages) {
23110                if (ps.pkg == null) continue;
23111
23112                final ApplicationInfo info = ps.pkg.applicationInfo;
23113                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23114                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23115
23116                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23117                        "unloadPrivatePackagesInner")) {
23118                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23119                            false, null)) {
23120                        unloaded.add(info);
23121                    } else {
23122                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23123                    }
23124                }
23125
23126                // Try very hard to release any references to this package
23127                // so we don't risk the system server being killed due to
23128                // open FDs
23129                AttributeCache.instance().removePackage(ps.name);
23130            }
23131
23132            mSettings.writeLPr();
23133        }
23134        }
23135
23136        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23137        sendResourcesChangedBroadcast(false, false, unloaded, null);
23138        mLoadedVolumes.remove(vol.getId());
23139
23140        // Try very hard to release any references to this path so we don't risk
23141        // the system server being killed due to open FDs
23142        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23143
23144        for (int i = 0; i < 3; i++) {
23145            System.gc();
23146            System.runFinalization();
23147        }
23148    }
23149
23150    private void assertPackageKnown(String volumeUuid, String packageName)
23151            throws PackageManagerException {
23152        synchronized (mPackages) {
23153            // Normalize package name to handle renamed packages
23154            packageName = normalizePackageNameLPr(packageName);
23155
23156            final PackageSetting ps = mSettings.mPackages.get(packageName);
23157            if (ps == null) {
23158                throw new PackageManagerException("Package " + packageName + " is unknown");
23159            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23160                throw new PackageManagerException(
23161                        "Package " + packageName + " found on unknown volume " + volumeUuid
23162                                + "; expected volume " + ps.volumeUuid);
23163            }
23164        }
23165    }
23166
23167    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23168            throws PackageManagerException {
23169        synchronized (mPackages) {
23170            // Normalize package name to handle renamed packages
23171            packageName = normalizePackageNameLPr(packageName);
23172
23173            final PackageSetting ps = mSettings.mPackages.get(packageName);
23174            if (ps == null) {
23175                throw new PackageManagerException("Package " + packageName + " is unknown");
23176            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23177                throw new PackageManagerException(
23178                        "Package " + packageName + " found on unknown volume " + volumeUuid
23179                                + "; expected volume " + ps.volumeUuid);
23180            } else if (!ps.getInstalled(userId)) {
23181                throw new PackageManagerException(
23182                        "Package " + packageName + " not installed for user " + userId);
23183            }
23184        }
23185    }
23186
23187    private List<String> collectAbsoluteCodePaths() {
23188        synchronized (mPackages) {
23189            List<String> codePaths = new ArrayList<>();
23190            final int packageCount = mSettings.mPackages.size();
23191            for (int i = 0; i < packageCount; i++) {
23192                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23193                codePaths.add(ps.codePath.getAbsolutePath());
23194            }
23195            return codePaths;
23196        }
23197    }
23198
23199    /**
23200     * Examine all apps present on given mounted volume, and destroy apps that
23201     * aren't expected, either due to uninstallation or reinstallation on
23202     * another volume.
23203     */
23204    private void reconcileApps(String volumeUuid) {
23205        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23206        List<File> filesToDelete = null;
23207
23208        final File[] files = FileUtils.listFilesOrEmpty(
23209                Environment.getDataAppDirectory(volumeUuid));
23210        for (File file : files) {
23211            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23212                    && !PackageInstallerService.isStageName(file.getName());
23213            if (!isPackage) {
23214                // Ignore entries which are not packages
23215                continue;
23216            }
23217
23218            String absolutePath = file.getAbsolutePath();
23219
23220            boolean pathValid = false;
23221            final int absoluteCodePathCount = absoluteCodePaths.size();
23222            for (int i = 0; i < absoluteCodePathCount; i++) {
23223                String absoluteCodePath = absoluteCodePaths.get(i);
23224                if (absolutePath.startsWith(absoluteCodePath)) {
23225                    pathValid = true;
23226                    break;
23227                }
23228            }
23229
23230            if (!pathValid) {
23231                if (filesToDelete == null) {
23232                    filesToDelete = new ArrayList<>();
23233                }
23234                filesToDelete.add(file);
23235            }
23236        }
23237
23238        if (filesToDelete != null) {
23239            final int fileToDeleteCount = filesToDelete.size();
23240            for (int i = 0; i < fileToDeleteCount; i++) {
23241                File fileToDelete = filesToDelete.get(i);
23242                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23243                synchronized (mInstallLock) {
23244                    removeCodePathLI(fileToDelete);
23245                }
23246            }
23247        }
23248    }
23249
23250    /**
23251     * Reconcile all app data for the given user.
23252     * <p>
23253     * Verifies that directories exist and that ownership and labeling is
23254     * correct for all installed apps on all mounted volumes.
23255     */
23256    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23257        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23258        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23259            final String volumeUuid = vol.getFsUuid();
23260            synchronized (mInstallLock) {
23261                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23262            }
23263        }
23264    }
23265
23266    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23267            boolean migrateAppData) {
23268        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23269    }
23270
23271    /**
23272     * Reconcile all app data on given mounted volume.
23273     * <p>
23274     * Destroys app data that isn't expected, either due to uninstallation or
23275     * reinstallation on another volume.
23276     * <p>
23277     * Verifies that directories exist and that ownership and labeling is
23278     * correct for all installed apps.
23279     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23280     */
23281    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23282            boolean migrateAppData, boolean onlyCoreApps) {
23283        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23284                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23285        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23286
23287        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23288        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23289
23290        // First look for stale data that doesn't belong, and check if things
23291        // have changed since we did our last restorecon
23292        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23293            if (StorageManager.isFileEncryptedNativeOrEmulated()
23294                    && !StorageManager.isUserKeyUnlocked(userId)) {
23295                throw new RuntimeException(
23296                        "Yikes, someone asked us to reconcile CE storage while " + userId
23297                                + " was still locked; this would have caused massive data loss!");
23298            }
23299
23300            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23301            for (File file : files) {
23302                final String packageName = file.getName();
23303                try {
23304                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23305                } catch (PackageManagerException e) {
23306                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23307                    try {
23308                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23309                                StorageManager.FLAG_STORAGE_CE, 0);
23310                    } catch (InstallerException e2) {
23311                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23312                    }
23313                }
23314            }
23315        }
23316        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23317            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23318            for (File file : files) {
23319                final String packageName = file.getName();
23320                try {
23321                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23322                } catch (PackageManagerException e) {
23323                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23324                    try {
23325                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23326                                StorageManager.FLAG_STORAGE_DE, 0);
23327                    } catch (InstallerException e2) {
23328                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23329                    }
23330                }
23331            }
23332        }
23333
23334        // Ensure that data directories are ready to roll for all packages
23335        // installed for this volume and user
23336        final List<PackageSetting> packages;
23337        synchronized (mPackages) {
23338            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23339        }
23340        int preparedCount = 0;
23341        for (PackageSetting ps : packages) {
23342            final String packageName = ps.name;
23343            if (ps.pkg == null) {
23344                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23345                // TODO: might be due to legacy ASEC apps; we should circle back
23346                // and reconcile again once they're scanned
23347                continue;
23348            }
23349            // Skip non-core apps if requested
23350            if (onlyCoreApps && !ps.pkg.coreApp) {
23351                result.add(packageName);
23352                continue;
23353            }
23354
23355            if (ps.getInstalled(userId)) {
23356                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23357                preparedCount++;
23358            }
23359        }
23360
23361        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23362        return result;
23363    }
23364
23365    /**
23366     * Prepare app data for the given app just after it was installed or
23367     * upgraded. This method carefully only touches users that it's installed
23368     * for, and it forces a restorecon to handle any seinfo changes.
23369     * <p>
23370     * Verifies that directories exist and that ownership and labeling is
23371     * correct for all installed apps. If there is an ownership mismatch, it
23372     * will try recovering system apps by wiping data; third-party app data is
23373     * left intact.
23374     * <p>
23375     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23376     */
23377    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23378        final PackageSetting ps;
23379        synchronized (mPackages) {
23380            ps = mSettings.mPackages.get(pkg.packageName);
23381            mSettings.writeKernelMappingLPr(ps);
23382        }
23383
23384        final UserManager um = mContext.getSystemService(UserManager.class);
23385        UserManagerInternal umInternal = getUserManagerInternal();
23386        for (UserInfo user : um.getUsers()) {
23387            final int flags;
23388            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23389                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23390            } else if (umInternal.isUserRunning(user.id)) {
23391                flags = StorageManager.FLAG_STORAGE_DE;
23392            } else {
23393                continue;
23394            }
23395
23396            if (ps.getInstalled(user.id)) {
23397                // TODO: when user data is locked, mark that we're still dirty
23398                prepareAppDataLIF(pkg, user.id, flags);
23399            }
23400        }
23401    }
23402
23403    /**
23404     * Prepare app data for the given app.
23405     * <p>
23406     * Verifies that directories exist and that ownership and labeling is
23407     * correct for all installed apps. If there is an ownership mismatch, this
23408     * will try recovering system apps by wiping data; third-party app data is
23409     * left intact.
23410     */
23411    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23412        if (pkg == null) {
23413            Slog.wtf(TAG, "Package was null!", new Throwable());
23414            return;
23415        }
23416        prepareAppDataLeafLIF(pkg, userId, flags);
23417        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23418        for (int i = 0; i < childCount; i++) {
23419            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23420        }
23421    }
23422
23423    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23424            boolean maybeMigrateAppData) {
23425        prepareAppDataLIF(pkg, userId, flags);
23426
23427        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23428            // We may have just shuffled around app data directories, so
23429            // prepare them one more time
23430            prepareAppDataLIF(pkg, userId, flags);
23431        }
23432    }
23433
23434    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23435        if (DEBUG_APP_DATA) {
23436            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23437                    + Integer.toHexString(flags));
23438        }
23439
23440        final String volumeUuid = pkg.volumeUuid;
23441        final String packageName = pkg.packageName;
23442        final ApplicationInfo app = pkg.applicationInfo;
23443        final int appId = UserHandle.getAppId(app.uid);
23444
23445        Preconditions.checkNotNull(app.seInfo);
23446
23447        long ceDataInode = -1;
23448        try {
23449            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23450                    appId, app.seInfo, app.targetSdkVersion);
23451        } catch (InstallerException e) {
23452            if (app.isSystemApp()) {
23453                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23454                        + ", but trying to recover: " + e);
23455                destroyAppDataLeafLIF(pkg, userId, flags);
23456                try {
23457                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23458                            appId, app.seInfo, app.targetSdkVersion);
23459                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23460                } catch (InstallerException e2) {
23461                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23462                }
23463            } else {
23464                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23465            }
23466        }
23467
23468        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23469            // TODO: mark this structure as dirty so we persist it!
23470            synchronized (mPackages) {
23471                final PackageSetting ps = mSettings.mPackages.get(packageName);
23472                if (ps != null) {
23473                    ps.setCeDataInode(ceDataInode, userId);
23474                }
23475            }
23476        }
23477
23478        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23479    }
23480
23481    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23482        if (pkg == null) {
23483            Slog.wtf(TAG, "Package was null!", new Throwable());
23484            return;
23485        }
23486        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23487        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23488        for (int i = 0; i < childCount; i++) {
23489            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23490        }
23491    }
23492
23493    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23494        final String volumeUuid = pkg.volumeUuid;
23495        final String packageName = pkg.packageName;
23496        final ApplicationInfo app = pkg.applicationInfo;
23497
23498        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23499            // Create a native library symlink only if we have native libraries
23500            // and if the native libraries are 32 bit libraries. We do not provide
23501            // this symlink for 64 bit libraries.
23502            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23503                final String nativeLibPath = app.nativeLibraryDir;
23504                try {
23505                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23506                            nativeLibPath, userId);
23507                } catch (InstallerException e) {
23508                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23509                }
23510            }
23511        }
23512    }
23513
23514    /**
23515     * For system apps on non-FBE devices, this method migrates any existing
23516     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23517     * requested by the app.
23518     */
23519    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23520        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23521                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23522            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23523                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23524            try {
23525                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23526                        storageTarget);
23527            } catch (InstallerException e) {
23528                logCriticalInfo(Log.WARN,
23529                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23530            }
23531            return true;
23532        } else {
23533            return false;
23534        }
23535    }
23536
23537    public PackageFreezer freezePackage(String packageName, String killReason) {
23538        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23539    }
23540
23541    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23542        return new PackageFreezer(packageName, userId, killReason);
23543    }
23544
23545    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23546            String killReason) {
23547        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23548    }
23549
23550    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23551            String killReason) {
23552        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23553            return new PackageFreezer();
23554        } else {
23555            return freezePackage(packageName, userId, killReason);
23556        }
23557    }
23558
23559    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23560            String killReason) {
23561        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23562    }
23563
23564    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23565            String killReason) {
23566        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23567            return new PackageFreezer();
23568        } else {
23569            return freezePackage(packageName, userId, killReason);
23570        }
23571    }
23572
23573    /**
23574     * Class that freezes and kills the given package upon creation, and
23575     * unfreezes it upon closing. This is typically used when doing surgery on
23576     * app code/data to prevent the app from running while you're working.
23577     */
23578    private class PackageFreezer implements AutoCloseable {
23579        private final String mPackageName;
23580        private final PackageFreezer[] mChildren;
23581
23582        private final boolean mWeFroze;
23583
23584        private final AtomicBoolean mClosed = new AtomicBoolean();
23585        private final CloseGuard mCloseGuard = CloseGuard.get();
23586
23587        /**
23588         * Create and return a stub freezer that doesn't actually do anything,
23589         * typically used when someone requested
23590         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23591         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23592         */
23593        public PackageFreezer() {
23594            mPackageName = null;
23595            mChildren = null;
23596            mWeFroze = false;
23597            mCloseGuard.open("close");
23598        }
23599
23600        public PackageFreezer(String packageName, int userId, String killReason) {
23601            synchronized (mPackages) {
23602                mPackageName = packageName;
23603                mWeFroze = mFrozenPackages.add(mPackageName);
23604
23605                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23606                if (ps != null) {
23607                    killApplication(ps.name, ps.appId, userId, killReason);
23608                }
23609
23610                final PackageParser.Package p = mPackages.get(packageName);
23611                if (p != null && p.childPackages != null) {
23612                    final int N = p.childPackages.size();
23613                    mChildren = new PackageFreezer[N];
23614                    for (int i = 0; i < N; i++) {
23615                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23616                                userId, killReason);
23617                    }
23618                } else {
23619                    mChildren = null;
23620                }
23621            }
23622            mCloseGuard.open("close");
23623        }
23624
23625        @Override
23626        protected void finalize() throws Throwable {
23627            try {
23628                if (mCloseGuard != null) {
23629                    mCloseGuard.warnIfOpen();
23630                }
23631
23632                close();
23633            } finally {
23634                super.finalize();
23635            }
23636        }
23637
23638        @Override
23639        public void close() {
23640            mCloseGuard.close();
23641            if (mClosed.compareAndSet(false, true)) {
23642                synchronized (mPackages) {
23643                    if (mWeFroze) {
23644                        mFrozenPackages.remove(mPackageName);
23645                    }
23646
23647                    if (mChildren != null) {
23648                        for (PackageFreezer freezer : mChildren) {
23649                            freezer.close();
23650                        }
23651                    }
23652                }
23653            }
23654        }
23655    }
23656
23657    /**
23658     * Verify that given package is currently frozen.
23659     */
23660    private void checkPackageFrozen(String packageName) {
23661        synchronized (mPackages) {
23662            if (!mFrozenPackages.contains(packageName)) {
23663                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23664            }
23665        }
23666    }
23667
23668    @Override
23669    public int movePackage(final String packageName, final String volumeUuid) {
23670        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23671
23672        final int callingUid = Binder.getCallingUid();
23673        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23674        final int moveId = mNextMoveId.getAndIncrement();
23675        mHandler.post(new Runnable() {
23676            @Override
23677            public void run() {
23678                try {
23679                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23680                } catch (PackageManagerException e) {
23681                    Slog.w(TAG, "Failed to move " + packageName, e);
23682                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23683                }
23684            }
23685        });
23686        return moveId;
23687    }
23688
23689    private void movePackageInternal(final String packageName, final String volumeUuid,
23690            final int moveId, final int callingUid, UserHandle user)
23691                    throws PackageManagerException {
23692        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23693        final PackageManager pm = mContext.getPackageManager();
23694
23695        final boolean currentAsec;
23696        final String currentVolumeUuid;
23697        final File codeFile;
23698        final String installerPackageName;
23699        final String packageAbiOverride;
23700        final int appId;
23701        final String seinfo;
23702        final String label;
23703        final int targetSdkVersion;
23704        final PackageFreezer freezer;
23705        final int[] installedUserIds;
23706
23707        // reader
23708        synchronized (mPackages) {
23709            final PackageParser.Package pkg = mPackages.get(packageName);
23710            final PackageSetting ps = mSettings.mPackages.get(packageName);
23711            if (pkg == null
23712                    || ps == null
23713                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23714                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23715            }
23716            if (pkg.applicationInfo.isSystemApp()) {
23717                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23718                        "Cannot move system application");
23719            }
23720
23721            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23722            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23723                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23724            if (isInternalStorage && !allow3rdPartyOnInternal) {
23725                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23726                        "3rd party apps are not allowed on internal storage");
23727            }
23728
23729            if (pkg.applicationInfo.isExternalAsec()) {
23730                currentAsec = true;
23731                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23732            } else if (pkg.applicationInfo.isForwardLocked()) {
23733                currentAsec = true;
23734                currentVolumeUuid = "forward_locked";
23735            } else {
23736                currentAsec = false;
23737                currentVolumeUuid = ps.volumeUuid;
23738
23739                final File probe = new File(pkg.codePath);
23740                final File probeOat = new File(probe, "oat");
23741                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23742                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23743                            "Move only supported for modern cluster style installs");
23744                }
23745            }
23746
23747            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23748                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23749                        "Package already moved to " + volumeUuid);
23750            }
23751            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23752                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23753                        "Device admin cannot be moved");
23754            }
23755
23756            if (mFrozenPackages.contains(packageName)) {
23757                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23758                        "Failed to move already frozen package");
23759            }
23760
23761            codeFile = new File(pkg.codePath);
23762            installerPackageName = ps.installerPackageName;
23763            packageAbiOverride = ps.cpuAbiOverrideString;
23764            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23765            seinfo = pkg.applicationInfo.seInfo;
23766            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23767            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23768            freezer = freezePackage(packageName, "movePackageInternal");
23769            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23770        }
23771
23772        final Bundle extras = new Bundle();
23773        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23774        extras.putString(Intent.EXTRA_TITLE, label);
23775        mMoveCallbacks.notifyCreated(moveId, extras);
23776
23777        int installFlags;
23778        final boolean moveCompleteApp;
23779        final File measurePath;
23780
23781        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23782            installFlags = INSTALL_INTERNAL;
23783            moveCompleteApp = !currentAsec;
23784            measurePath = Environment.getDataAppDirectory(volumeUuid);
23785        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23786            installFlags = INSTALL_EXTERNAL;
23787            moveCompleteApp = false;
23788            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23789        } else {
23790            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23791            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23792                    || !volume.isMountedWritable()) {
23793                freezer.close();
23794                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23795                        "Move location not mounted private volume");
23796            }
23797
23798            Preconditions.checkState(!currentAsec);
23799
23800            installFlags = INSTALL_INTERNAL;
23801            moveCompleteApp = true;
23802            measurePath = Environment.getDataAppDirectory(volumeUuid);
23803        }
23804
23805        // If we're moving app data around, we need all the users unlocked
23806        if (moveCompleteApp) {
23807            for (int userId : installedUserIds) {
23808                if (StorageManager.isFileEncryptedNativeOrEmulated()
23809                        && !StorageManager.isUserKeyUnlocked(userId)) {
23810                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23811                            "User " + userId + " must be unlocked");
23812                }
23813            }
23814        }
23815
23816        final PackageStats stats = new PackageStats(null, -1);
23817        synchronized (mInstaller) {
23818            for (int userId : installedUserIds) {
23819                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23820                    freezer.close();
23821                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23822                            "Failed to measure package size");
23823                }
23824            }
23825        }
23826
23827        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23828                + stats.dataSize);
23829
23830        final long startFreeBytes = measurePath.getUsableSpace();
23831        final long sizeBytes;
23832        if (moveCompleteApp) {
23833            sizeBytes = stats.codeSize + stats.dataSize;
23834        } else {
23835            sizeBytes = stats.codeSize;
23836        }
23837
23838        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23839            freezer.close();
23840            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23841                    "Not enough free space to move");
23842        }
23843
23844        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23845
23846        final CountDownLatch installedLatch = new CountDownLatch(1);
23847        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23848            @Override
23849            public void onUserActionRequired(Intent intent) throws RemoteException {
23850                throw new IllegalStateException();
23851            }
23852
23853            @Override
23854            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23855                    Bundle extras) throws RemoteException {
23856                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23857                        + PackageManager.installStatusToString(returnCode, msg));
23858
23859                installedLatch.countDown();
23860                freezer.close();
23861
23862                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23863                switch (status) {
23864                    case PackageInstaller.STATUS_SUCCESS:
23865                        mMoveCallbacks.notifyStatusChanged(moveId,
23866                                PackageManager.MOVE_SUCCEEDED);
23867                        break;
23868                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23869                        mMoveCallbacks.notifyStatusChanged(moveId,
23870                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23871                        break;
23872                    default:
23873                        mMoveCallbacks.notifyStatusChanged(moveId,
23874                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23875                        break;
23876                }
23877            }
23878        };
23879
23880        final MoveInfo move;
23881        if (moveCompleteApp) {
23882            // Kick off a thread to report progress estimates
23883            new Thread() {
23884                @Override
23885                public void run() {
23886                    while (true) {
23887                        try {
23888                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23889                                break;
23890                            }
23891                        } catch (InterruptedException ignored) {
23892                        }
23893
23894                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23895                        final int progress = 10 + (int) MathUtils.constrain(
23896                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23897                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23898                    }
23899                }
23900            }.start();
23901
23902            final String dataAppName = codeFile.getName();
23903            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23904                    dataAppName, appId, seinfo, targetSdkVersion);
23905        } else {
23906            move = null;
23907        }
23908
23909        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23910
23911        final Message msg = mHandler.obtainMessage(INIT_COPY);
23912        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23913        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23914                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23915                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23916                PackageManager.INSTALL_REASON_UNKNOWN);
23917        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23918        msg.obj = params;
23919
23920        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23921                System.identityHashCode(msg.obj));
23922        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23923                System.identityHashCode(msg.obj));
23924
23925        mHandler.sendMessage(msg);
23926    }
23927
23928    @Override
23929    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23930        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23931
23932        final int realMoveId = mNextMoveId.getAndIncrement();
23933        final Bundle extras = new Bundle();
23934        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23935        mMoveCallbacks.notifyCreated(realMoveId, extras);
23936
23937        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23938            @Override
23939            public void onCreated(int moveId, Bundle extras) {
23940                // Ignored
23941            }
23942
23943            @Override
23944            public void onStatusChanged(int moveId, int status, long estMillis) {
23945                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23946            }
23947        };
23948
23949        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23950        storage.setPrimaryStorageUuid(volumeUuid, callback);
23951        return realMoveId;
23952    }
23953
23954    @Override
23955    public int getMoveStatus(int moveId) {
23956        mContext.enforceCallingOrSelfPermission(
23957                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23958        return mMoveCallbacks.mLastStatus.get(moveId);
23959    }
23960
23961    @Override
23962    public void registerMoveCallback(IPackageMoveObserver callback) {
23963        mContext.enforceCallingOrSelfPermission(
23964                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23965        mMoveCallbacks.register(callback);
23966    }
23967
23968    @Override
23969    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23970        mContext.enforceCallingOrSelfPermission(
23971                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23972        mMoveCallbacks.unregister(callback);
23973    }
23974
23975    @Override
23976    public boolean setInstallLocation(int loc) {
23977        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23978                null);
23979        if (getInstallLocation() == loc) {
23980            return true;
23981        }
23982        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23983                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23984            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23985                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23986            return true;
23987        }
23988        return false;
23989   }
23990
23991    @Override
23992    public int getInstallLocation() {
23993        // allow instant app access
23994        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23995                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23996                PackageHelper.APP_INSTALL_AUTO);
23997    }
23998
23999    /** Called by UserManagerService */
24000    void cleanUpUser(UserManagerService userManager, int userHandle) {
24001        synchronized (mPackages) {
24002            mDirtyUsers.remove(userHandle);
24003            mUserNeedsBadging.delete(userHandle);
24004            mSettings.removeUserLPw(userHandle);
24005            mPendingBroadcasts.remove(userHandle);
24006            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24007            removeUnusedPackagesLPw(userManager, userHandle);
24008        }
24009    }
24010
24011    /**
24012     * We're removing userHandle and would like to remove any downloaded packages
24013     * that are no longer in use by any other user.
24014     * @param userHandle the user being removed
24015     */
24016    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24017        final boolean DEBUG_CLEAN_APKS = false;
24018        int [] users = userManager.getUserIds();
24019        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24020        while (psit.hasNext()) {
24021            PackageSetting ps = psit.next();
24022            if (ps.pkg == null) {
24023                continue;
24024            }
24025            final String packageName = ps.pkg.packageName;
24026            // Skip over if system app
24027            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24028                continue;
24029            }
24030            if (DEBUG_CLEAN_APKS) {
24031                Slog.i(TAG, "Checking package " + packageName);
24032            }
24033            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24034            if (keep) {
24035                if (DEBUG_CLEAN_APKS) {
24036                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24037                }
24038            } else {
24039                for (int i = 0; i < users.length; i++) {
24040                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24041                        keep = true;
24042                        if (DEBUG_CLEAN_APKS) {
24043                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24044                                    + users[i]);
24045                        }
24046                        break;
24047                    }
24048                }
24049            }
24050            if (!keep) {
24051                if (DEBUG_CLEAN_APKS) {
24052                    Slog.i(TAG, "  Removing package " + packageName);
24053                }
24054                mHandler.post(new Runnable() {
24055                    public void run() {
24056                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24057                                userHandle, 0);
24058                    } //end run
24059                });
24060            }
24061        }
24062    }
24063
24064    /** Called by UserManagerService */
24065    void createNewUser(int userId, String[] disallowedPackages) {
24066        synchronized (mInstallLock) {
24067            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24068        }
24069        synchronized (mPackages) {
24070            scheduleWritePackageRestrictionsLocked(userId);
24071            scheduleWritePackageListLocked(userId);
24072            applyFactoryDefaultBrowserLPw(userId);
24073            primeDomainVerificationsLPw(userId);
24074        }
24075    }
24076
24077    void onNewUserCreated(final int userId) {
24078        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24079        // If permission review for legacy apps is required, we represent
24080        // dagerous permissions for such apps as always granted runtime
24081        // permissions to keep per user flag state whether review is needed.
24082        // Hence, if a new user is added we have to propagate dangerous
24083        // permission grants for these legacy apps.
24084        if (mPermissionReviewRequired) {
24085            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24086                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24087        }
24088    }
24089
24090    @Override
24091    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24092        mContext.enforceCallingOrSelfPermission(
24093                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24094                "Only package verification agents can read the verifier device identity");
24095
24096        synchronized (mPackages) {
24097            return mSettings.getVerifierDeviceIdentityLPw();
24098        }
24099    }
24100
24101    @Override
24102    public void setPermissionEnforced(String permission, boolean enforced) {
24103        // TODO: Now that we no longer change GID for storage, this should to away.
24104        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24105                "setPermissionEnforced");
24106        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24107            synchronized (mPackages) {
24108                if (mSettings.mReadExternalStorageEnforced == null
24109                        || mSettings.mReadExternalStorageEnforced != enforced) {
24110                    mSettings.mReadExternalStorageEnforced = enforced;
24111                    mSettings.writeLPr();
24112                }
24113            }
24114            // kill any non-foreground processes so we restart them and
24115            // grant/revoke the GID.
24116            final IActivityManager am = ActivityManager.getService();
24117            if (am != null) {
24118                final long token = Binder.clearCallingIdentity();
24119                try {
24120                    am.killProcessesBelowForeground("setPermissionEnforcement");
24121                } catch (RemoteException e) {
24122                } finally {
24123                    Binder.restoreCallingIdentity(token);
24124                }
24125            }
24126        } else {
24127            throw new IllegalArgumentException("No selective enforcement for " + permission);
24128        }
24129    }
24130
24131    @Override
24132    @Deprecated
24133    public boolean isPermissionEnforced(String permission) {
24134        // allow instant applications
24135        return true;
24136    }
24137
24138    @Override
24139    public boolean isStorageLow() {
24140        // allow instant applications
24141        final long token = Binder.clearCallingIdentity();
24142        try {
24143            final DeviceStorageMonitorInternal
24144                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24145            if (dsm != null) {
24146                return dsm.isMemoryLow();
24147            } else {
24148                return false;
24149            }
24150        } finally {
24151            Binder.restoreCallingIdentity(token);
24152        }
24153    }
24154
24155    @Override
24156    public IPackageInstaller getPackageInstaller() {
24157        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24158            return null;
24159        }
24160        return mInstallerService;
24161    }
24162
24163    private boolean userNeedsBadging(int userId) {
24164        int index = mUserNeedsBadging.indexOfKey(userId);
24165        if (index < 0) {
24166            final UserInfo userInfo;
24167            final long token = Binder.clearCallingIdentity();
24168            try {
24169                userInfo = sUserManager.getUserInfo(userId);
24170            } finally {
24171                Binder.restoreCallingIdentity(token);
24172            }
24173            final boolean b;
24174            if (userInfo != null && userInfo.isManagedProfile()) {
24175                b = true;
24176            } else {
24177                b = false;
24178            }
24179            mUserNeedsBadging.put(userId, b);
24180            return b;
24181        }
24182        return mUserNeedsBadging.valueAt(index);
24183    }
24184
24185    @Override
24186    public KeySet getKeySetByAlias(String packageName, String alias) {
24187        if (packageName == null || alias == null) {
24188            return null;
24189        }
24190        synchronized(mPackages) {
24191            final PackageParser.Package pkg = mPackages.get(packageName);
24192            if (pkg == null) {
24193                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24194                throw new IllegalArgumentException("Unknown package: " + packageName);
24195            }
24196            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24197            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24198                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24199                throw new IllegalArgumentException("Unknown package: " + packageName);
24200            }
24201            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24202            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24203        }
24204    }
24205
24206    @Override
24207    public KeySet getSigningKeySet(String packageName) {
24208        if (packageName == null) {
24209            return null;
24210        }
24211        synchronized(mPackages) {
24212            final int callingUid = Binder.getCallingUid();
24213            final int callingUserId = UserHandle.getUserId(callingUid);
24214            final PackageParser.Package pkg = mPackages.get(packageName);
24215            if (pkg == null) {
24216                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24217                throw new IllegalArgumentException("Unknown package: " + packageName);
24218            }
24219            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24220            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24221                // filter and pretend the package doesn't exist
24222                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24223                        + ", uid:" + callingUid);
24224                throw new IllegalArgumentException("Unknown package: " + packageName);
24225            }
24226            if (pkg.applicationInfo.uid != callingUid
24227                    && Process.SYSTEM_UID != callingUid) {
24228                throw new SecurityException("May not access signing KeySet of other apps.");
24229            }
24230            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24231            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24232        }
24233    }
24234
24235    @Override
24236    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24237        final int callingUid = Binder.getCallingUid();
24238        if (getInstantAppPackageName(callingUid) != null) {
24239            return false;
24240        }
24241        if (packageName == null || ks == null) {
24242            return false;
24243        }
24244        synchronized(mPackages) {
24245            final PackageParser.Package pkg = mPackages.get(packageName);
24246            if (pkg == null
24247                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24248                            UserHandle.getUserId(callingUid))) {
24249                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24250                throw new IllegalArgumentException("Unknown package: " + packageName);
24251            }
24252            IBinder ksh = ks.getToken();
24253            if (ksh instanceof KeySetHandle) {
24254                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24255                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24256            }
24257            return false;
24258        }
24259    }
24260
24261    @Override
24262    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24263        final int callingUid = Binder.getCallingUid();
24264        if (getInstantAppPackageName(callingUid) != null) {
24265            return false;
24266        }
24267        if (packageName == null || ks == null) {
24268            return false;
24269        }
24270        synchronized(mPackages) {
24271            final PackageParser.Package pkg = mPackages.get(packageName);
24272            if (pkg == null
24273                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24274                            UserHandle.getUserId(callingUid))) {
24275                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24276                throw new IllegalArgumentException("Unknown package: " + packageName);
24277            }
24278            IBinder ksh = ks.getToken();
24279            if (ksh instanceof KeySetHandle) {
24280                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24281                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24282            }
24283            return false;
24284        }
24285    }
24286
24287    private void deletePackageIfUnusedLPr(final String packageName) {
24288        PackageSetting ps = mSettings.mPackages.get(packageName);
24289        if (ps == null) {
24290            return;
24291        }
24292        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24293            // TODO Implement atomic delete if package is unused
24294            // It is currently possible that the package will be deleted even if it is installed
24295            // after this method returns.
24296            mHandler.post(new Runnable() {
24297                public void run() {
24298                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24299                            0, PackageManager.DELETE_ALL_USERS);
24300                }
24301            });
24302        }
24303    }
24304
24305    /**
24306     * Check and throw if the given before/after packages would be considered a
24307     * downgrade.
24308     */
24309    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24310            throws PackageManagerException {
24311        if (after.versionCode < before.mVersionCode) {
24312            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24313                    "Update version code " + after.versionCode + " is older than current "
24314                    + before.mVersionCode);
24315        } else if (after.versionCode == before.mVersionCode) {
24316            if (after.baseRevisionCode < before.baseRevisionCode) {
24317                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24318                        "Update base revision code " + after.baseRevisionCode
24319                        + " is older than current " + before.baseRevisionCode);
24320            }
24321
24322            if (!ArrayUtils.isEmpty(after.splitNames)) {
24323                for (int i = 0; i < after.splitNames.length; i++) {
24324                    final String splitName = after.splitNames[i];
24325                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24326                    if (j != -1) {
24327                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24328                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24329                                    "Update split " + splitName + " revision code "
24330                                    + after.splitRevisionCodes[i] + " is older than current "
24331                                    + before.splitRevisionCodes[j]);
24332                        }
24333                    }
24334                }
24335            }
24336        }
24337    }
24338
24339    private static class MoveCallbacks extends Handler {
24340        private static final int MSG_CREATED = 1;
24341        private static final int MSG_STATUS_CHANGED = 2;
24342
24343        private final RemoteCallbackList<IPackageMoveObserver>
24344                mCallbacks = new RemoteCallbackList<>();
24345
24346        private final SparseIntArray mLastStatus = new SparseIntArray();
24347
24348        public MoveCallbacks(Looper looper) {
24349            super(looper);
24350        }
24351
24352        public void register(IPackageMoveObserver callback) {
24353            mCallbacks.register(callback);
24354        }
24355
24356        public void unregister(IPackageMoveObserver callback) {
24357            mCallbacks.unregister(callback);
24358        }
24359
24360        @Override
24361        public void handleMessage(Message msg) {
24362            final SomeArgs args = (SomeArgs) msg.obj;
24363            final int n = mCallbacks.beginBroadcast();
24364            for (int i = 0; i < n; i++) {
24365                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24366                try {
24367                    invokeCallback(callback, msg.what, args);
24368                } catch (RemoteException ignored) {
24369                }
24370            }
24371            mCallbacks.finishBroadcast();
24372            args.recycle();
24373        }
24374
24375        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24376                throws RemoteException {
24377            switch (what) {
24378                case MSG_CREATED: {
24379                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24380                    break;
24381                }
24382                case MSG_STATUS_CHANGED: {
24383                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24384                    break;
24385                }
24386            }
24387        }
24388
24389        private void notifyCreated(int moveId, Bundle extras) {
24390            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24391
24392            final SomeArgs args = SomeArgs.obtain();
24393            args.argi1 = moveId;
24394            args.arg2 = extras;
24395            obtainMessage(MSG_CREATED, args).sendToTarget();
24396        }
24397
24398        private void notifyStatusChanged(int moveId, int status) {
24399            notifyStatusChanged(moveId, status, -1);
24400        }
24401
24402        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24403            Slog.v(TAG, "Move " + moveId + " status " + status);
24404
24405            final SomeArgs args = SomeArgs.obtain();
24406            args.argi1 = moveId;
24407            args.argi2 = status;
24408            args.arg3 = estMillis;
24409            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24410
24411            synchronized (mLastStatus) {
24412                mLastStatus.put(moveId, status);
24413            }
24414        }
24415    }
24416
24417    private final static class OnPermissionChangeListeners extends Handler {
24418        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24419
24420        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24421                new RemoteCallbackList<>();
24422
24423        public OnPermissionChangeListeners(Looper looper) {
24424            super(looper);
24425        }
24426
24427        @Override
24428        public void handleMessage(Message msg) {
24429            switch (msg.what) {
24430                case MSG_ON_PERMISSIONS_CHANGED: {
24431                    final int uid = msg.arg1;
24432                    handleOnPermissionsChanged(uid);
24433                } break;
24434            }
24435        }
24436
24437        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24438            mPermissionListeners.register(listener);
24439
24440        }
24441
24442        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24443            mPermissionListeners.unregister(listener);
24444        }
24445
24446        public void onPermissionsChanged(int uid) {
24447            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24448                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24449            }
24450        }
24451
24452        private void handleOnPermissionsChanged(int uid) {
24453            final int count = mPermissionListeners.beginBroadcast();
24454            try {
24455                for (int i = 0; i < count; i++) {
24456                    IOnPermissionsChangeListener callback = mPermissionListeners
24457                            .getBroadcastItem(i);
24458                    try {
24459                        callback.onPermissionsChanged(uid);
24460                    } catch (RemoteException e) {
24461                        Log.e(TAG, "Permission listener is dead", e);
24462                    }
24463                }
24464            } finally {
24465                mPermissionListeners.finishBroadcast();
24466            }
24467        }
24468    }
24469
24470    private class PackageManagerInternalImpl extends PackageManagerInternal {
24471        @Override
24472        public void setLocationPackagesProvider(PackagesProvider provider) {
24473            synchronized (mPackages) {
24474                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24475            }
24476        }
24477
24478        @Override
24479        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24480            synchronized (mPackages) {
24481                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24482            }
24483        }
24484
24485        @Override
24486        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24487            synchronized (mPackages) {
24488                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24489            }
24490        }
24491
24492        @Override
24493        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24494            synchronized (mPackages) {
24495                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24496            }
24497        }
24498
24499        @Override
24500        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24501            synchronized (mPackages) {
24502                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24503            }
24504        }
24505
24506        @Override
24507        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24508            synchronized (mPackages) {
24509                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24510            }
24511        }
24512
24513        @Override
24514        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24515            synchronized (mPackages) {
24516                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24517                        packageName, userId);
24518            }
24519        }
24520
24521        @Override
24522        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24523            synchronized (mPackages) {
24524                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24525                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24526                        packageName, userId);
24527            }
24528        }
24529
24530        @Override
24531        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24532            synchronized (mPackages) {
24533                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24534                        packageName, userId);
24535            }
24536        }
24537
24538        @Override
24539        public void setKeepUninstalledPackages(final List<String> packageList) {
24540            Preconditions.checkNotNull(packageList);
24541            List<String> removedFromList = null;
24542            synchronized (mPackages) {
24543                if (mKeepUninstalledPackages != null) {
24544                    final int packagesCount = mKeepUninstalledPackages.size();
24545                    for (int i = 0; i < packagesCount; i++) {
24546                        String oldPackage = mKeepUninstalledPackages.get(i);
24547                        if (packageList != null && packageList.contains(oldPackage)) {
24548                            continue;
24549                        }
24550                        if (removedFromList == null) {
24551                            removedFromList = new ArrayList<>();
24552                        }
24553                        removedFromList.add(oldPackage);
24554                    }
24555                }
24556                mKeepUninstalledPackages = new ArrayList<>(packageList);
24557                if (removedFromList != null) {
24558                    final int removedCount = removedFromList.size();
24559                    for (int i = 0; i < removedCount; i++) {
24560                        deletePackageIfUnusedLPr(removedFromList.get(i));
24561                    }
24562                }
24563            }
24564        }
24565
24566        @Override
24567        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24568            synchronized (mPackages) {
24569                // If we do not support permission review, done.
24570                if (!mPermissionReviewRequired) {
24571                    return false;
24572                }
24573
24574                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24575                if (packageSetting == null) {
24576                    return false;
24577                }
24578
24579                // Permission review applies only to apps not supporting the new permission model.
24580                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24581                    return false;
24582                }
24583
24584                // Legacy apps have the permission and get user consent on launch.
24585                PermissionsState permissionsState = packageSetting.getPermissionsState();
24586                return permissionsState.isPermissionReviewRequired(userId);
24587            }
24588        }
24589
24590        @Override
24591        public PackageInfo getPackageInfo(
24592                String packageName, int flags, int filterCallingUid, int userId) {
24593            return PackageManagerService.this
24594                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24595                            flags, filterCallingUid, userId);
24596        }
24597
24598        @Override
24599        public ApplicationInfo getApplicationInfo(
24600                String packageName, int flags, int filterCallingUid, int userId) {
24601            return PackageManagerService.this
24602                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24603        }
24604
24605        @Override
24606        public ActivityInfo getActivityInfo(
24607                ComponentName component, int flags, int filterCallingUid, int userId) {
24608            return PackageManagerService.this
24609                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24610        }
24611
24612        @Override
24613        public List<ResolveInfo> queryIntentActivities(
24614                Intent intent, int flags, int filterCallingUid, int userId) {
24615            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24616            return PackageManagerService.this
24617                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24618                            userId, false /*resolveForStart*/);
24619        }
24620
24621        @Override
24622        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24623                int userId) {
24624            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24625        }
24626
24627        @Override
24628        public void setDeviceAndProfileOwnerPackages(
24629                int deviceOwnerUserId, String deviceOwnerPackage,
24630                SparseArray<String> profileOwnerPackages) {
24631            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24632                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24633        }
24634
24635        @Override
24636        public boolean isPackageDataProtected(int userId, String packageName) {
24637            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24638        }
24639
24640        @Override
24641        public boolean isPackageEphemeral(int userId, String packageName) {
24642            synchronized (mPackages) {
24643                final PackageSetting ps = mSettings.mPackages.get(packageName);
24644                return ps != null ? ps.getInstantApp(userId) : false;
24645            }
24646        }
24647
24648        @Override
24649        public boolean wasPackageEverLaunched(String packageName, int userId) {
24650            synchronized (mPackages) {
24651                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24652            }
24653        }
24654
24655        @Override
24656        public void grantRuntimePermission(String packageName, String name, int userId,
24657                boolean overridePolicy) {
24658            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24659                    overridePolicy);
24660        }
24661
24662        @Override
24663        public void revokeRuntimePermission(String packageName, String name, int userId,
24664                boolean overridePolicy) {
24665            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24666                    overridePolicy);
24667        }
24668
24669        @Override
24670        public String getNameForUid(int uid) {
24671            return PackageManagerService.this.getNameForUid(uid);
24672        }
24673
24674        @Override
24675        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24676                Intent origIntent, String resolvedType, String callingPackage,
24677                Bundle verificationBundle, int userId) {
24678            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24679                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24680                    userId);
24681        }
24682
24683        @Override
24684        public void grantEphemeralAccess(int userId, Intent intent,
24685                int targetAppId, int ephemeralAppId) {
24686            synchronized (mPackages) {
24687                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24688                        targetAppId, ephemeralAppId);
24689            }
24690        }
24691
24692        @Override
24693        public boolean isInstantAppInstallerComponent(ComponentName component) {
24694            synchronized (mPackages) {
24695                return mInstantAppInstallerActivity != null
24696                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24697            }
24698        }
24699
24700        @Override
24701        public void pruneInstantApps() {
24702            mInstantAppRegistry.pruneInstantApps();
24703        }
24704
24705        @Override
24706        public String getSetupWizardPackageName() {
24707            return mSetupWizardPackage;
24708        }
24709
24710        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24711            if (policy != null) {
24712                mExternalSourcesPolicy = policy;
24713            }
24714        }
24715
24716        @Override
24717        public boolean isPackagePersistent(String packageName) {
24718            synchronized (mPackages) {
24719                PackageParser.Package pkg = mPackages.get(packageName);
24720                return pkg != null
24721                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24722                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24723                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24724                        : false;
24725            }
24726        }
24727
24728        @Override
24729        public List<PackageInfo> getOverlayPackages(int userId) {
24730            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24731            synchronized (mPackages) {
24732                for (PackageParser.Package p : mPackages.values()) {
24733                    if (p.mOverlayTarget != null) {
24734                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24735                        if (pkg != null) {
24736                            overlayPackages.add(pkg);
24737                        }
24738                    }
24739                }
24740            }
24741            return overlayPackages;
24742        }
24743
24744        @Override
24745        public List<String> getTargetPackageNames(int userId) {
24746            List<String> targetPackages = new ArrayList<>();
24747            synchronized (mPackages) {
24748                for (PackageParser.Package p : mPackages.values()) {
24749                    if (p.mOverlayTarget == null) {
24750                        targetPackages.add(p.packageName);
24751                    }
24752                }
24753            }
24754            return targetPackages;
24755        }
24756
24757        @Override
24758        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24759                @Nullable List<String> overlayPackageNames) {
24760            synchronized (mPackages) {
24761                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24762                    Slog.e(TAG, "failed to find package " + targetPackageName);
24763                    return false;
24764                }
24765                ArrayList<String> overlayPaths = null;
24766                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24767                    final int N = overlayPackageNames.size();
24768                    overlayPaths = new ArrayList<>(N);
24769                    for (int i = 0; i < N; i++) {
24770                        final String packageName = overlayPackageNames.get(i);
24771                        final PackageParser.Package pkg = mPackages.get(packageName);
24772                        if (pkg == null) {
24773                            Slog.e(TAG, "failed to find package " + packageName);
24774                            return false;
24775                        }
24776                        overlayPaths.add(pkg.baseCodePath);
24777                    }
24778                }
24779
24780                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24781                ps.setOverlayPaths(overlayPaths, userId);
24782                return true;
24783            }
24784        }
24785
24786        @Override
24787        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24788                int flags, int userId) {
24789            return resolveIntentInternal(
24790                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24791        }
24792
24793        @Override
24794        public ResolveInfo resolveService(Intent intent, String resolvedType,
24795                int flags, int userId, int callingUid) {
24796            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24797        }
24798
24799        @Override
24800        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24801            synchronized (mPackages) {
24802                mIsolatedOwners.put(isolatedUid, ownerUid);
24803            }
24804        }
24805
24806        @Override
24807        public void removeIsolatedUid(int isolatedUid) {
24808            synchronized (mPackages) {
24809                mIsolatedOwners.delete(isolatedUid);
24810            }
24811        }
24812
24813        @Override
24814        public int getUidTargetSdkVersion(int uid) {
24815            synchronized (mPackages) {
24816                return getUidTargetSdkVersionLockedLPr(uid);
24817            }
24818        }
24819
24820        @Override
24821        public boolean canAccessInstantApps(int callingUid, int userId) {
24822            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24823        }
24824    }
24825
24826    @Override
24827    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24828        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24829        synchronized (mPackages) {
24830            final long identity = Binder.clearCallingIdentity();
24831            try {
24832                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24833                        packageNames, userId);
24834            } finally {
24835                Binder.restoreCallingIdentity(identity);
24836            }
24837        }
24838    }
24839
24840    @Override
24841    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24842        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24843        synchronized (mPackages) {
24844            final long identity = Binder.clearCallingIdentity();
24845            try {
24846                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24847                        packageNames, userId);
24848            } finally {
24849                Binder.restoreCallingIdentity(identity);
24850            }
24851        }
24852    }
24853
24854    private static void enforceSystemOrPhoneCaller(String tag) {
24855        int callingUid = Binder.getCallingUid();
24856        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24857            throw new SecurityException(
24858                    "Cannot call " + tag + " from UID " + callingUid);
24859        }
24860    }
24861
24862    boolean isHistoricalPackageUsageAvailable() {
24863        return mPackageUsage.isHistoricalPackageUsageAvailable();
24864    }
24865
24866    /**
24867     * Return a <b>copy</b> of the collection of packages known to the package manager.
24868     * @return A copy of the values of mPackages.
24869     */
24870    Collection<PackageParser.Package> getPackages() {
24871        synchronized (mPackages) {
24872            return new ArrayList<>(mPackages.values());
24873        }
24874    }
24875
24876    /**
24877     * Logs process start information (including base APK hash) to the security log.
24878     * @hide
24879     */
24880    @Override
24881    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24882            String apkFile, int pid) {
24883        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24884            return;
24885        }
24886        if (!SecurityLog.isLoggingEnabled()) {
24887            return;
24888        }
24889        Bundle data = new Bundle();
24890        data.putLong("startTimestamp", System.currentTimeMillis());
24891        data.putString("processName", processName);
24892        data.putInt("uid", uid);
24893        data.putString("seinfo", seinfo);
24894        data.putString("apkFile", apkFile);
24895        data.putInt("pid", pid);
24896        Message msg = mProcessLoggingHandler.obtainMessage(
24897                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24898        msg.setData(data);
24899        mProcessLoggingHandler.sendMessage(msg);
24900    }
24901
24902    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24903        return mCompilerStats.getPackageStats(pkgName);
24904    }
24905
24906    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24907        return getOrCreateCompilerPackageStats(pkg.packageName);
24908    }
24909
24910    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24911        return mCompilerStats.getOrCreatePackageStats(pkgName);
24912    }
24913
24914    public void deleteCompilerPackageStats(String pkgName) {
24915        mCompilerStats.deletePackageStats(pkgName);
24916    }
24917
24918    @Override
24919    public int getInstallReason(String packageName, int userId) {
24920        final int callingUid = Binder.getCallingUid();
24921        enforceCrossUserPermission(callingUid, userId,
24922                true /* requireFullPermission */, false /* checkShell */,
24923                "get install reason");
24924        synchronized (mPackages) {
24925            final PackageSetting ps = mSettings.mPackages.get(packageName);
24926            if (filterAppAccessLPr(ps, callingUid, userId)) {
24927                return PackageManager.INSTALL_REASON_UNKNOWN;
24928            }
24929            if (ps != null) {
24930                return ps.getInstallReason(userId);
24931            }
24932        }
24933        return PackageManager.INSTALL_REASON_UNKNOWN;
24934    }
24935
24936    @Override
24937    public boolean canRequestPackageInstalls(String packageName, int userId) {
24938        return canRequestPackageInstallsInternal(packageName, 0, userId,
24939                true /* throwIfPermNotDeclared*/);
24940    }
24941
24942    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24943            boolean throwIfPermNotDeclared) {
24944        int callingUid = Binder.getCallingUid();
24945        int uid = getPackageUid(packageName, 0, userId);
24946        if (callingUid != uid && callingUid != Process.ROOT_UID
24947                && callingUid != Process.SYSTEM_UID) {
24948            throw new SecurityException(
24949                    "Caller uid " + callingUid + " does not own package " + packageName);
24950        }
24951        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24952        if (info == null) {
24953            return false;
24954        }
24955        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24956            return false;
24957        }
24958        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24959        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24960        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24961            if (throwIfPermNotDeclared) {
24962                throw new SecurityException("Need to declare " + appOpPermission
24963                        + " to call this api");
24964            } else {
24965                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24966                return false;
24967            }
24968        }
24969        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24970            return false;
24971        }
24972        if (mExternalSourcesPolicy != null) {
24973            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24974            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24975                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24976            }
24977        }
24978        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24979    }
24980
24981    @Override
24982    public ComponentName getInstantAppResolverSettingsComponent() {
24983        return mInstantAppResolverSettingsComponent;
24984    }
24985
24986    @Override
24987    public ComponentName getInstantAppInstallerComponent() {
24988        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24989            return null;
24990        }
24991        return mInstantAppInstallerActivity == null
24992                ? null : mInstantAppInstallerActivity.getComponentName();
24993    }
24994
24995    @Override
24996    public String getInstantAppAndroidId(String packageName, int userId) {
24997        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24998                "getInstantAppAndroidId");
24999        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25000                true /* requireFullPermission */, false /* checkShell */,
25001                "getInstantAppAndroidId");
25002        // Make sure the target is an Instant App.
25003        if (!isInstantApp(packageName, userId)) {
25004            return null;
25005        }
25006        synchronized (mPackages) {
25007            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25008        }
25009    }
25010}
25011
25012interface PackageSender {
25013    void sendPackageBroadcast(final String action, final String pkg,
25014        final Bundle extras, final int flags, final String targetPkg,
25015        final IIntentReceiver finishedReceiver, final int[] userIds);
25016    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25017        int appId, int... userIds);
25018}
25019